<?php

namespace App\Http\Controllers;

use App\Facades\UserService;
use App\Http\Resources\OrderUserInfoResource;
use App\Http\Resources\UserInfoResource;
use App\Http\Response\ResponseJson;
use App\Jobs\AsynHttp;
use App\Jobs\MakeGuide;
use App\Jobs\MakeNutrient;
use App\Jobs\SyncOrderServiceStatus;
use App\Jobs\TempToServiceOrder;
use App\Models\Group;
use App\Models\MedicalReport;
use App\Models\OfflineOrder;
use App\Models\Order;
use App\Models\OtherHealthFile;
use App\Models\User;
use App\Models\UserInfo;
use App\Services\ImService;
use App\Services\OfflineOrderService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserInfoController extends Controller
{
    use ResponseJson;

    public function healthInfo(Request $request)
    {
        $chat_id = $request->input('chat_id');
//        $chat_id = 3;
        if (empty($chat_id)) {//正常小程序查看个人信息
            $user_info = UserInfo::firstOrCreate(['user_id' => auth()->id()]);
            $data = UserInfoResource::make($user_info);
            return $this->success('ok', $data);
        } else {
            //群订单是否绑定用户
            $order = Order::whereHas('group', function ($sql) use ($chat_id) {
                $sql->where("chat_id", $chat_id);
            })->first();
            if (empty($order) || $order->user_id) {
                $user_info = UserInfo::firstOrCreate(['user_id' => auth()->id()]);
                $data = UserInfoResource::make($user_info);
                return $this->success('ok', $data);
            } elseif (empty($order->user_id)) {
                //订单未绑定用户
                $data = OrderUserInfoResource::make($order->orderUserInfo);
                return $this->success('ok', $data);
            }
        }
    }

    public function updateHealthInfo(Request $request)
    {
        $name = $request->input('name');
        if ($name) {
            $user_data['name'] = $name;
        }
        $sex = $request->input('sex');
        if ($sex) {
            $user_data['sex'] = $sex;
        }
        $birthday = $request->input('birthday');
        if ($birthday) {
            $user_data['birthday'] = $birthday;
        }
        $stature = $request->input('stature');
        if ($stature) {
            $user_data['stature'] = $stature;
        }
        $body_images = $request->input('body_images');
        if(is_array($body_images)) {
            $user_data['body_images'] = json_encode($body_images);
        }
        $address = $request->input('address');
        if ($address) {
            $info_data['address'] = $address;
        }
        $weight = $request->input('weight');
        if ($weight) {
            $info_data['weight'] = $weight;
        }
        $vegan = $request->input('vegan');
        if (is_numeric($vegan)) {
            $info_data['vegan'] = $vegan;
        }
        $egg = $request->input('egg');
        if (is_numeric($egg)) {
            $info_data['egg'] = $egg;
        }
        $stomach = $request->input('stomach');
        if (is_array($stomach)) {
            $info_data['stomach'] = json_encode($stomach);
        }
        $heart = $request->input('heart');
        if (is_array($heart)) {
            $info_data['heart'] = json_encode($heart);
        }
        $sleep = $request->input('sleep');
        if (is_array($sleep)) {
            $info_data['sleep'] = json_encode($sleep);
        }
        $immunity = $request->input('immunity');
        if (is_array($immunity)) {
            $info_data['immunity'] = json_encode($immunity);
        }
        $woman = $request->input('woman');
        if (is_array($woman)) {
            $info_data['woman'] = json_encode($woman);
        }
        $man = $request->input('man');
        if (is_array($man)) {
            $info_data['man'] = json_encode($man);
        }
        $other = $request->input('other');
        if (is_array($other)) {
            $info_data['other'] = json_encode($other);
        }
        $dietary = $request->input('dietary');
        if (is_array($dietary)) {
            $info_data['dietary'] = json_encode($dietary);
        }
        $living = $request->input('living');
        if (is_array($living)) {
            $info_data['living'] = json_encode($living);
        }
        $mental = $request->input('mental');
        if (is_array($mental)) {
            $info_data['mental'] = json_encode($mental);
        }
        $family = $request->input('family');
        if (is_array($family)) {
            $info_data['family'] = json_encode($family);
        }
        $family_member = $request->input('family_member');
        if (is_array($family_member)) {
            $info_data['family_member'] = json_encode($family_member);
        }
        $personal = $request->input('personal');
        if (is_array($personal)) {
            $info_data['personal'] = json_encode($personal);
        }
        $know = $request->input('know');
        if (is_array($know)) {
            $info_data['know'] = json_encode($know);
        }
        $understand = $request->input('understand');
        if (is_array($understand)) {
            $info_data['understand'] = json_encode($understand);
        }
        $really = $request->input('really');
        if (is_array($really)) {
            $info_data['really'] = json_encode($really);
        }
        $duty = $request->input('duty');
        if (is_array($duty)) {
            $info_data['duty'] = json_encode($duty);
        }
        $surgery = $request->input('surgery');
        if (is_array($surgery)) {
            $info_data['surgery'] = json_encode($surgery);
        }
        $medication = $request->input('medication');
        if (is_array($medication)) {
            $info_data['medication'] = json_encode($medication);
        }
        $allergies = $request->input('allergies');
        if (is_array($allergies)) {
            $info_data['allergies'] = json_encode($allergies);
        }
        $health_server = $request->input('health_server');
        if (is_array($health_server)) {
            $info_data['health_server'] = json_encode($health_server);
        }
        if ($request->has('desc')) {
            $info_data['desc'] = $request->input('desc');
        }

        $user = auth()->user();

        $mobile = $request->input('mobile');
        //如果手机号已经被绑定,提示信息
         if($mobile){
//             $mobileInfo = User::where('mobile',$mobile)->first();
//             if($mobileInfo && ($mobileInfo->id != $user->id)){
//                 return $this->failure('该手机号已被绑定');
//             }
             $is_exists = User::where("mobile",$mobile)->where('source', User::SOURCE_APP)->first();
             if($is_exists){
                 $user = User::updateAppUser($mobile,$user->id);
             }else{
                 $user_data['mobile'] = $mobile;
             }
//             if(empty($user->mobile)){
//                 $user_data['mobile'] = $mobile;
//             }
         }
        if ($request->has('desc')) {
            $info_data['desc'] = $request->input('desc');
        }
        //事务处理
//        try {
            DB::beginTransaction();

            // 在事务中执行的代码
            if (isset($user_data)) User::where('id', $user->id)->update($user_data);
            if (isset($info_data)) UserInfo::where('user_id', $user->id)->update($info_data);

            //如果存在群组id则需要处理以下逻辑
            $chat_id = $request->input('chat_id');
            if (!empty($chat_id)) {
                $this->bindOrder($user->id, $chat_id);
            }
            //占位订单TEMP转为虚拟订单SERVICE

            Log::info("群id---" . $request->chat_id);
            TempToServiceOrder::dispatch($user, $request->chat_id)->onQueue('health');

            DB::commit(); // 提交事务
//        } catch (\Exception $e) {
//            DB::rollBack(); // 回滚事务
//        }
        $user = User::where('id',$user->id)->first();
        $create_offline_order = $request->input('create_offline_order');
        if(!empty($create_offline_order) && empty($chat_id)){
            $offline_order_exists = OfflineOrder::where('contract_no',$user->mobile)->exists();
            if($offline_order_exists){
                return $this->failure("合同号已存在");
            }
            $order_exists = Order::getPayOrder($user->id);
            if(empty($order_exists)){
                $data = [];
                $data['name'] = $user->name;
                $data['price'] = Order::ORDER_PRICE;
                $data['mobile'] = $user->mobile;
                $data['chat_id'] = $chat_id;
                $OfflineOrderService = new OfflineOrderService();
                $OfflineOrderService->createOfflineOrder($data,$user->id);
            }
        }
        //更新网易云信数据
        $imService = new ImService();
        $imService->updateImUser($user->id,$user);

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


    /**
     * 处理订单逻辑
     * 1.如果群组关联的订单未绑定用户,则跟用户绑定
     * 2.如果用户产生了订单,但是订单未关联群,则将订单和群关联
     * 3.如果群组关联的订单已经和其他用户绑定,只更新资料,并加个日志记录该群已经和哪个用户绑定了,也记录当前想要绑定的用户id
     * 4.如果群组表未查询到群组信息,则创建order记录,offline_order记录,groups表记录,并将用户和订单绑定
     * @param $user
     * @param $chat_id
     */
    public function bindOrder($user_id, $chat_id=null)
    {
        $user = User::where('id',$user_id)->first();
        //查看群是否存在,如果存在则绑定用户
        $groupInfo = Group::select('chat_id', 'order_id')->where('chat_id', $chat_id)->first();
        //查看是否有角色
        $OfflineOrderService = new OfflineOrderService();
        if (!empty($groupInfo)) {
            $orderInfo = Order::select('user_id')->where('id', $groupInfo->order_id)->first();
            //如果未绑定用户,则去绑定用户
            if ($orderInfo->user_id == 0) {
                Order::where('id', $groupInfo->order_id)->update(['user_id' => $user->id]);
                $OfflineOrderService->insertRoleData($chat_id,$orderInfo->user_id);
            } else {
                Log::info('绑定订单:提示信息:订单' . $groupInfo->order_id . '已被用户id:' . $orderInfo->user_id . '绑定,当前用户id:' . $user->id . '无需额外操作');
            }
        } else {
            //创建线下订单时用户姓名和手机号不为空
            if(!empty($user->name) && !empty($user->mobile)){
                //没有群信息,插入新订单,线下订单,和群组记录
                $data = [];
                $data['name'] = $user->name;
                $data['price'] = Order::ORDER_PRICE;
                $data['mobile'] = $user->mobile;
                $data['chat_id'] = $chat_id;
                $OfflineOrderService = new OfflineOrderService();

                //查看用户订单是否存在,存在则绑定群id
                $order = Order::where('user_id',$user_id)->orderBYDesc('id')->first();
                if($order){
                    $group = Group::where('order_id', $order->id)->first();
                    if(empty($group->chat_id)){
                        Group::where('id',$group->id)->update(['chat_id'=>$chat_id]);
                        $OfflineOrderService->insertRoleData($chat_id,$order->id);
                    }else{
                        $OfflineOrderService->createOfflineOrder($data);
                    }
                }else{
                    $OfflineOrderService->createOfflineOrder($data);
                }
            }
        }
    }

    public function healthReport(Request $request)
    {
        $user_id = auth()->id();
        $user_info = UserInfo::firstOrCreate(['user_id' => $user_id]);
        $user_info = UserInfoResource::make($user_info)->toArray($request);
        $reports = MedicalReport::where('user_id', $user_id)->orderBYDesc('id')->get();
        foreach ($reports as $report) {
            $report->content = json_decode($report->content);
            $report->body_images = json_decode($report->body_images);
        }

        $data = [
            'medical_report' => $reports,
            'anomaly' => $user_info['anomaly'],
        ];
        return $this->success('ok', $data);
    }

    public function healthReportV2(Request $request)
    {
        $user_id = auth()->id();
        $before_reports = MedicalReport::where('user_id', $user_id)->where('type',MedicalReport::TYPE_BEFORE)->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', $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',$before_reports);
        return $this->success('ok', compact('before_reports','after_reports'));
    }


    public function updateHealthReport(Request $request)
    {
        $user_id = auth()->id();
        $medical_report = $request->input('medical_report');
        $medical_date = $request->input('medical_date');
        $desc = $request->input('desc');
        $type = $request->get('type',MedicalReport::TYPE_BEFORE);
        if (is_array($medical_report)) {
            $medical_report = json_encode($medical_report);
            MedicalReport::create(['user_id' => $user_id, 'type'=>$type,'content' => $medical_report, 'medical_date' => $medical_date, 'desc' => $desc]);
        }
        $anomaly = $request->input('anomaly');
        if (is_array($anomaly)) {
            $info_data['anomaly'] = json_encode($anomaly ?: []);
            UserInfo::where('user_id', $user_id)->where('type',$type)->update($info_data);
        }
        return $this->success('ok');
    }

    public function storeHealthReport(Request $request)
    {
        $user_id = auth()->id();
        $medical_report = $request->input('medical_report');
        $medical_date = $request->input('medical_date');
        $body_images = $request->input('body_images');
        $desc = $request->input('desc');
        $anomaly = $request->input('anomaly', []);
        //检测类型
        $anomaly_type = $request->input('anomaly_type', 1);

        $type = $request->input('type', MedicalReport::TYPE_BEFORE);
        if (is_array($medical_report)) {
            $medical_report = json_encode($medical_report);
            if(is_array($body_images)){
                $body_images = json_encode($body_images);
            }
            $anomaly = json_encode($anomaly);
            MedicalReport::create(['user_id' => $user_id, 'type'=>$type,'content' => $medical_report, 'medical_date' => $medical_date, 'desc' => $desc, 'anomaly' => $anomaly, 'anomaly_type' => $anomaly_type,'body_images' => !empty($body_images) ? $body_images : null]);
        }
        if ($anomaly_type == 2) {//触发扫描
//            AsynHttp::dispatch('get', 'http://192.168.1.201:5000/ai')->onQueue('health');
        }
        return $this->success('ok');
    }

    public function deleteHealthReport(Request $request, $report_id)
    {
        MedicalReport::where('id', $report_id)->where('user_id', auth()->id())->delete();
        return $this->success('ok');
    }

    public function serviceStatus(Request $request)
    {
        $user = auth()->user();
        $status = "NOORDER";
        $order = $user->payOrders()->whereIn('status', ['NOTSTART', 'STARTING', 'FINISHED'])->orderByDesc('id')->first();
        if ($order) {
            $status = $order->status;
        }
        //信息是否完善
        $user_info = $user->userInfo;
        $res1 = UserService::checkUserInfo($user, $user_info);
        //自述症状
        $res2 = UserService::checkSymptoms($user_info);
        $is_user_info = ($res1 && $res2) ? 1 : 0;
        return $this->success('ok', compact('status', 'is_user_info'));
    }

    public function makeNutrient(Request $request)
    {
        $user = auth()->user();
        $user_info = $user->userInfo;
        if ($user_info->nutrient) return $this->success('已生成');
        //检查信息 个人信息，症状自诉，体检报告;
        $res = UserService::checkUserInfo($user, $user_info);
        if (empty($res)) return $this->success('缺少个人信息');
        //自述症状
        $res = UserService::checkSymptoms($user_info);
        if (empty($res)) return $this->success('缺少自述症状');
        //体检报告
        $res = $user->medicalReports()->count();
        if (empty($res)) return $this->success('缺少体检报告');
        //生成餐单 第三方
        if (config('app.env') == 'production') {
            $this->httpMakeNutrient($user);
        } else {
            $this->httpMakeNutrientTest($user_info);
        }
        return $this->success('ok');
    }

    public function httpMakeNutrient($user)
    {
        MakeNutrient::dispatch($user)->onQueue('health');
    }

    public function httpMakeNutrientTest($user_info)
    {
        $nutrient = [
            [
                "title" => "水煮蛋",
                "unit" => "个",
                "number" => 1,
                "pic" => "https://hbimg.b0.upaiyun.com/62620088daaf8b47e66f8b843e7641de2a4075a43bdf3-brWb6h_fw658"
            ], [
                "title" => "茶叶蛋",
                "unit" => "个",
                "number" => 1,
                "pic" => "https://hbimg.b0.upaiyun.com/62620088daaf8b47e66f8b843e7641de2a4075a43bdf3-brWb6h_fw658"
            ], [
                "title" => "水煮蛋",
                "unit" => "个",
                "number" => 1,
                "pic" => "https://hbimg.b0.upaiyun.com/62620088daaf8b47e66f8b843e7641de2a4075a43bdf3-brWb6h_fw658"
            ], [
                "title" => "茶叶蛋",
                "unit" => "个",
                "number" => 1,
                "pic" => "https://hbimg.b0.upaiyun.com/62620088daaf8b47e66f8b843e7641de2a4075a43bdf3-brWb6h_fw658"
            ]
        ];
        $user_info->nutrient = $nutrient;
        $user_info->save();
    }

    /**
     * 上传报告添加补充资料
     * @param Request $request
     */
    public function addOtherHealthFile(Request $request){
        try {
            $user_id = auth()->id();
            $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'] = $user_id;
            $map['text'] = $text;
            $map['images'] = $images;
            $map['type'] = $type;
            OtherHealthFile::create($map);
            return $this->success('ok',$map);
        } 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 getOtherHealthFileList(Request $request){
        try {
            $user_id = auth()->id();
            $before_reports = OtherHealthFile::where('user_id',$user_id)->where('type',MedicalReport::TYPE_BEFORE)->orderByDesc('id')->select()->get();
            foreach ($before_reports as $item){
                $item->images = json_decode($item->images,true);
            }
            $after_reports = OtherHealthFile::where('user_id',$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 deleteUserInfoByMobile(Request $request){
        $mobile = $request->input('mobile');
        $sign = $request->input('sign');
        if(empty($sign) || empty($mobile)){
            return $this->failure('操作失败');
        }
        //调用接口验证sign值,增加安全性,避免接口暴露被恶意删除用户数据
        if($sign != 'YdO!D^nrBMdRMyMaWZ4eX4$1'){
            return $this->failure('操作失败');
        }
        $res = User::where('mobile',$mobile)->delete();
        if($res){
            return $this->success('ok');
        }
        return $this->failure('操作失败');
    }
}
