<?php

namespace App\Http\Controllers\Admin;

use App\Events\OperationLoggedEvent;
use App\Facades\CommonService;
use App\Facades\UserService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\MakeGuide;
use App\Models\DmaProcess;
use App\Models\Food;
use App\Models\Guide;
use App\Models\GuideTemplate;
use App\Models\Order;
use App\Models\User;
use App\Services\ChatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use function PHPUnit\Framework\isNull;

class GuideController extends Controller
{
    use ResponseJson;

    public function orderGuides(Request $request, Order $order)
    {
        $guides = $order->guides();
        $keyword = $request->input('keyword');
        if ($keyword) {
            $keyword = trim($keyword);
            $guides = $guides->where(function ($sql) use($keyword) {
                $sql->where('phase_title', 'like', '%'.$keyword.'%');
            });
        }
        $guides = $guides->paginate();
        foreach ($guides as $guide)
        {
            $guide->hint = json_decode($guide->hint);
            $guide->menu = $menus = json_decode($guide->menu);
            $guide->price = 0;
            foreach ($menus as $menu) {
                foreach ($menu->nutrient as $item) {
                    if(!isset($item->price)){
                        continue;
                    }
                    $guide->price += get_two_float($item->number*$item->price,2);
                }
            }
            $guide->price = get_two_float($guide->price,2);
        }
        return $this->success('ok', $guides);
    }

    public function userGuides(Request $request, User $user)
    {
        $order = $user->payOrders()->first();
        $order_id = $order?$order->id:null;
        $guides = Guide::where('order_id', $order_id);
        $keyword = $request->input('keyword');
        if ($keyword) {
            $keyword = trim($keyword);
            $guides = $guides->where(function ($sql) use($keyword) {
                $sql->where('phase_title', 'like', '%'.$keyword.'%');
            });
        }
        $guides = $guides->paginate();
        foreach ($guides as $guide)
        {
            $guide->hint = json_decode($guide->hint);
            $guide->menu = json_decode($guide->menu);
        }
        return $this->success('ok', $guides);
    }

    public function orderGuide(Request $request, Guide $guide)
    {
        $guide->menu = json_decode($guide->menu);
        return $this->success('ok', $guide);
    }

    public function updateGuide(Request $request, Guide $guide)
    {
        $phase_date = $request->input('phase_date');
        if ($phase_date) {
            $is_exists = Guide::where('order_id', $guide->order_id)->where('phase_date', $phase_date)->where('id', '<>', $guide->id)->exists();
            if ($is_exists) return $this->failure("当前日期餐单已存在");
            $guide->phase_date = $phase_date;
        }
        $phase_title = $request->input("phase_title");
        if ($phase_title) {
            $guide->phase_title = $phase_title;
        }
        $menu = $request->input('menu', []);
        if ($request->has('menu')) {
            $guide->menu = json_encode($menu, JSON_UNESCAPED_UNICODE);
        }
        $hint = $request->input('hint');
        if ($request->has('hint')) {
            $guide->hint = json_encode($hint, JSON_UNESCAPED_UNICODE);
        }
        $guide->save();

        //操作记录
        OperationLoggedEvent::dispatch("更新了订单 $guide->order_id 的餐单:$guide->id");
        return $this->success('ok');
    }

    public function deleteOrderGuide(Request $request, Guide $guide)
    {
        $guide->delete();
        return $this->success('ok');
    }

    public function addOrderGuide(Request $request, Order $order)
    {
        $phase_date = $request->input('phase_date');
        if (empty($phase_date)) return $this->failure("请选择日期");
        $phase_title = $request->input("phase_title");
        if (empty($phase_title)) return $this->failure("请输入名称");
        $menu = $request->input('menu')?:[];
//        if (empty($menu)) return $this->failure("请输入餐单信息");
        $hint = $request->input('hint')?:[];
        $is_exists = $order->guides()->where('phase_date', $phase_date)->exists();
        if ($is_exists) return $this->failure("当前日期餐单已存在");
        $guide = $order->guides()->create(['user_id'=>$order->user_id, 'phase_date'=>$phase_date, 'phase_title'=>$phase_title, 'menu'=>json_encode($menu, JSON_UNESCAPED_UNICODE), 'hint'=>json_encode($hint, JSON_UNESCAPED_UNICODE)]);

        //发送餐单信息
        $chatService = new ChatService();
        $params = [];
        $params['phase_date'] = $phase_date;
        $chatService->sendGroupMsg($order->user_id,'方案信息','系统已为您生成好订单方案，请点击查看详情','https://image.fulllinkai.com/202311/27/fd67ab8389d4ff1c5832ddda72cd0dc1.png','yfheal://app/push/MineMenu',$params);

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

    /**
     * 复制最近一次餐单
     * @param Request $request
     */
    public function copyOrderGuide(Request $request,Order $order){
        $phase_date = $request->input('phase_date');
        if (empty($phase_date)) return $this->failure("请选择日期");

        $date = date('Y-m-d');
        if($phase_date < $date){
            return $this->failure("创建餐单时间不得小于当天");
        }
        //判断该用户当天是否存在餐单
        $is_exists = $order->guides()->where('user_id',$order->user_id)->where('phase_date', $phase_date)->exists();
        if ($is_exists) return $this->failure("当前日期餐单已存在");
        $beforeGuide = $order->guides()->where('user_id',$order->user_id)->where('phase_date','<',$phase_date)->orderByDesc('phase_date')->first();
        if(!$beforeGuide){
            return $this->failure("不存在历史餐单,请先创建");
        }
        //复制历史最近一次餐单
        $guide = $order->guides()->create(['user_id'=>$order->user_id, 'phase_date'=>$phase_date, 'phase_title'=>$beforeGuide->phase_title, 'menu'=>$beforeGuide->menu, 'hint'=>$beforeGuide->hint]);
        $guide->menu = json_decode($guide->menu,true);
        $guide->hint = json_decode($guide->hint,true);
        return $this->success('ok', $guide);
    }


    public function makeGuide(Request $request, Order $order)
    {
        $user = $order->user;
        $user_info = $user->userInfo;
        //检查信息 个人信息，症状自诉，体检报告;
        $res = UserService::checkUserInfo($user, $user_info);
        if (empty($res)) return $this->failure("未完成个人信息");
        //自述症状
        $res = UserService::checkSymptoms($user_info);
        if (empty($res)) return $this->failure("未完成个人自述症状");
        //体检报告
        $res = $user->medicalReports()->count();
        if (empty($res)) return $this->failure("未完成体检报告");
        //生成餐单 第三方
        if (config('app.env') == 'production') {
            $this->httpMakeGuide($user, $order);
        }else {
            $this->httpMakeGuideTest($order, $user, $user_info);
        }

        //操作记录
        OperationLoggedEvent::dispatch("给订单:$order->id 生成了餐单");
        return $this->success('ok');
    }

    /**
     * 获取营养素和食物
     * @param Request $request
     */
    public function getOrderFood(Request $request){
        try {
            $order_id = $request->get('order_id');
            $order = Order::where('id',$order_id)->first();
            $scheme = $order->scheme?$order->scheme->scheme:[];
            foreach ($scheme as $item){
                $item->type = 'NUTRIENT';
            }
            $foods = Food::where('type',Food::TYPE_FOOD)->select('id','name','icon','unit','price','stock as num','type')->orderByDesc('id')->get();
            $result = collect($scheme)->merge($foods)->toArray();
            return $this->success('ok', $result);
        }catch (\Exception $e){
            return $this->failure('获取失败');
        }
    }

    public function httpMakeGuide($user, $order)
    {
        Cache::put('guide_status_'.$order->id, 'MAKING');
        MakeGuide::dispatch($user)->onQueue('health');
    }

    public function httpMakeGuideTest($order, $user, $user_info)
    {
        //餐单
        $menu = [
            "morning"=> [
                "food"=> [[
                    "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"
                ], [
                    "title"=> "茶叶蛋",
                    "unit"=> "个",
                    "number"=> 1,
                    "pic"=> "https://hbimg.b0.upaiyun.com/62620088daaf8b47e66f8b843e7641de2a4075a43bdf3-brWb6h_fw658"
                ]],
                "nutrient"=> [[
                    "title"=> "蛋白粉",
                    "unit"=> "克",
                    "number"=> 50
                ], [
                    "title"=> "倍力健",
                    "unit"=> "对",
                    "number"=> 1,
                    "pic"=> "https://hbimg.b0.upaiyun.com/62620088daaf8b47e66f8b843e7641de2a4075a43bdf3-brWb6h_fw658"
                ]]
            ],
            "forenoon"=> [
                "food"=> [[
                    "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"
                ]],
                "nutrient"=> [[
                    "title"=> "蛋白粉",
                    "unit"=> "克",
                    "number"=> 50
                ], [
                    "title"=> "倍力健",
                    "unit"=> "对",
                    "number"=> 1,
                    "pic"=> "https://hbimg.b0.upaiyun.com/62620088daaf8b47e66f8b843e7641de2a4075a43bdf3-brWb6h_fw658"
                ]]
            ],
            "noon"=> [
                "food"=> [[
                    "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"
                ]],
                "nutrient"=> [[
                    "title"=> "蛋白粉",
                    "unit"=> "克",
                    "number"=> 50
                ], [
                    "title"=> "倍力健",
                    "unit"=> "对",
                    "number"=> 1,
                    "pic"=> "https://hbimg.b0.upaiyun.com/62620088daaf8b47e66f8b843e7641de2a4075a43bdf3-brWb6h_fw658"
                ]]
            ],
            "afternoon"=> [
                "food"=> [[
                    "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"
                ]],
                "nutrient"=> [[
                    "title"=> "蛋白粉",
                    "unit"=> "克",
                    "number"=> 50
                ], [
                    "title"=> "倍力健",
                    "unit"=> "对",
                    "number"=> 1,
                    "pic"=> "https://hbimg.b0.upaiyun.com/62620088daaf8b47e66f8b843e7641de2a4075a43bdf3-brWb6h_fw658"
                ]]
            ],
            "evening"=> [
                "food"=> [[
                    "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"
                ]],
                "nutrient"=> [[
                    "title"=> "蛋白粉",
                    "unit"=> "克",
                    "number"=> 50
                ], [
                    "title"=> "倍力健",
                    "unit"=> "对",
                    "number"=> 1,
                    "pic"=> "https://hbimg.b0.upaiyun.com/62620088daaf8b47e66f8b843e7641de2a4075a43bdf3-brWb6h_fw658"
                ]]
            ]
        ];
        $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();
        for ($index = 1; $index <= 49; $index++) {
            $date = date('Y-m-d', strtotime("+ $index days",));
            $menu_title = $menu['morning']['food'][0]['title'];
            $menu['morning']['food'][0]['title'] = $menu_title.$index;
            $order->guides()->create([
                'user_id'=>$user->id,
                'phase_date'=>$date,
                'phase_title'=>'清洁日'.$index,
                'menu'=> json_encode($menu, JSON_UNESCAPED_UNICODE),
                'hint'=>json_encode(["注意饮食".$index], JSON_UNESCAPED_UNICODE),
            ]);
            $menu['morning']['food'][0]['title'] = $menu_title;
        }

    }


    public function getGuideTemplate($order_id){
        $templates = GuideTemplate::where('order_id',$order_id)
//            ->where('status',GuideTemplate::STATUS_OPEN)
            ->select('type','effect_guide')->get();
        foreach ($templates as $template){
            $template->effect_guide = json_decode($template->effect_guide);
        }
        return $this->success('ok',$templates);
    }

    public function getGuideDate(Request $request,$order_id){
        $date = $request->get('date');
        $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 = [];
        $send_arr = [];
        $guide_arr = [];
        foreach ($dailies as $daily){
            $guide = Guide::where('order_id',$order_id)->where('phase_date',$daily)->first();
            if(!empty($guide)){
                switch ($guide->phase_title) {
                    case "准备日":
                        $date_arr[] = 1;
                        break;
                    case "装修日":
                        $date_arr[] = 2;
                        break;
                    case "清洁日":
                        $date_arr[] = 3;
                        break;
                }
            }else{
                $date_arr[] = 0;
            }
            $send_arr[] = $guide->send_status??0;
            if(isset($guide->menu)){
                $menu = json_decode($guide->menu,true);
            }else{
                $menu = [];
            }
            $guide_arr[] = $menu;
        }
        $res = [];
        $res["date_arr"] = $date_arr;
        $res["send_status"] = $send_arr;
        $res["guide"] = $guide_arr;
        return $this->success('ok',$res);
    }
}
