<?php

namespace App\Http\Controllers\H5;

use App\Events\OperationLoggedEvent;
use App\Facades\CommonService;
use App\Facades\GuideService;
use App\Facades\TaskService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use App\Models\DmaProcess;
use App\Models\DmaProcessLog;
use App\Models\Food;
use App\Models\Group;
use App\Models\Guide;
use App\Models\GuideHint;
use App\Models\GuideScheme;
use App\Models\GuideTemplate;
use App\Models\Order;
use App\Models\S2RealObject;
use App\Models\S2ShopSku;
use App\Models\ServiceRole;
use App\Models\ServiceRoleUser;
use App\Models\ServiceUser;
use App\Services\ChatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class GuideController extends Controller
{
    use ResponseJson;

    public function guides(Request $request)
    {
        Log::info($request->all());
        $date_arr = null;
        $guides = [];
        $nutrient = null;
        $scheme_status = GuideScheme::GUIDE_STATUS_YES;
        $chat_id = $request->input('chat_id');
        Log::info("guides餐单群id---$chat_id");
        $group = $request->group;
        $order = $request->group->order;
        if (empty($order))
            return $this->success('ok', compact('date_arr', 'guides', 'nutrient'));
        if (empty($group->order->user))
            return $this->failure('该群未绑定实际用户订单');
        Log::info("订单id:" . $order->id);
        $user = $order->user;
        // if ($order->status == 'NOTSTART') {
        //     $nutrient = json_decode($user->userInfo->nutrient);
        // } else {
        $date = $request->input('date');
        $role = $request->input('role');

        $scheme = GuideScheme::where("order_id", $order->id)->exists();
        if (!$scheme) {
            return $this->failure("方案未设置,请先设置方案");
        }

        //获取明天日期
        $today = date('Y-m-d');
        $tomorrow = date('Y-m-d', strtotime($today . ' +1 day'));

        $start_date = date('Y-m-01', strtotime($date));
        $end_date = date('Y-m-d', strtotime("$start_date + 1 month -1 day"));

        //如果是用户端,则只返回到明天的数据
        $query = Guide::query()->where('order_id', $order->id);
        if ($role == 0) {
            // $query->where('phase_date', '<=',$tomorrow);
        }
        $query->whereBetween("phase_date", [$start_date, $end_date]);
        $guides = $query->orderBy('phase_date', 'asc')->get();

        $dates = $guides->pluck('phase_date')->toArray();
        $dailies = CommonService::daliy($start_date, $end_date);
        $date_arr = [];
        foreach ($dailies as $daily) {
            $status = GuideService::getGuideStatus($daily, $guides, $dates);
            if ($role == 0 && $daily > $tomorrow) {
                $status = 0;
            }
            Log::info($daily . "----" . $status);
            $date_arr[] = $status;
        }

        if (empty($order->scheme)) {
            $scheme_status = GuideScheme::GUIDE_STATUS_NO;
            return $this->success('ok', compact('scheme_status'));
        }
        //获取量
        [$guides, $scheme_food, $flag] = GuideService::getQuantity($order->scheme->scheme, $guides);
        // }
        foreach ($guides as $guide) {
            if (!empty($guide->hint)) {
                continue;
            }
            $type = GuideTemplate::TYPE_STR_ARR[$guide->phase_title] ?? 0;
            $hint = GuideHint::GetHint($type);
            $guide->hint = json_decode($hint, true);
        }
        //返回餐单模板状态
        $template = GuideTemplate::where('order_id', $order->id)->first();
        $template_is_check = GuideTemplate::NOT_EXIST;
        if (!empty($template)) {
            $template_is_check = GuideTemplate::NOT_CHECK;
            if (!empty($template->effect_guide)) {
                $template_is_check = GuideTemplate::IS_CHECK;
            }
        }
        $clean_count = Guide::where("order_id", $order->id)->where("phase_title", "清洁日")->count();
        $trim_count = Guide::where("order_id", $order->id)->where("phase_title", "装修日")->count();
        $prepare_count = Guide::where("order_id", $order->id)->where("phase_title", "准备日")->count();

        //        $log = DmaProcessLog::where("order_id",$order->id)
//            ->whereIn("key_name",["set_guide_template","save_guide","check_guide","set_date_guide","send_date_guide"])
//            ->orderByDesc("id")
//            ->get();
        Log::info($date_arr);
        return $this->success('ok', compact('date_arr', 'guides', 'nutrient', 'flag', 'template_is_check', 'scheme_status', 'clean_count', 'trim_count', 'prepare_count'));
    }


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

    public function addOrderGuide(Request $request)
    {
        //        $work_user = session('work_wechat_user');
//        if (empty($work_user)) return $this->failure('未授权企业微信用户');
//        if (!isset($work_user['raw']['userid'])) return $this->failure("请使用企业微信扫码绑定");
//        $work_user_id = $work_user['raw']['userid'];
//        $service_user = ServiceUser::where("work_user_id", $work_user_id)->first();
//        $service_role_user = ServiceRoleUser::where("s_user_id", $service_user->id)->where('role_id',ServiceRole::CUSTOMER)->first();
//        if(empty($service_role_user)){
//            return $this->failure('请使用客服角色');
//        }
        $order = $request->group->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), 'status' => Guide::STATUS_REVIEW]);

        $chatService = new ChatService();
        $chatService->sendImMsgUserToUser($order->id, '系统通知', $order->name . '餐单已编辑,待审核', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', config('app.url') . '/work/#/h5/appEditUserMenu', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER]);

        // 待办事项-主教练
        $theme = "请审核餐单并设置「用户" . $order->name . "」的餐单日历";
        TaskService::AddTask(0, 0, $theme, [1], $order->id, "", "", "", "check_guide");
        return $this->success('ok', $guide);
    }

    /**
     * 审核餐单信息
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function checkGuide(Request $request)
    {
        $id = $request->get('id');
        if (empty($id))
            return $this->failure('id不为空');
        $guide = Guide::where('id', $id)->first();
        if (empty($guide))
            return $this->failure('餐单不存在');
        $guide->status = Guide::STATUS_SCHEDULED;
        $guide->save();

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

        $order = $request->group->order;
        $chatService->sendImMsgUserToUser($guide->order_id, '系统通知', $order->name . '餐单审核完毕,待发送', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', '', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER]);
        return $this->success('ok');
    }

    /**
     * 复制最近一次餐单
     * @param Request $request
     */
    public function copyOrderGuide(Request $request)
    {
        $order = $request->group->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, 'status' => Guide::STATUS_SCHEDULED]);
        $guide->menu = json_decode($guide->menu, true);
        $guide->hint = json_decode($guide->hint, true);

        $chatService = new ChatService();
        $chatService->sendImMsgUserToUser($order->id, '系统通知', $order->name . '餐单日历已设置完成', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', '', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER], [], [$request->input('service_user_id')]);

        DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "set_date_guide", "设置餐单日历", $request->input('service_user_id'));
        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 (is_array($hint)) {
            $guide->hint = json_encode($hint, JSON_UNESCAPED_UNICODE);
        }
        $guide->save();
        return $this->success('ok');
    }

    public function orderScheme(Request $request)
    {
        $order = $request->group->order;
        $scheme = $order->scheme ? $order->scheme->scheme : [];

        $guides = Guide::where('order_id', $order->id)->orderBy('phase_date', 'asc')->get();
        //        dd($guides);
        [$guides, $scheme_food] = GuideService::getQuantity($scheme, $guides);

        foreach ($scheme as $item) {
            $id = $item->id;
            $item->remain_quantity = $scheme_food[$id]->remain_quantity ?? 0;
            $item->rate = 100;
            $item->quantity = $scheme_food[$id]->quantity ?? 0;
            if ($item->quantity != 0) {
                $item->rate = round($item->remain_quantity / $item->quantity, 2) * 100;
            }
        }
        return $this->success('ok', $scheme);
    }

    /**
     * 获取营养素和食物
     * @param Request $request
     */
    public function getOrderFood(Request $request)
    {
        try {
            $order = $request->group->order;
            //获取初始化营养素
            $scheme = $order->scheme ? $order->scheme->scheme : [];
            foreach ($scheme as $key => $item) {
                $scheme[$key] = json_decode(json_encode($item), true);
                // 修改类型为 'NUTRIENT'
                $scheme[$key]['type'] = 'NUTRIENT';
                // 如果存在 config 属性，则进行 JSON 解码
                if (isset($scheme[$key]['config'])) {
                    $scheme[$key]['config'] = json_decode($scheme[$key]['config'], true);
                } else {
                    $config = Food::where('id', $item->id)->value('config');
                    $scheme[$key]['config'] = json_decode($config, true);
                }
            }
            // $foods = Food::where('type', Food::TYPE_FOOD)->select('id', 'name', 'icon', 'unit', 'price', 'stock as num', 'type', 'config')->orderByDesc('id')->get()?->toArray();
            // foreach ($foods as $k => $v) {
            //     if (empty($v['config'])) {
            //         continue;
            //     }
            //     $foods[$k]['config'] = json_decode($v['config'], true);
            // }
            // // 合并 $scheme 和 $foods 数组
            // $result = array_merge($scheme, $foods);
            return $this->success('ok', $scheme);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getOrderFood file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }
    }

    /**
     * 写个接口更新旧的餐单没有id的情况
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function updateOldGuides()
    {
        DB::beginTransaction();
        try {
            $guides = Guide::get();
            //循环所有餐单数据
            foreach ($guides as $guide) {
                $guide_info = Guide::where('id', $guide->id)->first();
                if (empty($guide_info)) {
                    continue;
                }
                $guide->menu = json_decode($guide->menu);

                foreach ($guide->menu as $menu) {
                    //更新旧的营养素
                    foreach ($menu->nutrient as $nutrient) {
                        if (isset($nutrient->price)) {
                            continue;
                        }
                        $type_nutrient = Food::where('name', $nutrient->title)->where('type', 'NUTRIENT')->first();
                        if (!$type_nutrient) {
                            continue;
                        }
                        $nutrient->id = $type_nutrient->id;
                        $nutrient->price = $type_nutrient->price;
                    }
                    //更新旧的食物
                    foreach ($menu->food as $food) {
                        if (isset($food->price)) {
                            continue;
                        }
                        $type_food = Food::where('name', $food->title)->where('type', 'FOOD')->first();
                        if (!$type_food) {
                            continue;
                        }
                        $food->id = $type_food->id;
                        $food->price = $type_food->price;
                    }
                }
                $guide_info->menu = json_encode($guide->menu, JSON_UNESCAPED_UNICODE);
                $guide_info->save();
            }
            DB::commit();
            return $this->success('ok');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('updateOldGuides:' . $e->getMessage());
            return $this->failure('更新失败');
        }
    }

    /**
     * 设置餐单模板
     * @param Request $request
     * @param $order_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function setGuideTemplate(Request $request)
    {
        try {
            $order = $request->group->order;
            $service_user_id = $request->input("service_user_id");
            // $auth_status = $order->orderAuthStatus($service_user_id, [ServiceRole::MAIN_COACH, ServiceRole::CUSTOMER]);
            // if (empty($auth_status)) {
            //     return $this->failure("主教练、客服权限，您无权限操作");
            // }
            $map = [];
            $prepare_guide = $request->input('prepare_guide');
            $decoration_guide = $request->input('decoration_guide');
            $clean_guide = $request->input('clean_guide');

            $prepare_hint = $request->input('prepare_hint');
            $decoration_hint = $request->input('decoration_hint');
            $clean_hint = $request->input('clean_hint');

            $prepare_step = $request->input("prepare_step", 10000);
            $decoration_step = $request->input("decoration_step", 10000);
            $clean_step = $request->input("clean_step", 10000);

            $map[0]['type'] = GuideTemplate::TYPE_PREPARE;
            $map[0]['init_guide'] = json_encode($prepare_guide);
            $map[0]['hint'] = json_encode($prepare_hint);
            $map[0]["step"] = $prepare_step;
            $map[1]['type'] = GuideTemplate::TYPE_DECORATION;
            $map[1]['init_guide'] = json_encode($decoration_guide);
            $map[1]['hint'] = json_encode($decoration_hint);
            $map[1]["step"] = $decoration_step;
            $map[2]['type'] = GuideTemplate::TYPE_CLEAN;
            $map[2]['init_guide'] = json_encode($clean_guide);
            $map[2]['hint'] = json_encode($clean_hint);
            $map[2]["step"] = $clean_step;
            foreach ($map as $item) {
                GuideTemplate::updateOrCreate(['order_id' => $order->id, 'type' => $item['type']], ['order_id' => $order->id, 'type' => $item['type'], 'init_guide' => $item['init_guide'], 'status' => GuideTemplate::STATUS_CLOSE, 'hint' => !empty($item['hint']) ? $item['hint'] : GuideHint::GetHint($item['type']), "step" => $item["step"]]);
            }

            $chatService = new ChatService();
            $chatService->sendImMsgUserToUser($order->id, '系统通知', $order->name . '餐单已编辑,待审核', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', config('app.url') . '/work/#/h5/appEditUserMenu', [ServiceRole::MAIN_COACH, ServiceRole::CUSTOMER], [], []);
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "set_guide_template", "编辑用户餐单", $request->input('service_user_id'));
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "save_guide", "保存用户餐单", $request->input('service_user_id'));
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "send_save_guide_msg", "系统发送餐单待审核通知", $request->input('service_user_id'), 5);

            // 待办事项-主教练
            $theme = "请审核餐单并设置「用户" . $order->name . "」的餐单日历";
            TaskService::AddTask(0, 0, $theme, [1], $order->id, "", "", "", "check_guide");
            return $this->success('ok');
        } catch (\Exception $e) {
            AddErrorLog::dispatch('setGuideTemplate file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure("设置失败");
        }
    }

    /**
     * 获取餐单模板
     * @param Request $request
     * @param $order_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getGuideTemplate(Request $request)
    {
        try {
            $order = $request->group->order;

            $templates = GuideTemplate::where('order_id', $order->id)->select('init_guide', 'type', 'status', 'hint')->get()?->toArray();

            //获取初始化营养素
            $scheme = $order->scheme ? $order->scheme->scheme : [];

            if (empty($scheme)) {
                return $this->success('ok', []);
            }

            foreach ($scheme as $key => $item) {
                $scheme[$key] = json_decode(json_encode($item), true);
                // 修改类型为 'NUTRIENT'
                $scheme[$key]['type'] = 'NUTRIENT';
                // 如果存在 config 属性，则进行 JSON 解码
                if (isset($scheme[$key]['config'])) {
                    $scheme[$key]['config'] = json_decode($scheme[$key]['config'], true);
                    $scheme[$key]['oneNum'] = isset($scheme[$key]['config'][0]["oneNum"]) ? $scheme[$key]['config'][0]["oneNum"] : 1;
                } else {
                    $config = Food::where('id', $item->id)->value('config');
                    $scheme[$key]['config'] = json_decode($config, true);
                    $scheme[$key]['oneNum'] = isset($scheme[$key]['config'][0]["oneNum"]) ? $scheme[$key]['config'][0]["oneNum"] : 1;
                }
            }
            $foods = Food::with("shopSpu")->where('type', Food::TYPE_FOOD)->orderByDesc('id')->get()?->toArray();
            foreach ($foods as $k => $v) {
                if (empty($v['config'])) {
                    continue;
                }
                $sku = S2ShopSku::where('id', $v["shop_spu"]["skuid"])->first();
                $object = S2RealObject::where('id', $sku->real_id)->first();
                $foods[$k]['name'] = $v["shop_spu"]["title"];
                $foods[$k]['icon'] = $v["shop_spu"]["icon"];
                $foods[$k]['price'] = ($sku->price ?? 0) / 100;
                $foods[$k]['num'] = $object->stock ?? 0;
                $foods[$k]['have_goods'] = 1;
                unset($v["shop"]);
                $foods[$k]['config'] = json_decode($v['config'], true);
                $foods[$k]['oneNum'] = isset($foods[$k]['config'][0]["oneNum"]) ? $foods[$k]['config'][0]["oneNum"] : 1;
            }
            // 合并 $scheme 和 $foods 数组
            $result = array_merge($scheme, $foods);

            foreach ($result as &$value) {
                $value['state'] = 0;
            }
            unset($value);
            if (empty($templates)) {
                $templates = [];
                // 创建三条假数据
                for ($i = 0; $i < 3; $i++) {
                    $template = [
                        'type' => $i,
                        'status' => GuideTemplate::STATUS_INIT,
                        'init_guide' => [
                            'list' => $result,
                            'menu' => null
                        ],
                        'hint' => "",
                    ];
                    $templates[] = $template;
                }
            } else {
                foreach ($templates as &$template) {
                    $template['init_guide'] = $init_guide = json_decode($template['init_guide'], true);
                    $lookup = [];
                    if (count($init_guide) == 0 || !isset($init_guide["list"]))
                        continue;
                    foreach ($init_guide["list"] as $item) {
                        $lookup[$item['id']] = $item;
                    }
                    foreach ($result as &$item) {
                        if (isset($lookup[$item['id']])) {
                            //                            $item = array_merge($item, $lookup[$item['id']]);
                            $item = $lookup[$item['id']];
                        }
                    }
                    unset($item);

                    $template['init_guide']["list"] = $result;
                }
            }
            unset($template);
            return $this->success('ok', $templates);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('setGuideTemplate file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure("设置失败");
        }
    }

    /**
     * 审核餐单模板
     * @param $order_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function checkGuideTemplate(Request $request)
    {
        DB::beginTransaction();
        try {
            $order = $request->group->order;
            $service_user_id = $request->input("service_user_id");
            $auth_status = $order->orderAuthStatus($service_user_id, [ServiceRole::MAIN_COACH]);
            if (empty($auth_status)) {
                return $this->failure("主教练权限，您无权限操作");
            }
            $templates = GuideTemplate::where('order_id', $order->id)->get();
            foreach ($templates as $template) {
                $template->effect_guide = $template->init_guide;
                $template->status = GuideTemplate::STATUS_OPEN;
                $template->save();
            }
            //更新未来餐单
            $this->updateFutureGuide($order->id);

            DB::commit();

            $chatService = new ChatService();
            $chatService->sendImMsgUserToUser($order->id, '系统通知', $order->name . '餐单审核完毕', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', config('app.url') . '/work/#/h5/appEditUserMenu', [ServiceRole::COACH, ServiceRole::CUSTOMER], [], []);

            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "check_guide", "确定餐单内容", $request->input('service_user_id'));
            return $this->success('ok');
        } catch (\Exception $e) {
            DB::rollBack();
            AddErrorLog::dispatch('setGuideTemplate file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure("设置失败");
        }
    }

    public function updateFutureGuide($order_id)
    {
        $date = date("Y-m-d");
        $guide = Guide::where("order_id", $order_id)->where("phase_date", ">", $date)->get();
        foreach ($guide as $item) {
            $type = 0;
            if ($item->phase_title == "装修日") {
                $type = 1;
            } elseif ($item->phase_title == "清洁日") {
                $type = 2;
            }
            $template = GuideTemplate::where('order_id', $order_id)->where("type", $type)->first();

            if (empty($template) || empty($template->effect_guide)) {
                return $this->failure('模板不可用');
            }

            $effect_guide = json_decode($template->effect_guide, true);

            $menu = $effect_guide['menu'] ?: [];
            Guide::where("id", $item->id)->update(['menu' => json_encode($menu, JSON_UNESCAPED_UNICODE), 'hint' => !empty($template->hint) ? $template->hint : GuideHint::GetHint($type)]);
        }
    }
    /**
     * 根据餐单模板设置餐单
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function setOrderGuide(Request $request)
    {
        $order = $request->group->order;
        $service_user_id = $request->input("service_user_id");
        // 限制条件- 群内主教练可操作
        $auth_status = $order->orderAuthStatus($service_user_id, [ServiceRole::MAIN_COACH]);
        if (empty($auth_status)) {
            return $this->failure("主教练权限，您无权限操作");
        }
        $phase_date = $request->input('phase_date');
        if (empty($phase_date))
            return $this->failure("请选择日期");
        $type = $request->input("type");
        if (strlen($type) == 0)
            return $this->failure("请输入名称");
        $phase_title = GuideTemplate::TYPE_ARR[$type];

        $guide = Guide::where('order_id', $order->id)->where('phase_date', $phase_date)->first();

        $guide_template = GuideTemplate::where('order_id', $order->id)->where('type', $type)->first();
        if (empty($guide_template) || empty($guide_template->effect_guide)) {
            return $this->failure('模板不可用');
        }
        $effect_guide = json_decode($guide_template->effect_guide, true);

        $menu = $effect_guide['menu'] ?: [];
        $hint = !empty($guide_template->hint) ? $guide_template->hint : GuideHint::GetHint($type);
        if (!empty($guide)) {
            $guide->phase_title = $phase_title;
            $guide->menu = json_encode($menu, JSON_UNESCAPED_UNICODE);
            $guide->hint = $hint;
            $guide->save();
        } else {
            $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' => $hint, 'status' => Guide::STATUS_SCHEDULED]);
        }

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

        //        $redis = Redis::client();
//        $redis_guide = $redis->get('set_guide');
//        if(!$redis_guide){
//            $redis->set('set_guide',1,5*60);
//
//            $chatService = new ChatService();
//            $chatService->sendImMsgUserToUser($order->id, '系统通知', $order->name . '餐单日历已设置完成', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', '', [ServiceRole::MAIN_COACH,ServiceRole::COACH,ServiceRole::CUSTOMER]);
//
//            DmaProcessLog::addUserProcessLog($order->user_id??0,$order->id??0,1,"set_date_guide","设置餐单日历",$request->input('service_user_id'));
//            DmaProcessLog::addUserProcessLog($order->user_id??0,$order->id??0,1,"system_send_date_guide","系统发送餐单待发送通知",$request->input('service_user_id'));
//
//        }

        $chatService = new ChatService();
        $chatService->sendImMsgUserToUser($order->id, '系统通知', $order->name . '餐单日历已设置完成', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', '', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER], [], [$request->input('service_user_id')]);

        DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "set_date_guide", "设置餐单日历", $request->input('service_user_id'));
        DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "system_send_date_guide", "系统发送餐单待发送通知", $request->input('service_user_id'), 5);

        $guide->menu = $effect_guide['menu'] ?? [];
        return $this->success('ok', $guide);
    }

    /**
     * 根据餐单模板批量设置餐单
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function batchSetOrderGuide(Request $request)
    {
        $order = $request->group->order;
        $service_user_id = $request->input("service_user_id");
        // 限制条件- 群内主教练可操作
        $auth_status = $order->orderAuthStatus($service_user_id, [ServiceRole::MAIN_COACH]);
        if (empty($auth_status)) {
            return $this->failure("主教练权限，您无权限操作");
        }
        $guide_arr = $request->input("guide_arr");
        $is_send = $request->input("is_send");

        $month = $request->input("month");
        $today = date("Y-m-d");
        Guide::where('order_id', $order->id)->where('phase_date', ">", $today)->where("phase_date", "like", $month . "%")->delete();

        foreach ($guide_arr as $item) {
            $phase_title = GuideTemplate::TYPE_ARR[$item["type"]];

            $guide = Guide::where('order_id', $order->id)->where('phase_date', $item["date"])->first();

            $guide_template = GuideTemplate::where('order_id', $order->id)->where('type', $item["type"])->first();
            if (empty($guide_template) || empty($guide_template->effect_guide)) {
                return $this->failure('模板不可用');
            }
            $effect_guide = json_decode($guide_template->effect_guide, true);
            $hint = !empty($guide_template->hint) ? $guide_template->hint : GuideHint::GetHint($item["type"]);

            $menu = $effect_guide['menu'] ?: [];
            if (!empty($guide)) {
                $guide->phase_title = $phase_title;
                $guide->menu = json_encode($menu, JSON_UNESCAPED_UNICODE);
                $guide->hint = $hint;
                $guide->save();
            } else {
                $guide = $order->guides()->create(['user_id' => $order->user_id, 'phase_date' => $item["date"], 'phase_title' => $phase_title, 'menu' => json_encode($menu, JSON_UNESCAPED_UNICODE), 'hint' => $hint, 'status' => Guide::STATUS_SCHEDULED]);
            }

            $guide->menu = $effect_guide['menu'] ?? [];
        }


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

        if ($is_send) {
            $chatService = new ChatService();
            $chatService->sendImMsgUserToUser($order->id, '系统通知', $order->name . '餐单日历已设置完成', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', '', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER], [], [$request->input('service_user_id')]);
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "set_date_guide", "设置餐单日历", $request->input('service_user_id'));
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "system_send_date_guide", "系统发送餐单待发送通知", $request->input('service_user_id'), 5);
        }
        return $this->success('ok');
    }
}
