<?php

namespace App\Http\Controllers\H5;

use App\Facades\CommonService;
use App\Http\Controllers\Controller;
use App\Http\Resources\OrderUserInfoResource;
use App\Http\Resources\OrderUserInfoV1Resource;
use App\Http\Resources\UserInfoResource;
use App\Http\Resources\UserInfoV1Resource;
use App\Http\Response\ResponseJson;
use App\Jobs\SendTemplateNotice;
use App\Models\ApplyScanQrcode;
use App\Models\Group;
use App\Models\Guide;
use App\Models\GuideScheme;
use App\Models\InviteUser;
use App\Models\MedicalReport;
use App\Models\Message;
use App\Models\OrderMedicalReport;
use App\Models\OtherHealthFile;
use App\Models\Partner;
use App\Models\ScanQrcodeUser;
use App\Models\Order;
use App\Models\ServiceUser;
use App\Models\User;
use App\Models\UserInfo;
use App\Models\Wechat;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class IssueController extends Controller
{
    use ResponseJson;

    public function getIssueUserList(Request $request)
    {

        $page_size = $request->get('page_size', 15);
        $issue_list = Order::where('orders.is_hook', 1)->where('pay_status', 'PAID')
            ->leftjoin('user_infos as ui', 'ui.user_id', '=', 'orders.user_id')
            ->leftjoin('users', 'users.id', '=', 'orders.user_id')
            ->select('orders.user_id', 'orders.name', 'orders.created_at', 'ui.user_id','ui.stomach', 'ui.heart', 'ui.sleep', 'ui.immunity', 'ui.other', 'users.birthday','users.sex','users.body_images')
            ->orderByDesc('orders.id')
            ->paginate($page_size);
        foreach($issue_list as &$issue)
        {
            $symptom_get = [];
            $info =  User::STEP_TWO_INFO;
            $symptom_get = array_merge($symptom_get, $this->getIssueNameList($issue['stomach'], $info['step_two_info']['stomach']['ch_config']));
            $symptom_get = array_merge($symptom_get, $this->getIssueNameList($issue['heart'], $info['step_two_info']['heart']['ch_config']));
            $symptom_get = array_merge($symptom_get, $this->getIssueNameList($issue['sleep'], $info['step_two_info']['sleep']['ch_config']));
            // $symptom_get = array_merge($symptom_get, $this->getIssueNameList($issue['immunity'], $info['step_two_info']['immunity']['ch_config']));
            $symptom_get = array_merge($symptom_get, $this->getIssueNameList($issue['other'], $info['step_two_info']['other']['ch_config']));
            
            $issue['symptom_list'] = $symptom_get;
            $issue['image_before'] = $this->getIssueImageList($issue['body_images']);
            $issue['image_after'] = [];
            $birthyear = (explode('-', $issue['birthday']))[0];
            $issue['age'] = intval(date('Y')) - intval($birthyear?$birthyear:0);
            $issue['sex'] = $issue['sex'] == "1"?'男':'女';
            // $issue['name'] = substr_replace($issue['name'], '*', 1);
            $issue['name'] =  mb_substr($issue['name'], 0, 1, 'UTF-8').'**';
            unset($issue['stomach']);
            unset($issue['heart']);
            unset($issue['sleep']);
            unset($issue['immunity']);
            unset($issue['other']);
            unset($issue['birthday']);
            unset($issue['body_images']);
            
            
        }

        return $this->success('ok', $issue_list);
    }

    private function getIssueImageList($image_str)
    {
        $image_list = [];
        $image_array = json_decode($image_str?$image_str:'[]', 1);
        foreach($image_array as $image)
        {
            if(is_array($image))
            {
                foreach($image as $item)
                {   
                    if($item)
                    {
                        array_push($image_list, $item);
                    }
                }
            }else{

                if($image != '')
                {
                    array_push($image_list, $image);
                }
            }
        }
        return $image_list;
    }
    private function  getIssueNameList($answer_str, $option_list)
    {
        $name = [];
        $answer_list = json_decode($answer_str?$answer_str:'[]', true);
        if(count($answer_list) > 0)
        {
            foreach($option_list as $option)
            {
                foreach($answer_list as $answer)
                {
                    if ($answer['key']!= 'key1' && $answer['key'] == $option['key'])
                    {
                        array_push($name, $option['name']);
                    }
                }
            }
        }
        
        return $name;
    }
    public function healthInfo(Request $request)
    {
        $chat_id = $request->input('chat_id');
        if (empty($chat_id)) throw new \Exception("缺少参数群id");
//        $group = Group::with('order')->where('chat_id', $chat_id)->first();
        $group = $request->group;
        if (empty($group) || empty($group->order)) return $this->failure("缺少群信息或者订单信息");

        //增加营养素
        $schemes = [];
        $schemes_info = GuideScheme::where('order_id', $group->order->id)->first();
        if (!empty($schemes_info)) {
            $schemes = $schemes_info->scheme;
        }
        if (empty($group->order->user_id)) {
            if ($group->order->orderUserInfo) {
                $group->order->orderUserInfo->scheme = $schemes;
                //增加快递信息
                $group->order->orderUserInfo->delivery_name = $group->order->delivery_name;
                $group->order->orderUserInfo->delivery_number = $group->order->delivery_number;
                $group->order->orderUserInfo->delivery_type = $group->order->delivery_type;
            }
            $data = OrderUserInfoV1Resource::make($group->order->orderUserInfo);
        } else {
            $user_info = UserInfo::where('user_id', $group->order->user_id)->first();
            $user_info->scheme = $schemes;
            //增加快递信息
            $user_info->delivery_name = $group->order->delivery_name;
            $user_info->delivery_number = $group->order->delivery_number;
            $user_info->delivery_type = $group->order->delivery_type;
            $data = UserInfoV1Resource::make($user_info);
        }
        return $this->success('ok', $data);
    }

    public function healthReport(Request $request)
    {
        $chat_id = $request->input('chat_id');
//        $group = Group::with('order')->where('chat_id', $chat_id)->first();
        $group = $request->group;

        if (empty($group) || empty($group->order)) return $this->failure("缺少群信息或者订单信息");
        if (!empty($group->order->user_id)) {
            $before_reports = MedicalReport::where('user_id', $group->order->user_id)->where('type',MedicalReport::TYPE_BEFORE)->orderBYDesc('id')->get();
        } else {
            $before_reports = OrderMedicalReport::where('order_id', $group->order->id)->orderBYDesc('id')->get();
        }

        foreach ($before_reports as $report) {
            $report->content = json_decode($report->content);
            $report->body_images = json_decode($report->body_images);
        }
        $after_reports = MedicalReport::where('user_id', $group->order->user_id)->where('type',MedicalReport::TYPE_AFTER)->orderBYDesc('id')->get();
        foreach ($after_reports as $after_report) {
            $after_report->content = json_decode($after_report->content);
            $after_report->body_images = json_decode($after_report->body_images);
        }
//        return $this->success('ok',$reports);
        return $this->success('ok', compact('before_reports','after_reports'));
    }

    public function storeHealthReport(Request $request)
    {
        $order = $request->group->order;
        $medical_report = $request->medical_report;
        $anomaly_type = $request->anomaly_type ?: 1;
        $medical_date = $request->medical_date;
        $body_images = $request->body_images;
        $desc = $request->desc;
        $anomaly = $request->anomaly;
        $type = $request->type??0;
        if ($order->user) {
            MedicalReport::create(['user_id' => $order->user->id,'type'=>$type, 'content' => json_encode($medical_report), 'medical_date' => $medical_date, 'desc' => $desc, 'anomaly' => json_encode($anomaly), 'anomaly_type' => $anomaly_type,'body_images' => !empty($body_images) ? json_encode($body_images) : null]);

        } else {
            OrderMedicalReport::create([
                'order_id' => $order->id,
                'content' => json_encode($medical_report),
                'medical_date' => $medical_date,
                'desc' => $desc,
                'anomaly' => json_encode($anomaly),
                'anomaly_type' => $anomaly_type
            ]);
        }
        return $this->success('ok');
    }

    public function deleteHealthReport(Request $request, $report_id)
    {
        $order = $request->group->order;
        if ($order->user) {
            MedicalReport::where('id', $report_id)->delete();
        } else {
            OrderMedicalReport::where('id', $report_id)->delete();
        }
        return $this->success('ok');
    }

    /**
     * 添加报告
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function addOtherHealthFile(Request $request){
        try {
            $order = $request->group->order;
            $text = $request->input('text');
            $images = $request->input('images');
            $type = $request->input('type',MedicalReport::TYPE_BEFORE);
            if(is_array($images)){
                $images = json_encode($images);
            }
            $map = [];
            $map['user_id'] = $order->user->id;
            $map['text'] = $text;
            $map['type'] = $type;
            $map['images'] = $images;
            $res = OtherHealthFile::create($map);
            return $this->success('ok',$res);
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 获取补充列表
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getOtherHealthReport(Request $request){
        try{
            $order = $request->group->order;
            $before_reports = OtherHealthFile::where('user_id',$order->user_id)->where('type',MedicalReport::TYPE_BEFORE)->orderByDesc('id')->get();
            foreach ($before_reports as $item){
                $item->images = json_decode($item->images,true);
            }
            $after_reports = OtherHealthFile::where('user_id',$order->user_id)->where('type',MedicalReport::TYPE_AFTER)->orderByDesc('id')->select()->get();
            foreach ($after_reports as $value){
                $value->images = json_decode($value->images,true);
            }
//            return $this->success('ok',$before_list);
            return $this->success('ok',compact('before_reports','after_reports'));
        }catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 获取补充资料详情
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getOtherHealthFileDetail(Request $request){
        try{
            $id = $request->get('id');
            $detail = OtherHealthFile::where('id',$id)->first();
            $detail->images = json_decode($detail->images,true);
            return $this->success('ok',$detail);
        }catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 删除补充资料
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function deleteOtherHealthFile(Request $request){
        try {
            $id = $request->get('id');
            $res = OtherHealthFile::where('id',$id)->delete();
            return $this->success('ok',$res);
        }catch (\Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 内部服务状态
     * @param Request $request
     */
    public function userServiceStatus(Request $request)
    {
        $order = $request->group->order;
        $status = $order->service_status;
        $order_id = $order->trade_no ?? 0;
        $order_status = $order->status;

        $guide_info = Guide::where('user_id',$order->user_id)
            ->where('order_id',$order->id)
            ->where('status',Guide::STATUS_SCHEDULED)
            ->first();
        $start_date = date('Y-m-d');
        if($guide_info){
            $start_date = $guide_info->phase_date;
        }
        if($status == 'FINISHED'){
            $start_date = $order->updated_at;
        }
        // 转换为 Carbon 对象
        $givenDateTime = Carbon::parse($start_date);
        // 当前时间
        $now = Carbon::now();
        // 计算天数差
        $diffInDays = $givenDateTime->diffInDays($now);
        $scheme_date = $diffInDays+1;

        return $this->success('ok', compact('status', 'order_id','scheme_date','order_status'));
    }

    /**
     * 获取我的客户列表
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getInviteUser(Request $request)
    {
        try {
            $user = auth()->user();
            $page_size = $request->get('page_size', 15);
            $list = InviteUser::where('invite_user_id', $user->id)
                ->orderByDesc('id')
                ->paginate($page_size);;
            foreach ($list as $item) {
                $item->wx_name = '';
                $item->avatar = '';
                $user_info = User::where('id', $item->user_id)->first();
                if (!$user_info) {
                    continue;
                }
                $item->wx_name = $user_info->name;
                $item->avatar = $user_info->avatar;
                //获取申请记录
                $item->apply = ApplyScanQrcode::where('invite_user_id',$user->id)
                    ->where('user_id',$item->user_id)
                    ->select('date','id')->orderBy('date','asc')->limit(3)->get();
                $date = date('Y-m-d');
                foreach ($item->apply as $apply){
                    $apply->status = 0;
                    $exists = ScanQrcodeUser::where('user_id',$item->user_id)
                        ->where('created_at','like',$apply->date.'%')
                        ->exists();
                    if($exists){
                        $apply->status = 1;
                    }
                    if($apply->date < $date && !$exists){
                        $apply->status = 2;
                    }

                }
            }
            return $this->success('ok', $list);
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 获取某个用户的申请记录
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getApplyList(Request $request){
        try {
            $invite_user = auth()->user();
            $user_id = $request->get('user_id');
            $list = ApplyScanQrcode::where('invite_user_id',$invite_user->id)
                ->where('user_id',$user_id)
                ->orderBy('date','asc')
                ->paginate();
            return $this->success('ok',$list);
        }catch (Exception $e) {
            Log::error('getApplyList:'.$e->getMessage());
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 填写邀请客户信息
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function updateInviteUserInfo(Request $request)
    {
        try {
            $id = $request->get('id');
            if (empty($id)) {
                return $this->failure('id不为空');
            }
            $name = $request->get('name', '');
            $mobile = $request->get('mobile', '');
            $res = InviteUser::where('id', $id)->update(['name' => $name, 'mobile' => $mobile]);
            return $this->success('ok', $res);
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 扫码签到
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function userScanQrcode(Request $request)
    {
        try {
            $user = Auth()->user();
            $user_info = User::where('id', $user->id)->first();
            if (!$user_info) {
                return $this->failure('用户信息不存在');
            }
            //查看用户当前是否已签到
            // 获取今天零点的时间戳
            $today_start = strtotime('today');
            // 获取明天零点的时间戳
            $tomorrow_start = $today_start + 86400;
            // 格式化时间戳为日期时间字符串
            $start_time = date('Y-m-d H:i:s', $today_start);
            $end_time = date('Y-m-d H:i:s', $tomorrow_start);
            $exists = ScanQrcodeUser::where('user_id', $user->id)->whereBetween('created_at', [$start_time, $end_time])->exists();
            if ($exists) {
                $msg_status = true;
                return $this->success('ok',compact('msg_status'));
            }
            //查看用户类型
            $type = 3;
            $real_name = $user_info->name;
            $mobile = $user_info->mobile;
            $avatar = $user_info->avatar;
            $service_user = Partner::where('user_id', $user->id)->first();
            $agent = $user->isAgent();
            if($agent){
                $type = 1;
            }
            if ($service_user) {
                $type = 1;
                $real_name = $service_user->name;
                $mobile = $service_user->mobile;
                $avatar = $service_user->pic;
            }

            $invite_user = InviteUser::where('user_id', $user->id)->first();
            if ($invite_user) {
                $type = 2;
                $real_name = $invite_user->name;
                $mobile = $invite_user->mobile;
            }
            $map = [];
            $map['user_id'] = $user->id;
            $map['nickname'] = $user_info->name;
            $map['real_name'] = $real_name;
            $map['avatar'] = $avatar;
            $map['mobile'] = $mobile;
            $map['type'] = $type;
            $res = ScanQrcodeUser::create($map);

            $flag = false;
            if ($type == 3) {
                $flag = true;
            }

            //查看是否有帮忙申请扫码
            $date = date('Y-m-d');
            $apply_info = ApplyScanQrcode::where('date',$date)->where('user_id',$user->id)->get();
            foreach ($apply_info as $apply){
                $open_id = Wechat::where('user_id',$apply->invite_user_id)->where('type','official')->value('openid');
                //查找填写的用户名
                $name = InviteUser::where('invite_user_id',$apply->invite_user_id)->where('user_id',$apply->user_id)->value('name');
                $send_name = $name??'未填写名字';
                //发送模板消息
                if($open_id){
                    $params = [
                        'touser'=>$open_id,
                        'template_id'=>config('wechat.tpls.user_scan_qrcode'),
                        'data'=>[
                            'thing2' => ['value'=>$send_name],
                            'thing3' => ['value'=>'友福同享'],
                            'time5' => ['value'=>date('Y-m-d H:i:s')],
                        ]
                    ];
                    SendTemplateNotice::dispatch($params)->onQueue('health');
                }
            }

            return $this->success('ok', compact('res','flag'));
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }


    /**
     * 获取扫码签到列表
     * @param Request $request
     */
    public function getScanLog(Request $request)
    {
        try {
            $date = $request->input('date');
            if (empty($date)) {
                return $this->failure('时间不为空');
            }
            $user = Auth()->user();
            $start_date = date('Y-m-01', strtotime($date));
            $end_date = date('Y-m-d', strtotime("$start_date + 1 month -1 day"));
            $dailies = CommonService::daliy($start_date, $end_date);
            $date_arr = [];
            foreach ($dailies as $daily) {
                $start_day_time = strtotime($daily);
                $end_day_time = $start_day_time + 86400;
                $start_time = date('Y-m-d H:i:s', $start_day_time);
                $end_time = date('Y-m-d H:i:s', $end_day_time);
                $exists = ScanQrcodeUser::where('user_id', $user->id)->whereBetween('created_at', [$start_time, $end_time])->exists();
                $status = 0;
                if ($exists) {
                    $status = 1;
                }
                $date_arr[] = $status;
            }
            return $this->success('ok', $date_arr);
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 给用户预约签到
     * @param Request $request
     */
    public function applyUserScanQrcode(Request $request){
        try {
            $invite_user = Auth()->user();
            $user_id = $request->input('user_id');
            $date = $request->input('date');

            if(empty($date) || empty($user_id)){
                return $this->failure('用户和日期不为空');
            }
            //查看这个用户这个日期是否邀请过
            $exists = ApplyScanQrcode::where('invite_user_id',$invite_user->id)->where('date',$date)->where('user_id',$user_id)->exists();
            if($exists){
                return $this->failure('用户该日期已预约');
            }
            $map = [
                'invite_user_id'=>$invite_user->id,
                'date'=>$date,
                'user_id'=>$user_id
            ];
            $model = ApplyScanQrcode::create($map);
            return $this->success('ok',$model);
        }catch (Exception $e) {
            Log::error('applyUserScanQrcode:'.$e->getMessage());
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 取消预约
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function deleteApplyLog(Request $request){
        try {
            $id = $request->get('id');
            if(empty($id)) return $this->failure('id不为空');

            $res = ApplyScanQrcode::where('id',$id)->delete();
            return $this->success('ok',$res);
        }catch (Exception $e) {
            Log::error('deleteApplyLog:'.$e->getMessage());
            return $this->jsonResponse(1, $e->getMessage());
        }
    }


}
