<?php

namespace App\Http\Controllers\H5;

use App\Facades\TaskService;
use App\Facades\WechatService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use App\Jobs\SendEasySms;
use App\Jobs\SendSubscribeMessage;
use App\Jobs\SendTemplateNotice;
use App\Models\BeforeDmaQuestion;
use App\Models\CustomerServiceUser;
use App\Models\DmaProcess;
use App\Models\DmaProcessLog;
use App\Models\DmaServiceUserRole;
use App\Models\FatLog;
use App\Models\Food;
use App\Models\Group;
use App\Models\GroupUser;
use App\Models\GuideScheme;
use App\Models\GuideTemplate;
use App\Models\MarkOrderLog;
use App\Models\MedicalReport;
use App\Models\NoticeUser;
use App\Models\OperateStockLog;
use App\Models\Order;
use App\Models\OrderOperateLog;
use App\Models\Partner;
use App\Models\S2RealObjectStockOperate;
use App\Models\S2ShopSku;
use App\Models\S2ShopSpu;
use App\Models\ServiceRole;
use App\Models\ServiceRoleOrder;
use App\Models\ServiceRoleUser;
use App\Models\ServiceUser;
use App\Models\ServiceUserBindRole;
use App\Models\TempOrder;
use App\Models\User;
use App\Models\Wechat;
use App\Services\ChatService;
use App\Services\OfflineOrderService;
use cccdl\yunxin_sdk\Im\Team;
use Exception;
use GuzzleHttp\Client;
use Http;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class OrderController extends Controller
{
    use ResponseJson;

    /**
     * 未绑定企业微信订单列表
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function groupOrders(Request $request)
    {
        $orders = Order::paid()->noWorkChatGroup()->keyword()->simplePaginate();
        return $this->success('ok', $orders);
    }

    public function schemeOrders(Request $request)
    {
        $orders = Order::with("user:id,name,is_privacy")->whereHas("group", function ($sql) {
            $sql->where("service_type", 1);
        })->paid()->keyword()->scheme()->orderBYDesc('id')->simplePaginate();
        return $this->success('ok', $orders);
    }

    /**
     * 订单绑定企业微信群
     * @param Request $request
     * @param Order $order
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function bindWorkGroupOrder(Request $request, Order $order)
    {
        DB::beginTransaction();
        $chat_id = $request->chat_id;
        if (empty($chat_id))
            throw new \Exception("缺少群ID");
        $service_user_id = $request->get('service_user_id');
        if ($service_user_id) {
            $group = Group::where('im_chat_id', $chat_id)->where('order_id', '<>', $order->id)->first();
            if ($group) {
                if ($group->order->type != 'TEMP')
                    throw new \Exception("该群组已绑定其他订单");
                $order_group = Group::where('order_id', $order->id)->where('id', '<>', $group->id)->first();
                //同步备注
                $group->order->comments()->update(['commentable_id' => $order->id]);
                $group->order->orderSurveys()->update(['order_id' => $order->id]);
                //同步问卷调查
                if ($order_group) {
                    if ($order_group->im_chat_id)
                        throw new \Exception("该订单已绑定群组");
                    $group->delete();
                    $order_group->update(['im_chat_id' => $chat_id]);
                } else {
                    Group::create(['name' => 'app群服务', 'order_id' => $order->id, 'im_chat_id' => $chat_id]);
                }
            } else {
                $group = $order->group;
                if (empty($group))
                    throw new \Exception("订单暂无群组");
                if ($group->im_chat_id && $chat_id != $group->im_chat_id)
                    return $this->failure("该订单已绑定其他群");
                $group->update(['im_chat_id' => $chat_id]);
            }
        } else {
            $group = Group::where('chat_id', $chat_id)->where('order_id', '<>', $order->id)->first();
            if ($group) {
                if ($group->order->type != 'TEMP')
                    throw new \Exception("该企业微信群已绑定其他订单");
                $order_group = Group::where('order_id', $order->id)->where('id', '<>', $group->id)->first();
                //同步备注
                $group->order->comments()->update(['commentable_id' => $order->id]);
                $group->order->orderSurveys()->update(['order_id' => $order->id]);
                //同步问卷调查
                if ($order_group) {
                    if ($order_group->chat_id)
                        throw new \Exception("该订单已绑定企业微信群");
                    $group->delete();
                    $order_group->update(['chat_id' => $chat_id]);
                } else {
                    Group::create(['name' => '微信群服务', 'order_id' => $order->id, 'chat_id' => $chat_id]);
                }
            } else {
                $group = $order->group;
                if (empty($group))
                    throw new \Exception("订单暂无群组");
                if ($group->chat_id && $chat_id != $group->chat_id)
                    return $this->failure("该订单已绑定其他企业微信群");
                $group->update(['chat_id' => $chat_id]);
            }
        }
        //查看是否有角色
        $OfflineOrderService = new OfflineOrderService();
        $OfflineOrderService->insertRoleData($chat_id, $order->id);
        DB::commit();
        return $this->success('ok', ['status' => 2]);
    }

    /**
     * 暂不绑定订单-生成临时订单
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function unbindWorkGroupOrder(Request $request)
    {
        $chat_id = $request->chat_id;
        if (empty($chat_id))
            throw new \Exception("缺少企业微信群ID");
        $service_user_id = $request->get('service_user_id');
        if ($service_user_id) {
            $group = Group::where('im_chat_id', $chat_id)->first();
            if ($group && $group->order->type != 'TEMP')
                throw new \Exception("企业微信群已绑定其他订单");
            if ($group && $group->order->type == 'TEMP')
                return $this->success('ok', ['status' => 3]);
            DB::beginTransaction();
            $order = Order::create(['type' => 'TEMP', 'type_id' => 0, 'price' => 0, 'user_id' => 0, 'trade_no' => 0]);
            $order->group()->create(['name' => "临时群", 'im_chat_id' => $chat_id]);

            //查看是否有角色
            $OfflineOrderService = new OfflineOrderService();
            $OfflineOrderService->insertRoleData($chat_id, $order->id);
            DB::commit();
        } else {
            $group = Group::where('chat_id', $chat_id)->first();
            if ($group && $group->order->type != 'TEMP')
                throw new \Exception("企业微信群已绑定其他订单");
            if ($group && $group->order->type == 'TEMP')
                return $this->success('ok', ['status' => 3]);
            DB::beginTransaction();
            $order = Order::create(['type' => 'TEMP', 'type_id' => 0, 'price' => 0, 'user_id' => 0, 'trade_no' => 0]);
            $order->group()->create(['name' => "临时群", 'chat_id' => $chat_id]);

            //查看是否有角色
            $OfflineOrderService = new OfflineOrderService();
            $OfflineOrderService->insertRoleData($chat_id, $order->id);
            DB::commit();
        }
        return $this->success('ok', ['status' => 3]);
    }

    /**
     * 企业微信群订单绑定状态 1.无订单，2。实际订单，3。占位订单
     * @param Request $request
     * @param $chat_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function workGroupOrderStatus(Request $request, $chat_id)
    {
        $service_user_id = $request->get('service_user_id');
        if ($service_user_id) {
            //查看是否存在群组
            $group = Group::where('im_chat_id', $chat_id)->first();
            if (empty($group)) {
                $status = 1;
            } elseif ($group->order && $group->order->type == 'SERVICE') {
                $status = 2;
            } else {
                $status = 3;
            }
            $service_user = ServiceUser::where("user_id", $service_user_id)->first();
            $is_bind = $service_user ? true : false;
            //查看是否绑定角色
            $is_role = false;
            $user_bind_role_data = [];
            $role_list = [];
            $is_comment = '';
            $is_main_coach = $is_coach = $is_customer = 0;
            if ($service_user) {
                //如果有群组
                if ($group) {
                    $service_role_order_ids = ServiceRoleOrder::where('user_id', $service_user->user_id)->where('order_id', $group->order_id)->select('role_id')->get()->toArray();
                    if ($service_role_order_ids) {
                        $user_bind_role_data = ServiceRole::whereIn('id', $service_role_order_ids)->select('id', 'name', 'type', 'value')->get();
                    }
                    $is_role = $service_role_order_ids ? true : false;
                } else {
                    $service_user_bind_role_ids = ServiceUserBindRole::where('chat_id', $chat_id)->where('user_id', $service_user->user_id)->select('role_id')->get()->toArray();
                    if ($service_user_bind_role_ids) {
                        $user_bind_role_data = ServiceRole::whereIn('id', $service_user_bind_role_ids)->select('id', 'name', 'type', 'value')->get();
                    }
                    $is_role = $service_user_bind_role_ids ? true : false;
                }
                //查看用户有什么角色
                foreach ($user_bind_role_data as $item) {
                    switch ($item->id) {
                        case ServiceRole::MAIN_COACH://主教练
                            $is_main_coach = 1;
                            break;
                        case ServiceRole::COACH://副教练
                            $is_coach = 1;
                            break;
                        case ServiceRole::CUSTOMER://客服
                            $is_customer = 1;
                            break;
                    }
                }
                //获取服务人员职责
                $roleUserIds = ServiceRoleUser::where('user_id', $service_user->user_id)->whereIn('role_id', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER])->select('role_id')->get()->toArray();
                $role_list = ServiceRole::whereIn('id', $roleUserIds)->select('id', 'name', 'type', 'value')->get();

                //查看是否备注存在红点
                $key = 'red_event_' . $chat_id . '_' . $service_user->user_id;
                $is_comment = Redis::get($key);
            }
        } else {
            //查看是否存在群组
            $group = Group::where('chat_id', $chat_id)->first();
            if (empty($group)) {
                $status = 1;
            } elseif ($group->order && $group->order->type == 'SERVICE') {
                $status = 2;
            } else {
                $status = 3;
            }
            //发送信息给服务人员
            if (config('app.env') == 'production') {
                $work_id = $request->get('work_id');
                if ($work_id) {
                    $work_user_id = $work_id;
                } else {
                    //查看是否绑定企业微信
                    $work_wechat_user = session('work_wechat_user');
                    $work_user_id = $work_wechat_user['raw']['userid'] ?? null;
                }
            } else {
                $work_user_id = "hankin";
            }
            $service_user = ServiceUser::where("work_user_id", $work_user_id)->first();
            $is_bind = $service_user ? true : false;
            //查看是否绑定角色
            $is_role = false;
            $user_bind_role_data = [];
            $role_list = [];
            $is_comment = '';
            $is_main_coach = $is_coach = $is_customer = 0;
            if ($service_user) {
                //如果有群组
                if ($group) {
                    $service_role_order_ids = ServiceRoleOrder::where('user_id', $service_user->user_id)->where('order_id', $group->order_id)->select('role_id')->get()->toArray();
                    if ($service_role_order_ids) {
                        $user_bind_role_data = ServiceRole::whereIn('id', $service_role_order_ids)->select('id', 'name', 'type', 'value')->get();
                    }
                    $is_role = $service_role_order_ids ? true : false;
                } else {
                    $service_user_bind_role_ids = ServiceUserBindRole::where('chat_id', $chat_id)->where('user_id', $service_user->user_id)->select('role_id')->get()->toArray();
                    if ($service_user_bind_role_ids) {
                        $user_bind_role_data = ServiceRole::whereIn('id', $service_user_bind_role_ids)->select('id', 'name', 'type', 'value')->get();
                    }
                    $is_role = $service_user_bind_role_ids ? true : false;
                }
                //查看用户有什么角色
                foreach ($user_bind_role_data as $item) {
                    switch ($item->id) {
                        case ServiceRole::MAIN_COACH://主教练
                            $is_main_coach = 1;
                            break;
                        case ServiceRole::COACH://副教练
                            $is_coach = 1;
                            break;
                        case ServiceRole::CUSTOMER://客服
                            $is_customer = 1;
                            break;
                    }
                }
                //获取服务人员职责
                $roleUserIds = ServiceRoleUser::where('user_id', $service_user->user_id)->whereIn('role_id', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER])->select('role_id')->get()->toArray();
                $role_list = ServiceRole::whereIn('id', $roleUserIds)->select('id', 'name', 'type', 'value')->get();

                //查看是否备注存在红点
                $key = 'red_event_' . $chat_id . '_' . $service_user->user_id;
                $is_comment = Redis::get($key);
            }
        }
        $data['order_status'] = $group->order->status ?? "NOTSTART";
        $data['status'] = $status;
        $data['is_bind'] = $is_bind;
        $data['is_role'] = $is_role;
        $data['user_bind_role_data'] = $user_bind_role_data;
        $data['role_list'] = $role_list;
        $data['is_comment'] = $is_comment;
        $data['is_coach'] = $is_coach;
        $data['is_main_coach'] = $is_main_coach;
        $data['is_customer'] = $is_customer;


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

    /**
     * 绑定角色
     * @param Request $request
     * @param $chat_id
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function bindRole(Request $request)
    {
        //查看是否存在群组
        $chat_id = $request->input('chat_id');
        if (empty($chat_id)) {
            return $this->failure('chat_id不为空');
        }
        $service_user_id = $request->get('service_user_id');
        if ($service_user_id) {
            $group = Group::where('im_chat_id', $chat_id)->first();
            $role_ids = $request->input('role_ids');
            if (empty($role_ids)) {
                return $this->failure('id不为空');
            }
            $service_user = ServiceUser::where("user_id", $service_user_id)->first();
            if (empty($service_user)) {
                return $this->failure('请先绑定服务人员');
            }
            //有群组则查找群组并绑定职责,如果没有则创建过渡信息,等绑定真实订单的时候再关联角色
            if (!empty($group) && !empty($group->order_id)) {
                foreach ($role_ids as $value) {
                    $ServiceRoleOrder = new ServiceRoleOrder();
                    $ServiceRoleOrder->insertRoleOrder($value, $service_user, $group->order_id);
                }
            } else {
                foreach ($role_ids as $value) {
                    $ServiceUserBindRole = new ServiceUserBindRole();
                    $ServiceUserBindRole->insertUserBindData($chat_id, $service_user, $value);
                }
            }
        } else {
            $group = Group::where('chat_id', $chat_id)->first();
            $role_ids = $request->input('role_ids');
            if (empty($role_ids)) {
                return $this->failure('id不为空');
            }
            $work_id = $request->get('work_id');
            if (!empty($work_id)) {
                $work_user_id = $work_id;
            } else {
                //查看是否绑定企业微信
                $work_wechat_user = session('work_wechat_user');
                $work_user_id = $work_wechat_user['raw']['userid'];
            }
            $service_user = ServiceUser::where("work_user_id", $work_user_id)->first();
            if (empty($service_user)) {
                return $this->failure('请先绑定服务人员');
            }
            //有群组则查找群组并绑定职责,如果没有则创建过渡信息,等绑定真实订单的时候再关联角色
            if (!empty($group) && !empty($group->order_id)) {
                foreach ($role_ids as $value) {
                    $ServiceRoleOrder = new ServiceRoleOrder();
                    $ServiceRoleOrder->insertRoleOrder($value, $service_user, $group->order_id);
                }
            } else {
                foreach ($role_ids as $value) {
                    $ServiceUserBindRole = new ServiceUserBindRole();
                    $ServiceUserBindRole->insertUserBindData($chat_id, $service_user, $value);
                }
            }
        }
        //增加网易云信用户标签
        if (!empty($group) && !empty($group->im_chat_id)) {
            GroupUser::addGroupUser($group, $service_user, $role_ids);
        }
        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 addOrderScheme(Request $request, Order $order)
    {
        $schemes = $request->input("schemes") ?? [];
        $ids = $request->input('ids') ?? [];
        $is_delete = $request->input('is_delete');
        $foods = Food::whereIn('id', $schemes)->select('id', 'name', 'icon', 'unit', 'price', 'config')->get();
        $scheme_obj = $order->scheme;
        $model = $request->input("model");

        //处理数组,将数量也加入到方案中
        foreach ($ids as $value) {
            foreach ($foods as $index => $items) {
                if ($value['id'] == $items->id) {
                    $foods[$index]->num = $value['num'];
                    $foods[$index]->name = $value['name'] ?? '';
                    $foods[$index]->icon = $value['icon'] ?? '';
                    $foods[$index]->price = $value['price'] ?? '';
                    $foods[$index]->unit = $value['unit'] ?? '';
                }
            }
        }
        // 开启事务
        DB::beginTransaction();
        try {
            // 在此处执行你的数据库操作
            if ($scheme_obj) {
                $hour = (time() - strtotime($scheme_obj->created_at)) / 3600;
                if ($hour > 24 && !$is_delete) {
                    //插入操作记录
                    OrderOperateLog::create(['order_id' => $order->id, 'type' => 2]);
                }
                $scheme_obj->update(['init_scheme' => $foods, "model" => $model]);
            } else {
                //插入操作记录
                OrderOperateLog::create(['order_id' => $order->id, 'type' => 1]);
                $order->scheme()->create(['init_scheme' => $foods, "model" => $model]);
            }

            // 提交事务
            DB::commit();
            return $this->success('ok');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            AddErrorLog::dispatch('addOrderScheme file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure("error");
        }
    }

    public function saveOrderScheme(Order $order)
    {
        DB::beginTransaction();
        $scheme = $order->scheme()->first();
        $scheme->update(['scheme' => $scheme->init_scheme]);

        $order->update(['service_status' => 'SCHEME']);

        DB::commit();
        //发送信息给服务人员
        if (config('app.env') == 'production') {
            // $this->sendMsgToServiceUser($order);
            $chatService = new ChatService();
            $chatService->sendImMsgUserToUser($order->id, '方案信息', "用户[" . ($order->name ?? "") . ']方案已设置,请配货并发送', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', '', [ServiceRole::CUSTOMER, ServiceRole::ADMINISTRATIVE]);

            // 待办事项-通知客服、行政
            $theme = "请确认「用户" . $order->name . "」收货方式（自提/邮寄)";
            TaskService::AddTask(0, 0, $theme, [3, 8], $order->id);
            // 待办事项-通知行政
            $theme = "请给「用户" . $order->name . "」拍照确认发货数量/填写快递单号";
            TaskService::AddTask(0, 0, $theme, [8]);
        }

        DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "set_guide_scheme", "用户方案已设置", auth()->user()->id ?? 0);
        DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "send_delivery", "通知行政给用户配送发货", auth()->user()->id ?? 0);
        return $this->success('ok');
        //        try {

        //        }catch (\Exception $e){
//            DB::rollBack();
//            AddErrorLog::dispatch('saveOrderScheme file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
//            return $this->failure('error');
//        }
    }
    /**
     * 发送通知给订单相关服务人员
     * @param $order
     */
    public function sendMsgToServiceUser($order)
    {
        //查看当前订单绑定的服务人员
        $roleOrderUser = ServiceRoleOrder::where('order_id', $order->id)->select()->get();
        foreach ($roleOrderUser as $item) {
            //查看openid
            $open_id = Wechat::where('user_id', $item->user_id)->where('type', 'official')->value('openid');
            $params = [
                'touser' => $open_id,
                'template_id' => config('wechat.tpls.order_scheme_set'),
                'url' => '',
                'data' => [
                    'time2' => ['value' => date('Y-m-d H:i:s')],
                    'character_string1' => ['value' => $order->trade_no],
                    'thing3' => ['value' => $order->name],
                    'phone_number10' => ['value' => $order->mobile],
                ]
            ];
            SendTemplateNotice::dispatch($params)->onQueue('health');

            //发送企业微信通知
            // $message = " 您负责的订单：用户[{$order->name}]订单号:[{$order->trade_no}]的方案已设置，请进入群聊客服查看";
            // $work_user_id = ServiceUser::where('user_id',$item->user_id)->value('work_user_id');
            // if($work_user_id){
            //     WechatService::sendWorkMessage($work_user_id,'text',['content'=>$message]);
            // }
        }
    }


    /**
     * 订单方案信息
     */
    public function orderScheme(Request $request, Order $order)
    {
        $foodIds = Food::where("type", "FOOD")->pluck("id")->toArray();
        $scheme = $order->scheme;
        $arr = [];
        if ($scheme) {
            $value = $scheme->scheme;
            foreach ($value as $item) {
                $food = Food::where("id", $item->id)->first();
                if ($food) {
                    $item->name = $food->name;
                }
                $item->model = $scheme->model;
                if (in_array($item->id, $foodIds))
                    continue;
                $arr[] = $item;
            }
        }
        return $this->success('ok', $arr);
    }

    /**
     * 服务人员标记用户订单状态
     * @param Request $request
     */
    public function updateOrderStatusv1(Request $request)
    {
        DB::beginTransaction();
        try {
            $order = $request->group->order;
            $status = $request->status;
            switch ($status) {
                case "NOSCHEME"://待配置方案
                    if ($order->service_status != 'NOINFO')
                        throw new \Exception("订单状态不符合用户信息已填写");
                    break;
                case "SCHENE":
                    //                if ($order->status != 'NOSCHEME')  throw new \Exception("订单状态不符合待设置方案");
                    break;
                case "FINISHED":
                    break;
                default:
                    throw new \Exception("不支持其他类型");
            }
            $delivery_name = $request->input('delivery_name', '');
            $delivery_number = $request->input('delivery_number', '');
            if (!empty($delivery_name)) {
                $order->delivery_name = $delivery_name;
            }
            if (!empty($delivery_number)) {
                $order->delivery_number = $delivery_number;
            }

            $delivery_type = $request->input('delivery_type');
            if (!empty($delivery_type))
                $order->delivery_type = $delivery_type;
            //如果标记用户信息已完善,则发送相应通知
            if ($status == "NOSCHEME") {
                $this->sendNoticeMsg($order);
            }

            //标记配送已完成增加库存记录
            if ($status == 'FINISHED') {
                if (!empty($order->scheme->scheme)) {
                    foreach ($order->scheme->scheme as $scheme) {
                        $food = Food::where('id', $scheme->id)->first();
                        if (!$food || $food->stock <= 0) {
                            continue;
                        }
                        //查看是否绑定企业微信
//                    $work_wechat_user = session('work_wechat_user');
//                    $work_user_id = $work_wechat_user['raw']['userid'];
//                    $service_user = ServiceUser::where("work_user_id", $work_user_id)->first();
                        $service_user = $request->service_user;

                        $exists = OperateStockLog::where('food_id', $food->id)->where('order_id', $order->id)->exists();
                        if ($exists) {
                            continue;
                        }
                        $admin = [];
                        $admin['name'] = $service_user->name;
                        $admin['id'] = $service_user->user_id;
                        $admin['mobile'] = $service_user->mobile;

                        $map = [];
                        $map['id'] = $food->id;
                        $map['name'] = $food->name;
                        $map['stock'] = $food->stock;
                        $map['num'] = $scheme->num;
                        $map['after_num'] = $food->stock - $scheme->num;
                        $map['type'] = OperateStockLog::TYPE_H5;
                        $map['remark'] = '服务人员:' . $service_user->name . '标记了订单完成,减少了' . $food->name . '的库存,减少数量为' . $scheme->num;
                        $map['operate_type'] = OperateStockLog::OPERATE_TYPE_OUT;
                        $map['status'] = OperateStockLog::OPERATE_STATUS_APPLY;
                        $map['order_id'] = $order->id;
                        $map['goods_type'] = OperateStockLog::GOODS_TYPE_FOOD;
                        OperateStockLog::addLog($admin, $map);
                        //
//                    $food->stock = $map['after_num'];
//                    $food->save();
                    }
                }
                if ($delivery_type == 1) {
                    $log = OrderOperateLog::where('order_id', $order->id)->whereIn('type', [3, 4])->first();
                    if ($log) {
                        if ($log->type == 4) {
                            $log->type = 3;
                        }
                        $log->delivery_name = $delivery_name;
                        $log->delivery_num = $delivery_number;
                        $log->save();
                    } else {
                        //插入操作记录
                        OrderOperateLog::create(['order_id' => $order->id, 'type' => 3, 'delivery_name' => $delivery_name, 'delivery_num' => $delivery_number]);
                    }
                } else {
                    $log = OrderOperateLog::where('order_id', $order->id)->whereIn('type', [3, 4])->first();
                    if ($log) {
                        if ($log->type == 3) {
                            $log->type = 4;
                        }
                        $log->delivery_name = '';
                        $log->delivery_num = '';
                        $log->save();
                    } else {
                        //插入操作记录
                        OrderOperateLog::create(['order_id' => $order->id, 'type' => 4]);
                    }
                }
                //发送公众号消息通知
                $open_id = Wechat::where('user_id', $order->user_id)->where('type', 'official')->value('openid');
                if ($open_id) {
                    $params = [
                        'touser' => $open_id,
                        'template_id' => config('wechat.tpls.send_order_shipment'),
                        "miniprogram" => [
                            "appid" => config('wechat.mini_program.app_id'),
                            "pagepath" => "pages/tabBar/home"
                        ],
                        'data' => [
                            'character_string1' => ['value' => $order->trade_no],
                            'thing6' => ['value' => $order->name],
                            'thing12' => ['value' => $service_user->name],
                            'phone_number11' => ['value' => $service_user->mobile],
                            'time17' => ['value' => date('Y-m-d H:i:s')],
                        ]
                    ];
                    SendTemplateNotice::dispatch($params)->onQueue('health');
                }
                //发送小程序订阅消息
                $mp_openid = Wechat::where('user_id', $order->user_id)->where('type', 'mp')->value('openid');
                if ($mp_openid) {
                    $param = [
                        'touser' => $mp_openid,
                        'template_id' => config('wechat.sub_tpls.send_order_shipment'),
                        'page' => 'pages/service/healthMGT?index=4',
                        'data' => [
                            'character_string2' => ['value' => $order->trade_no],
                            'thing12' => ['value' => $order->name],
                            'date8' => ['value' => date('Y-m-d H:i:s')],
                        ]
                    ];
                    SendSubscribeMessage::dispatch($param)->onQueue('health');
                }
            }

            $order->service_status = $status;
            $order->save();
            DB::commit();
            return $this->success('ok');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('updateOrderStatus:file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
            return $this->failure('标记失败');
        }

    }

    public function updateServerStatus(Request $request)
    {
        DB::beginTransaction();
        try {
            $order = $request->group->order;
            $status = $request->status;
            $service_user = $request->service_user;
            switch ($status) {
                case "NOSCHEME"://待配置方案
                    // 限制条件- 群内客服可操作
                    $auth_status = $order->orderAuthStatus(auth()->id(), [ServiceRole::CUSTOMER, ServiceRole::PERSONAL_COACH]);
                    if (empty($auth_status)) {
                        DB::commit();
                        return $this->failure("客服权限，您无权限操作");
                    }
                    //if ($order->service_status != 'NOINFO') throw new \Exception("订单状态不符合用户信息已填写");
                    $reports = MedicalReport::where('type', MedicalReport::TYPE_BEFORE)->where('user_id', $order->user_id)->exists();
                    if (!$reports)
                        return $this->failure('用户体检报告未上传');
                    $question = BeforeDmaQuestion::where("user_id", $order->user_id)->first();
                    if (empty($question) || $question->status != 1) {
                        DB::commit();
                        return $this->failure("方案前健康评估未审核通过");
                    }
                    break;

                case "SCHENE":
                    //                if ($order->status != 'NOSCHEME')  throw new \Exception("订单状态不符合待设置方案");
                    break;
                case "DELIVER":
                    break;
                case "FINISHED":
                    break;
                case "COMPLETEINFO":
                    break;
                default:
                    throw new \Exception("不支持其他类型");
            }

            $delivery_type = $request->input('delivery_type');
            //订单发货
            if ($status == "DELIVER" && $delivery_type == Order::DELIVER_ONLINE) {
                // 限制条件- 群内客服可操作
                $auth_status = $order->orderAuthStatus(auth()->id(), [ServiceRole::CUSTOMER, ServiceRole::ADMINISTRATIVE]);
                if (empty($auth_status)) {
                    DB::commit();
                    return $this->failure("客服权限，您无权限操作");
                }
                $delivery_name = $request->input('delivery_name', '');
                $delivery_number = $request->input('delivery_number', '');
                $delivery_send_img = $request->input("delivery_send_img", "");
                if (!empty($delivery_name)) {
                    $order->delivery_name = $delivery_name;
                }
                if (!empty($delivery_number)) {
                    $order->delivery_number = $delivery_number;
                }
                if (!empty($delivery_send_img)) {
                    $order->delivery_send_img = $delivery_send_img;
                }

                if (!empty($delivery_type))
                    $order->delivery_type = $delivery_type;

                $log = OrderOperateLog::where('order_id', $order->id)->whereIn('type', [3, 4])->first();
                if ($log) {
                    if ($log->type == 4) {
                        $log->type = 3;
                    }
                    $log->delivery_name = $delivery_name;
                    $log->delivery_num = $delivery_number;
                    $log->save();
                } else {
                    //插入操作记录
                    OrderOperateLog::create(['order_id' => $order->id, 'type' => 3, 'delivery_name' => $delivery_name, 'delivery_num' => $delivery_number]);
                }
                if (!empty($order->scheme->scheme)) {
                    foreach ($order->scheme->scheme as $scheme) {
                        $food = Food::where('id', $scheme->id)->first();
                        if (!$food) {
                            continue;
                        }
                        $exists = OperateStockLog::where('food_id', $food->id)->where('order_id', $order->id)->exists();
                        if ($exists) {
                            continue;
                        }
                        //获取实物id
                        $sku_id = S2ShopSpu::where('id', $food->shop_id)->value('skuid');
                        $real_id = S2ShopSku::where('id', $sku_id)->value('real_id');
                        $map = [];
                        $map['user_id'] = $service_user->user_id;
                        $map['operate_name'] = $service_user->name;
                        $map['operate_mobile'] = $service_user->mobile;
                        $map['operate_type'] = 1;
                        $map['real_ids'] = $real_id;
                        $map['before_num'] = $food->stock;
                        $map['modify_num'] = $scheme->num;
                        $map['after_num'] = $food->stock - $scheme->num;
                        $map['order_id'] = $order->id;
                        $map['remark'] = '服务人员:' . $service_user->name . '标记了订单发货,减少了' . $food->name . '的库存,减少数量为' . $scheme->num;
                        $map['order_source'] = 1;
                        S2RealObjectStockOperate::create($map);
                    }
                }


                // 给客服和行政发系统消息
                $chatService = new ChatService();
                $chatService->sendImMsgUserToUser($order->id, '已发货', "用户" . ($order->name ?? "") . "已发货，快递单号为：{$delivery_number}，请跟进服务。", 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', '', [ServiceRole::CUSTOMER, ServiceRole::ADMINISTRATIVE]);
                // 群聊消息
                $chatService->sendGroupMsg($order->user_id, '已发货', "您好！您的方案已设置完成，且已经配货成功，请留意快递信息，耐心等待收货。", 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', "yfheal://app/push/DmaDelivery", ["order_id" => $order->id], $order);
                $address = $order->userInfo ? $order->userInfo->address : "";
                $remark = "确认已发货，已由快递公司：{$delivery_name}, 快递单号：{$delivery_number}发货至【{$address}】";
                DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "check_delivery", $remark, $service_user->user_id ?? 0);
                //                DmaProcessLog::addUserProcessLog($order->user_id??0,$order->id??0,1,"send_delivery","发送发货通知",$service_user->user_id??0);
            }
            //标记配送已完成增加库存记录,线下订单直接签收
            if ($status == 'FINISHED' || $delivery_type == Order::DELIVER_OFFLINE) {
                if ($delivery_type == Order::DELIVER_OFFLINE) {
                    if (!empty($order->scheme->scheme)) {
                        foreach ($order->scheme->scheme as $scheme) {
                            $food = Food::where('id', $scheme->id)->first();
                            if (!$food) {
                                continue;
                            }
                            $exists = OperateStockLog::where('food_id', $food->id)->where('order_id', $order->id)->exists();
                            if ($exists) {
                                continue;
                            }
                            //获取实物id
                            // $sku_id = S2ShopSpu::where('id', $food->shop_id)->value('skuid');
                            // $real_id = S2ShopSku::where('id', $sku_id)->value('real_id');
                            $sku_id = $food->sku_id;
                            $real_id = $food->real_id;
                            $map = [];
                            $map['user_id'] = $service_user->user_id;
                            $map['operate_name'] = $service_user->name;
                            $map['operate_mobile'] = $service_user->mobile;
                            $map['operate_type'] = 1;
                            $map['real_ids'] = $real_id;
                            $map['before_num'] = $food->stock;
                            $map['modify_num'] = $scheme->num;
                            $map['after_num'] = $food->stock - $scheme->num;
                            $map['order_id'] = $order->id;
                            $map['remark'] = '服务人员:' . $service_user->name . '标记了订单发货,减少了' . $food->name . '的库存,减少数量为' . $scheme->num;
                            $map['order_source'] = 1;
                            S2RealObjectStockOperate::create($map);
                        }
                    }
                }

                //增加订单操作记录
                $log = OrderOperateLog::where('order_id', $order->id)->whereIn('type', [3, 4])->first();
                if ($log) {
                    if ($log->type == 3) {
                        $log->type = 4;
                    }
                    $log->delivery_name = '';
                    $log->delivery_num = '';
                    $log->save();
                } else {
                    //插入操作记录
                    OrderOperateLog::create(['order_id' => $order->id, 'type' => 4]);
                }
                $order->delivery_img = $request->input('delivery_img'); // 签收图
                $delivery_send_img = $request->input('delivery_send_img'); // 发货图
                if (!empty($delivery_send_img)) {
                    $order->delivery_send_img = $delivery_send_img;
                }
                if (!empty($delivery_type))
                    $order->delivery_type = $delivery_type;

                //订单标记完成发送im群消息
                $chatService = new ChatService();
                $chatService->sendImMsgUserToUser($order->id, '确认收货', "用户[" . ($order->name ?? "") . ']已确认收货,请客服设置餐单', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', config('app.url') . '/work/#/h5/appEditUserMenu', [ServiceRole::CUSTOMER]);
                $chatService->sendImMsgUserToUser($order->id, '系统通知', '请所有服务人员与用户[' . $order->name . ']进行第一次视频通话', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', '', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER]);
                if ($delivery_type == Order::DELIVER_OFFLINE) {
                    DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "check_delivery", "确认已发货，线下自提", $service_user->user_id ?? 0);
                }
                DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "user_take_delivery", "用户确认收货", $service_user->user_id ?? 0);

                // 待办事项-主教练
                $theme = "请邀请所有服务人员进行「用户" . $order->name . "」服务的第一次「视频通话」，并将相关视频链接转发给“友福服务”";
                TaskService::AddTask(0, 0, $theme, [1], $order->id);

                // 待办事项-客服
                if (empty($order->status)) {
                    $theme = "请标记「用户" . $order->name . "」的方案开始并确认方案开始时间";
                    TaskService::AddTask(0, 0, $theme, [3], $order->id);

                }
            }
            $update_schemes_lock = 0;
            $foodList = [];
            //标记信息完善,发送通知给陈老师设置方案
            if ($status == 'NOSCHEME') {
                // DMA 群聊通知
                $group = Group::where("order_id", $order->id)->first();
                if ($group && $group->service_type == Group::SERVICE_TYPE_DMA) {
                    $params = [
                        'touser' => 'oHGap6AcgPw9crYNNLVZJr_mtF0k', //陈老师
//                    'touser' => 'oHGap6F1HR-5q-JdRKrgb6DwztWQ', //测试的
                        'template_id' => config('wechat.tpls.check_refund'),
                        'url' => config('app.url') . '/h5/#/orderScheme',
                        'data' => [
                            'phrase3' => ['value' => "信息已完善"],
                            'time4' => ['value' => date("Y-m-d H:i:s")],
                            'thing12' => ['value' => $order->name],
                            'thing9' => ['value' => '友福健康服务'],
                            'amount8' => ['value' => $order->price],
                        ]
                    ];
                    Log::info('auditRefundOrders:' . json_encode($params));
                    SendTemplateNotice::dispatch($params)->onQueue('health');


                    // 系统通知
                    $chatService = new ChatService();
                    $chatService->sendImMsgUserToUserV2($order->id, 328, '方案设置通知', "用户【{$order->name}】的方案待设置。", 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', '');


                    DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "check_health_info", "标记用户信息已完善", $service_user->user_id ?? 0);
                    DmaProcessLog::addUserProcessLog($user->id ?? 0, $order->id ?? 0, 1, "send_guide_scheme", "系统发送方案待设置通知", $service_user->user_id ?? 0);

                } else if ($group && $group->service_type == Group::SERVICE_TYPE_MINI_DMA) { // MINI DMA 
                    $status = "SCHEME"; // 方案已设置
                    $guideScheme = GuideScheme::where("order_id", $order->id)->first();
                    if (empty($guideScheme)) {
                        $foodList = Food::whereIn("id", [131, 132])->select("id", "name", 'icon', "unit", "price", "config", "type")->get();
                        foreach ($foodList as $food) {
                            $food->num = 1;
                        }
                        $initScheme = json_encode($foodList);
                        GuideScheme::create([
                            "order_id" => $order->id,
                            "scheme" => $initScheme,
                            "init_scheme" => $initScheme
                        ]);

                    }
                    DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "set_guide_scheme", "用户方案已设置", auth()->user()->id ?? 0);
                    $update_schemes_lock = 1;
                }
            }

            $order->service_status = $status;
            $order->save();

            MarkOrderLog::create(['order_id' => $order->id, 'operate_id' => $service_user->user_id, 'operate_name' => $service_user->name, 'remark' => "服务人员修改server_status:" . $status]);


            DB::commit();

            if ($update_schemes_lock) {
                // 请求update_schemes_lock_
                $res = $this->updateSchemesLock($order->id, $foodList);
                if (!$res) {
                    throw new Exception("设置餐单方案失败");
                }
            }
            return $this->success('ok');


        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('updateServerStatus:file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage());
            return $this->failure('标记失败');
        }
    }

    public function updateSchemesLock($ordedrId, $foodList)
    {
        $url = config("app.url") . "/go/api/app/v2/dma/update_schemes_lock_" . $ordedrId;

        $client = new Client();
        $token = request()->header("Authorization");

        $headers = [
            "Authorization" => $token
        ];

        $schemes = [
            "ids" => $foodList,
            "schemes" => [131, 132],
            "is_delete" => false,
        ];
        $response = $client->post($url, [
            'headers' => $headers,
            'json' => [
                'schemes' => json_encode($schemes),
            ],
        ]);
        $code = $response->getStatusCode();
        if ($code != 200) {
            return false;
        }
        return true;
    }

    /**
     * 更新订单状态
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function updateOrderStatus(Request $request)
    {
        $order = $request->group->order;
        $order_status = $request->order_status;
        $service_user = $request->service_user;
        if (!in_array($order_status, ['NOTSTART', 'STARTING', 'SUSPEND', 'FINISHED'])) {
            return $this->failure("暂不支持其他类型操作");
        }

        if ($order->service_status != "FINISHED") {
            return $this->failure("请先确认用户已收货");
        }
        if ($order_status == 'FINISHED' && $order_status != $order->status) {
            $service_user = $request->service_user;
            //发送公众号消息通知
            $open_id = Wechat::where('user_id', $order->user_id)->where('type', 'official')->value('openid');
            if ($open_id) {
                $params = [
                    'touser' => $open_id,
                    'template_id' => config('wechat.tpls.send_order_shipment'),
                    "miniprogram" => [
                        "appid" => config('wechat.mini_program.app_id'),
                        "pagepath" => "pages/tabBar/home"
                    ],
                    'data' => [
                        'character_string1' => ['value' => $order->trade_no],
                        'thing6' => ['value' => $order->name],
                        'thing12' => ['value' => $service_user->name],
                        'phone_number11' => ['value' => $service_user->mobile],
                        'time17' => ['value' => date('Y-m-d H:i:s')],
                    ]
                ];
                SendTemplateNotice::dispatch($params)->onQueue('health');
            }
            //发送小程序订阅消息
            $mp_openid = Wechat::where('user_id', $order->user_id)->where('type', 'mp')->value('openid');
            if ($mp_openid) {
                $param = [
                    'touser' => $mp_openid,
                    'template_id' => config('wechat.sub_tpls.send_order_shipment'),
                    'page' => 'pages/service/healthMGT?index=4',
                    'data' => [
                        'character_string2' => ['value' => $order->trade_no],
                        'thing12' => ['value' => $order->name],
                        'date8' => ['value' => date('Y-m-d H:i:s')],
                    ]
                ];
                SendSubscribeMessage::dispatch($param)->onQueue('health');
            }

            //发送网易消息通知
            $chatService = new ChatService();
            $params = [];
            $params['chat_id'] = $request->group->im_chat_id;
            $params['group_name'] = $request->group->name;
            $chatService->sendImMsgUserToUser($order->id, '系统通知', $order->name . '方案已结束,请发送用户调查问卷', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', 'yfheal://app/push/IMGroup', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER], $params, [auth()->id()]);
            $chatService->sendImMsgUserToUser($order->id, '系统通知', $order->name . '方案已结束,请所有教练填写复盘服务评价表', 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', 'yfheal://app/push/IMGroup', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER], $params, []);

            // $theme = "请给「用户".$order->name."」转发【方案后评估表】";
            // TaskService::AddTask(0, 0, $theme, [3], $order->id);

            // $theme2 = "请填写「用户".$order->name."」的【复盘评价表】";
            // TaskService::AddTask(0, 0, $theme, [1,2,3], $order->id);

            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "mark_order_finish", "标记用户方案已结束", $service_user->user_id ?? 0);
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "system_send_order_finish", "系统发送方案结束通知", $service_user->user_id ?? 0);
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "send_after_report_msg", "系统发送上传复检报告通知", $service_user->user_id ?? 0);
        }

        if ($order_status == "STARTING" && $order_status != $order->status) {
            // 限制条件- 群内客服可操作
            $auth_status = $order->orderAuthStatus(auth()->id(), [ServiceRole::CUSTOMER]);
            if (empty($auth_status)) {
                return $this->failure("客服权限，您无权限操作");
            }

            $theme1 = "请给「用户" . $order->name . "」群聊发送【体脂秤指导视频】";
            $theme2 = "请给「用户" . $order->name . "」群聊发送【手环指导视频】";
            $theme3 = "请编辑「用户" . $order->name . "」的餐单内容";
            $processKey1 = "send_use_call_video";
            $processKey2 = "send_use_band_video";
            $processKey3 = "set_guide_scheme";

            // 待办通知-副教练
            TaskService::AddTask(0, 0, $theme1, [2], $order->id, "", "", "", $processKey1);
            TaskService::AddTask(0, 0, $theme2, [2], $order->id, "", "", "", $processKey2);
            TaskService::AddTask(0, 0, $theme3, [2], $order->id, "", "", "", $processKey3);

            // // 待办通知-行政
            // TaskService::AddTask(0,0,$theme2, [8]);


            //            $order->start_time = date("Y-m-d H:i:s");
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "check_order_start", "确认方案开始", $service_user->user_id ?? 0);
        } elseif ($order_status == "SUSPEND") {
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "mark_order_susped", "标记用户方案暂停", $service_user->user_id ?? 0);
        }
        $order->status = $order_status;
        $order->save();
        MarkOrderLog::create(['order_id' => $order->id, 'operate_id' => $service_user->user_id, 'operate_name' => $service_user->name, 'remark' => "服务人员修改order_status:" . $order_status]);
        return $this->success('ok');
    }

    /**
     * 发送消息
     */
    public function sendNoticeMsg($order)
    {
        $notice_user = NoticeUser::select()->get();
        foreach ($notice_user as $value) {
            $params = [
                'touser' => $value->open_id,
                'template_id' => config('wechat.tpls.order_user_info_set'),
                'url' => config('app.url') . '/h5/#/orderScheme',
                'data' => [
                    'time4' => ['value' => date('Y-m-d H:i:s')],
                    'character_string5' => ['value' => $order->trade_no],
                    'phrase9' => ['value' => $order->name],
                    'phone_number14' => ['value' => $order->mobile],
                ]
            ];
            SendTemplateNotice::dispatch($params)->onQueue('health');

            // 系统通知
            $chatService = new ChatService();
            $chatService->sendImMsgUserToUserV2($order->id, $value->user_id, '方案设置通知', "用户【{$order->name}】的方案待设置。", 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', '');


            //发送短信通知
            // $message = "您有新订单需要处理:用户{$order->name},订单号:{$order->trade_no}的方案需要设置【友福同享】";
            // if($value['send_message']){
            //     //发送短信通知
            //     $data = [
            //         'message'=>$message,
            //     ];
            //     SendEasySms::dispatch($value->mobile, $data)->onQueue('health');
            // }

            // //发送企业微信消息通知
            // $work_user_id = ServiceUser::where('user_id',$value->user_id)->value('work_user_id');
            // if($work_user_id){
            //     WechatService::sendWorkMessage($work_user_id,'text',['content'=>$message]);
            // }
        }
    }

    /**
     * 更新订单用户
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function updateOrderUser(Request $request)
    {
        // 开启事务
        DB::beginTransaction();
        try {
            //查看是否存在群组
            $chat_id = $request->input('chat_id');
            if (empty($chat_id)) {
                return $this->failure('chat_id不为空');
            }
            $service_user_id = $request->get('service_user_id');
            if ($service_user_id) {
                $group = Group::where('im_chat_id', $chat_id)->first();
            } else {
                $group = Group::where('chat_id', $chat_id)->first();
            }
            if (!$group) {
                return $this->failure('群组不存在');
            }
            if (empty($group->order_id)) {
                return $this->failure('群组未绑定订单');
            }
            $area_code = $request->input('area_code');
            $mobile = $request->input('mobile');
            if (empty($mobile)) {
                return $this->failure('手机号码不为空');
            }
            $userInfo = User::where('mobile', $mobile)->first();
            if (!$userInfo) {
                return $this->failure('手机号用户不存在');
            }
            $order = Order::where('id', $group->order_id)->where('user_id', '<>', $userInfo->id)->first();
            if (!$order) {
                return $this->failure('订单不存在');
            }
            $old_user_id = $order->user_id;
            //同步旧的信息到新账号
            $old_user_info = User::where('id', $old_user_id)->first();
            if ($old_user_info) {
                $userInfo->name = $old_user_info->name;
                $userInfo->avatar = $old_user_info->avatar;
                $userInfo->sex = $old_user_info->sex;
                $userInfo->birthday = $old_user_info->birthday;
                $userInfo->stature = $old_user_info->stature;
                $userInfo->unit = $old_user_info->unit;
                $userInfo->language = $old_user_info->language;
                $userInfo->save();

                //同步称重信息
                $old_fat_log = FatLog::where('user_id', $old_user_id)->select()->get();
                $fat_log = [];
                foreach ($old_fat_log as $value) {
                    $fat_log['user_id'] = $userInfo->id;
                    $fat_log['fat_name'] = $value->fat_name;
                    $fat_log['fat_state'] = $value->fat_state;
                    $fat_log['fat_data'] = $value->fat_data;
                    $fat_log['unit'] = $value->unit;
                    $fat_log['tested_at'] = $value->tested_at;
                    FatLog::create($fat_log);
                }
            }
            $order->area_code = $area_code;
            //切换订单用户
            $order->user_id = $userInfo['id'];
            $res = $order->save();
            DB::commit();
            return $this->success('ok', $res);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());
            return $this->failure('数据错误');
        }
    }

    /**
     * 填写快递单号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function updateDeliveryInfo(Request $request)
    {
        try {
            $delivery_name = $request->input('delivery_name');
            $delivery_number = $request->input('delivery_number');
            if (empty($delivery_name) || empty($delivery_number)) {
                return $this->failure('快递公司或单号不为空');
            }
            //查看是否存在群组
            $chat_id = $request->input('chat_id');
            if (empty($chat_id)) {
                return $this->failure('chat_id不为空');
            }
            $service_user_id = $request->get('service_user_id');
            if ($service_user_id) {
                $group = Group::where('im_chat_id', $chat_id)->first();
            } else {
                $group = Group::where('chat_id', $chat_id)->first();
            }
            if (!$group) {
                return $this->failure('群组不存在');
            }
            $group->order->delivery_name = $delivery_name;
            $group->order->delivery_number = $delivery_number;
            $group->order->save();

            //插入操作记录
            OrderOperateLog::create(['order_id' => $group->order->id, 'remark' => '已发货 ' . $delivery_name . ' ' . $delivery_number]);
            return $this->success('ok', $group->order);

        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return $this->failure('数据错误');
        }
    }

    public function getChatInfo(Request $request)
    {
        try {
            //查看是否存在群组
            $order = $request->group->order;
            if (empty($order)) {
                return $this->failure("订单不存在");
            }
            $config = [];
            $config['order_status'] = $order->status;
            $config['service_status'] = $order->service_status;

            $guide_template = GuideTemplate::where('order_id', $order->id)->first();
            $guide_status = GuideTemplate::NOT_EXIST;
            if (!empty($guide_template)) {
                $guide_status = GuideTemplate::NOT_CHECK;
                if (!empty($guide_template->effect_guide)) {
                    $guide_status = GuideTemplate::IS_CHECK;
                }
            }
            //如果订单用户未填写信息,邀请用户填写信息,胶囊显示状态控制
            if ($order->service_status == 'NOINFO') {
                $guide_status = -1;
            }
            $config['guide_status'] = $guide_status;
            return $this->success('ok', $config);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getChatInfo file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }
    }

    public function checkBeforeDmaQuestion(Request $request, $id)
    {
        $operate_user_id = $request->input("service_user_id");

        $exists = DB::table("dma_service_user_role")->where("user_id", $operate_user_id)->where("role", 7)->exists();
        if (!$exists) {
            return $this->failure("当前账号无权限,请联系管理员添加审核委员会");
        }
        $status = $request->input("status");
        $remark = $request->input("remark");

        $question = DB::table("before_dma_question")->where("id", $id)->first();
        $user = DB::table("users")->where("id", $question->user_id)->first();

        //查看用户订单是否存在,存在则绑定群id
        $order = Order::getPayOrder($user->id);
        $order_id = $order->id ?? null;
        if ($status == 1) {
            //创建虚拟订单
            $data = [];
            $data['name'] = $user->name;
            $data['price'] = Order::ORDER_PRICE;
            $data['mobile'] = $user->mobile;
            $OfflineOrderService = new OfflineOrderService();
            if (!$order) {
                $offline_order = $OfflineOrderService->createOfflineOrder($data, $user->id);
                $order_id = $offline_order->order_id ?? null;
            }

            DmaProcessLog::addUserProcessLog($question->user_id ?? 0, $order_id, 1, "check_dma_question", "系统已同意[" . $user->name . "]的方案前调查表单", $operate_user_id);
        } elseif ($status == 2) {
            $order_id = "";
            DmaProcessLog::addUserProcessLog($question->user_id ?? 0, $order_id, 1, "check_dma_question", "系统拒绝[" . $user->name . "]的方案前调查表单", $operate_user_id);
        }
        DmaProcessLog::addUserProcessLog($question->user_id ?? 0, $order_id, 1, "send_check_dma_question_to_user", "系统已发送[审核结果]给" . $user->name, $operate_user_id, 5);
        DmaProcessLog::addUserProcessLog($question->user_id ?? 0, $order_id, 1, "send_check_dma_question_to_admin", "系统已发送[审核结果]给行政", $operate_user_id, 5);
        $operate_user = User::find($operate_user_id);
        $question->status = $status;
        $question->order_id = $order_id ?? null;
        $question->remark = $remark;
        $question->operate_user_id = $operate_user_id;
        $question->operate_user_name = $operate_user->name ?? "";
        //        $question->save();
        DB::table("before_dma_question")->where("id", $id)->update(["status" => $status, "order_id" => $order_id, "remark" => $remark, "operate_user_id" => $operate_user_id, "operate_user_name" => $operate_user->name ?? ""]);

        if ($status == 1) {
            $data = [
                'message' => "用户" . $user->name . "的方案前健康评估表已审核通过，请跟进后续服务【友福同享】",
            ];
            // 短信通知行政
            $roles = DmaServiceUserRole::with("user")->where("status", 1)->where("role", 8)->get();
            foreach ($roles as $role) {
                if ($role->user && $role->user->mobile) {
                    SendEasySms::dispatch($role->user->mobile, $data, $role->user->area_code)->onQueue('send.code.sms');
                }
            }
        }
        return $this->success('ok', $question);
    }
}
