<?php

namespace App\Http\Controllers\H5;

use App\Facades\UserService;
use App\Http\Controllers\Controller;
use App\Http\Resources\OrderUserInfoResource;
use App\Http\Resources\UserInfoResource;
use App\Http\Response\ResponseJson;
use App\Jobs\SyncOrderServiceStatus;
use App\Jobs\TempToServiceOrder;
use App\Models\DmaProcessLog;
use App\Models\Group;
use App\Models\MedicalReport;
use App\Models\Order;
use App\Models\OrderMedicalReport;
use App\Models\OrderUserInfo;
use App\Models\OtherHealthFile;
use App\Models\User;
use App\Models\UserInfo;
use App\Services\ConfigService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserInfoController extends Controller
{
    use ResponseJson;

    public function serviceStatus(Request $request)
    {
        $status = "NOORDER";
        $chat_id = $request->input('chat_id');
        if (empty($chat_id))
            throw new \Exception("缺少群id");
        Log::info("餐单状态群id---$chat_id");

        //        $group = Group::with('order.user')->where('chat_id', $chat_id)->first();
        $group = $request->group;

        if ($group->service_type == 1) {
            if (empty($group->order->user)) {
                $is_user_info = 0;
                return $this->success('ok', compact('status', 'is_user_info'));
            }
            $order = $group->order;
            if ($order) {
                $status = $order->status;
            }
            $user = $group->order->user;
            //信息是否完善
            $user_info = $user->userInfo;
            $res1 = UserService::checkUserInfo($user, $user_info);
            //自述症状
            $res2 = UserService::checkSymptoms($user_info);
            $is_user_info = ($res1 && $res2) ? 1 : 0;
            Log::info($status);
        }

        return $this->success('ok', compact('status', 'is_user_info'));
    }

    public function updateHealthInfo(Request $request)
    {
        // 暂时关闭教练端修改用户信息
        // if (auth()->id() != 1 && auth()->id() != 152) {
        //     return $this->success("ok");
        // }
        $order = $request->group->order;
        DB::beginTransaction();
        $user_data = $info_data = [];
        $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);
        } else {
            $body_images = json_decode($order->user->body_images, true);
            $body_front = $request->input("body_front");
            if ($body_front) {
                $body_images["bodyFront"] = $body_front;
            }
            $body_profile = $request->input("body_profile");
            if ($body_profile) {
                $body_images["bodyProfile"] = $body_profile;
            }
            $big_head = $request->input("big_head");
            if ($big_head) {
                $body_images["bigHead"] = $big_head;
            }
            $left_palm = $request->input("left_palm");
            if ($left_palm) {
                $body_images["leftPalm"] = $left_palm;
            }
            $right_palm = $request->input("right_palm");
            if ($right_palm) {
                $body_images["rightPalm"] = $right_palm;
            }
            $tongue = $request->input("tongue");
            if ($tongue) {
                $body_images["tongue"] = $tongue;
            }
            $other_img = $request->input("other_img");
            if (is_array($other_img)) {
                $body_images["other_img"] = $other_img;
            }

            if ($body_images) {
                $user_data['body_images'] = json_encode($body_images);
            }
        }

        $after_body_images = $request->input('after_body_images');
        if (is_array($after_body_images)) {
            $user_data['after_body_images'] = json_encode($after_body_images);
        } else {
            $after_body_images = json_decode($order->user->after_body_images, true);
            $after_body_front = $request->input("after_body_front");
            if ($after_body_front) {
                $after_body_images["bodyFront"] = $after_body_front;
            }
            $after_body_profile = $request->input("after_body_profile");
            if ($after_body_profile) {
                $after_body_images["bodyProfile"] = $after_body_profile;
            }
            $after_big_head = $request->input("after_big_head");
            if ($after_big_head) {
                $after_body_images["bigHead"] = $after_big_head;
            }
            $after_left_palm = $request->input("after_left_palm");
            if ($after_left_palm) {
                $after_body_images["leftPalm"] = $after_left_palm;
            }
            $after_right_palm = $request->input("after_right_palm");
            if ($after_right_palm) {
                $after_body_images["rightPalm"] = $after_right_palm;
            }
            $after_tongue = $request->input("after_tongue");
            if ($after_tongue) {
                $after_body_images["tongue"] = $after_tongue;
            }
            $after_other_img = $request->input("after_other_img");
            if (is_array($after_other_img)) {
                $after_body_images["other_img"] = $after_other_img;
            }

            if ($after_body_images) {
                $user_data['after_body_images'] = json_encode($after_body_images);

                if ($order) {
                    DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "upload_after_body_image", "帮用户上传【方案后身体照】", auth()->id());
                }
            }
        }


        $weight = $request->input('weight');
        if ($weight) {
            $info_data['weight'] = $weight;
        }
        $address = $request->input('address');
        if ($address) {
            $info_data['address'] = $address;
        }
        $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);
        }
        $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');
        }
        $vegan = $request->input('vegan');
        if (is_numeric($vegan)) {
            $info_data['vegan'] = $vegan;
        }
        $egg = $request->input('egg');
        if (is_numeric($egg)) {
            $info_data['egg'] = $egg;
        }
        $woman = $request->input('woman');
        if (is_array($woman)) {
            $info_data['woman'] = json_encode($woman);
        }
        if ($order->user) {
            //修改当前用户信息
            $order->user->update($user_data);
            $order->user->userInfo->update($info_data);
        } else {
            OrderUserInfo::updateOrCreate(['order_id' => $order->id], array_merge($user_data, $info_data));
        }
        //检查是否完善资料
//        SyncOrderServiceStatus::dispatch($order->user)->onQueue('health');
        DB::commit();
        return $this->success('ok');
    }

    public function getStepConfig(Order $order)
    {
        $user = $order->user;
        $configService = new ConfigService();
        $res = $configService->stepConfig($user);
        if (!$res['status']) {
            return $this->failure($res['msg']);
        }
        return $this->success('ok', $res['data'] ?? []);
    }

    public function orderHeathInfo(Request $request, Order $order)
    {
        $user = $order->user;
        if (empty($user)) {
            //没有用户信息
            $data = OrderUserInfoResource::make($order->orderUserInfo);
            return $this->success('ok', $data);
        } else {
            $data = UserInfoResource::make($user->userInfo);
            return $this->success('ok', $data);
        }
    }

    public function orderHealthReports(Request $request, Order $order)
    {
        $user = $order->user;
        $after_reports = [];
        if (empty($user)) {
            $before_reports = $order->orderMedicalReports()->orderBy('id', 'desc')->get();
        } else {
            $before_reports = MedicalReport::where('user_id', $user->id)->where('type', MedicalReport::TYPE_BEFORE)->orderBYDesc('id')->get();
            $after_reports = MedicalReport::where('user_id', $user->id)->where('type', MedicalReport::TYPE_AFTER)->orderBYDesc('id')->get();
        }

        foreach ($before_reports as $report) {
            $report->content = json_decode($report->content);
            $report->body_images = json_decode($report->body_images);
        }

        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'));
    }

    /**
     * 获取补充列表
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getOtherHealthReport(Request $request, Order $order)
    {
        try {
            $user = $order->user;
            $before_reports = $after_reports = [];
            if (!empty($user)) {
                $before_reports = OtherHealthFile::where('user_id', $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', $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) {
            Log::error('getOtherHealthReport:' . $e->getMessage());
            return $this->jsonResponse(1, $e->getMessage());
        }
    }
}
