<?php

namespace App\Http\Controllers\App;

use App\Facades\TaskService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use App\Jobs\SyncMessage;
use App\Models\Band;
use App\Models\DmaProcess;
use App\Models\DmaProcessLog;
use App\Models\Group;
use App\Models\GroupUser;
use App\Models\Guide;
use App\Models\GuideHint;
use App\Models\GuideTemplate;
use App\Models\Order;
use App\Models\QuickReply;
use App\Models\S2ApiLog;
use App\Models\ServiceRole;
use App\Models\ServiceRoleOrder;
use App\Models\User;
use App\Services\ImMessageService;
use App\Services\YunXinMessageCallBack\YunXinMessageCallBackService;
use cccdl\yunxin_sdk\Exception\cccdlException;
use cccdl\yunxin_sdk\Im\CallBack;
use cccdl\yunxin_sdk\Im\Msg;
use cccdl\yunxin_sdk\Im\Team;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class ChatController extends Controller
{
    use ResponseJson;

    /**
     * 发送消息过滤
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function filterMessage(Request $request, ImMessageService $imService)
    {
        try {
            $user = auth()->user();
            $type = $request->input('type');
            if (!$type)
                return $this->failure('参数错误');
            $content = $request->input('content');
            if (!strlen($content))
                return $this->failure('文本不能为空');

            $imService->type = $type;
            $imService->content = $content;
            $imService->user = $user;
            return $this->success('ok', $imService->send());
        } catch (\Exception $e) {
            Log::error('filterMessage:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 消息回调
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function chatCallback(Request $request, YunXinMessageCallBackService $s)
    {
        try {
            $c = new CallBack(config('chat.im.app_id'), config('chat.im.app_secret'));
            $c->notify();
            // $s->handle();
            $param = $request->all();
            SyncMessage::dispatch($param)->onQueue("sync.message");
            return $this->success('ok');
        } catch (\Exception $e) {
            Log::error('chatCallback:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }


    /**
     * 获取订单服务人员
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getServiceUser(Request $request)
    {
        try {
            $user = auth()->user();
            $order = Order::where('user_id', $user->id)->orderByDesc('id')->first();
            if (empty($order)) {
                return $this->failure('订单不存在');
            }
            $service_user = ServiceRoleOrder::with('partnerUser')->where('order_id', $order->id)->get();
            return $this->success('ok', $service_user);
        } catch (\Exception $e) {
            Log::error('getServiceUser:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 群聊详情
     * @param Request $request
     * @param $group_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function groupInfo(Request $request, $group_id)
    {
        try {
            $user = auth()->user();
            $group = Group::query()->with(['users', 'order'])->find($group_id)?->toArray();
            if (!$group) {
                return $this->failure('群聊不存在');
            }

            //我在本群的昵称
            $nickname = GroupUser::query()
                ->where('user_id', $user->id)
                ->where('group_id', $group_id)
                ->value('nickname');
            $group['self']['nickname'] = $nickname ?: User::query()->where('id', $user->id)->value('name');

            $group['role_list'] = ServiceRoleOrder::with('role')->where('order_id', $group['order_id'])->where('user_id', $user->id)->get();
            return $this->success('ok', $group);
        } catch (\Exception $e) {
            Log::error('groupInfo:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 群聊详情
     * @param Request $request
     * @param $group_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getGroupInfo(Request $request)
    {
        // try {
        $user = auth()->user();
        $im_chat_id = $request->get('im_chat_id');
        $group = Group::query()->with(['users', 'order'])->where('im_chat_id', $im_chat_id)->first()?->toArray();
        if (!$group) {
            return $this->failure('群聊不存在');
        }

        //我在本群的昵称
        $groupUser = GroupUser::query()
            ->where('user_id', $user->id)
            ->where('group_id', $group['id'])
            ->first();
        if (empty($groupUser))
            return $this->failure("群聊不存在");
        $group['self']['nickname'] = $groupUser->nickname ?: User::query()->where('id', $user->id)->value('name');
        $group['self']['comment'] = $groupUser->comment;

        $group['role_list'] = ServiceRoleOrder::with('role')->where('order_id', $group['order_id'])->where('user_id', $user->id)->get();

        if (isset($group['users']) && is_array($group['users'])) {
            foreach ($group['users'] as &$userItem) { // 使用引用来更新原始数组
                if (is_array($userItem) && isset($userItem['id'])) {
                    $userItem['role_list'] = ServiceRoleOrder::with('role')
                        ->where('order_id', $group['order_id'])
                        ->where('user_id', $userItem['id'])
                        ->get();

                    $userItem['ac_cid'] = make_wangyiyun_accid($userItem['id']);
                    //                        $userItem['mobile'] = substr($userItem['mobile'], 0, 3) . str_repeat('*', strlen($userItem['mobile']) - 3);
                    $userItem['mobile'] = str_repeat('*', strlen($userItem['mobile']));
                }
            }
        }
        // 当前用户id
        $group_user_id = 0;
        if ($group["service_type"] == 1) {
            $group_user_id = $group["order"]["user_id"];
        } else if ($group["service_type"] == 2) {
            $group_user_id = Group::getGroupUserId($group["id"]);

        }

        $key = "user:" . $group_user_id . ":device_info";
        // 服务对象设备信息
        $device_info = Redis::get($key);
        Log::info($key);
        Log::info($device_info);
        if (empty($device_info)) {
            $device_info = ["version" => [], "phone_model" => [], "system_version" => [], "source" => []];
            $log = S2ApiLog::where("user_id", $group_user_id)->orderBy("id", "desc")->first();
            if ($log && $log->header) {
                $headers = json_decode($log->header, true);
                $device_info['version'] = $headers["Version"] ?? [];
                $device_info['phone_model'] = $headers["Phone-Model"] ?? [];
                $device_info['system_version'] = $headers["System-Version"] ?? [];
                $device_info['source'] = $headers["Source"] ?? [];
            }
            $device_info_str = json_encode($device_info);
            Redis::setex($key, 1 * 60 * 60, $device_info_str);
        } else {
            $device_info = json_decode($device_info, true);
        }
        $group["device_info"] = $device_info;
        // 电量
        $group["band_battery"] = null;
        $group["band_name"] = null;
        $group["band_timestamp"] = null;
        $band = Band::where("user_id", $group_user_id)->orderByDesc("id")->first();
        if ($band) {
            $history = DB::table("battery_history")->where("band_id", $band->id)->orderByDesc("timestamp")->first();
            $group["band_battery"] = $history ? $history->battery_percentage : null;
            $group['band_timestamp'] = $history ? $history->timestamp : null;
            $group["band_name"] = $band->name;
        }
        return $this->success('ok', $group);
        // } catch (\Exception $e) {
        //     Log::error('groupInfo:' . $e->getMessage());
        //     return $this->failure($e->getMessage());
        // }
    }

    /**
     * 修改用户在群聊的昵称
     * @param Request $request
     * @param $group_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function updateGroupUserNickname(Request $request, $group_id)
    {
        try {
            $user = auth()->user();

            $nickname = $request->input('nickname');
            if (!strlen($nickname)) {
                return $this->failure('昵称不能为空');
            }

            $group = Group::query()->find($group_id);
            if (!$group) {
                return $this->failure('群聊不存在');
            }

            $group_user = GroupUser::query()
                ->where('user_id', $user->id)
                ->where('group_id', $group_id)
                ->first();
            if (!$group_user) {
                return $this->failure('不在该群聊');
            }

            if ($group_user->nickname == $nickname) {
                return $this->success('ok');
            }

            //同步
            $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
            $owner_accid = make_wangyiyun_accid($group->owner_id);
            $user_accid = make_wangyiyun_accid($user->id);
            $options = ['nick' => $nickname];
            $imTeam->updateTeamNick($group->im_chat_id, $owner_accid, $user_accid, $options);

            $group_user->nickname = $nickname;
            $group_user->save();

            return $this->success('ok');
        } catch (\Exception $e) {
            Log::error('updateGroupUserNickname:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    public function addQuickReply(Request $request)
    {
        try {
            $user = auth()->user();
            $content = $request->input('content');

            $map = [];
            $map['user_id'] = $user->id;
            $map['content'] = $content;
            QuickReply::create($map);
            return $this->success('ok');
        } catch (\Exception $e) {
            AddErrorLog::dispatch('addQuickReply file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure("添加失败");
        }
    }

    public function getQuickReply(Request $request)
    {
        try {
            $user = auth()->user();
            $keyword = $request->input('keyword');
            $query = QuickReply::query();

            $query->where('user_id', $user->id);

            $query->when($keyword, function ($sql) use ($keyword) {
                $sql->where('content', 'like', '%' . $keyword . '%');
            });
            $list = $query->orderByDesc('id')->paginate();
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getQuickReply file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure("获取失败");
        }
    }

    public function getQuickReplyDetail($id)
    {
        try {
            $detail = QuickReply::find($id);
            return $this->success('ok', $detail);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getQuickReplyDetail file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure("获取失败");
        }
    }

    public function deleteQuickReply($id)
    {
        try {
            QuickReply::where('id', $id)->delete();
            return $this->success('ok');
        } catch (\Exception $e) {
            AddErrorLog::dispatch('deleteQuickReply file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure("删除失败");
        }
    }

    public function updateQuickReply(Request $request, $id)
    {
        try {
            $detail = QuickReply::find($id);
            $content = $request->input('content');
            $detail->content = $content;
            $detail->save();
            return $this->success('ok');
        } catch (\Exception $e) {
            AddErrorLog::dispatch('updateQuickReply file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure("更新失败");
        }
    }

    public function sendImVideo(Request $request)
    {
        $user = auth()->user();
        $user_id = make_wangyiyun_accid($user->id);
        $chat_id = $request->input('chat_id');
        $type = $request->input("type");
        //发送群消息
        $imMsg = new Msg(config('chat.im.app_id'), config('chat.im.app_secret'));
        $group = Group::query()->where("im_chat_id", $chat_id)->first();
        if ($type == "band") {
            $imMsg->sendMsg($user_id, 1, $chat_id, $imMsg::MSG_TYPE_VIDEO, json_encode(['url' => 'https://images.health.ufutx.com/202410/15/2024101401.mp4', 'md5' => 'cf8a8dfd196b2b06b52496fd1190be29', 'dur' => 73000, 'ext' => 'mp4', 'w' => 480, 'h' => 360, 'size' => 4934255]), ['ext' => json_encode(['video_thumb_url' => 'https://images.health.ufutx.com/202410/15/2024101402.jpg'])]);
            DmaProcessLog::addUserProcessLog($group->order->user_id ?? 0, $group->order->id ?? 0, 1, "send_use_call_video", "转发体脂秤使用教程", auth()->user()->id ?? 0);
        } else {
            $imMsg->sendMsg($user_id, 1, $chat_id, $imMsg::MSG_TYPE_VIDEO, json_encode(['url' => 'https://ufutx-health.oss-cn-hangzhou.aliyuncs.com/health/video/202606/08/3c0cff15522853080a132394a37886bc.mp4', 'md5' => 'cf8a8dfd196b2b06b52496fd1190be29', 'dur' => 73000, 'ext' => 'mp4', 'w' => 480, 'h' => 360, 'size' => 4934255]), ['ext' => json_encode(['video_thumb_url' => 'https://images.health.ufutx.com/202410/15/2024101401.jpg'])]);
            DmaProcessLog::addUserProcessLog($group->order->user_id ?? 0, $group->order->id ?? 0, 1, "send_use_band_video", "转发手环使用教程", auth()->user()->id ?? 0);
        }
        return $this->success('ok');
    }

    public function sendImMsg(Request $request)
    {
        $user_id = $request->input('user_id');
        if ($user_id) {
            $order = Order::where('user_id', $user_id)->orderByDesc('id')->first();
        } else {
            $chat_id = $request->input('chat_id');
            $is_im = $request->input('is_im');
            if ($is_im) {
                $group = Group::where('im_chat_id', $chat_id)->first();
            } else {
                $group = Group::where('chat_id', $chat_id)->first();
            }
            $order = Order::where('id', $group->order_id)->first();
        }
        $survey_id = $request->input('survey_id');
        if (!$order) {
            return $this->failure('发送失败');
        }
        $send_config = [
            'guide' => [
                'title' => '餐单信息',
                'content' => '系统已为您生成好餐单，请点击查看详情',
                'icon' => 'https://images.health.ufutx.com/202412/12/547a28634b7fb6fe32d42727aa983dce.png',
                //                'url' => 'yfheal://app/push/MineMenu',
                'url' => config('app.url') . '/work/#h5/appUserMenu',
                'param' => [
                    'is_guide' => 1,
                ],
            ],
            'survey' => [
                'title' => '方案后服务问卷',
                'content' => '本次为方案后服务问卷，请点击查看详情',
                'icon' => 'https://images.health.ufutx.com/202412/12/951ac6954a938c0ad069be6248d6b47b.png',
                "url" => config('app.url') . "/go_html/role_apply#/app/afterSurveyMenu",
                'param' => [
                    'is_guide' => 1,
                ],
            ],
            'health' => [
                'title' => '健康信息',
                "content" => "请点击填写健康信息",
                'icon' => 'https://images.health.ufutx.com/202412/12/abc84f7b2b5dc2b94d6d27ca4eeb09ab.png',
                'url' => 'yfheal://app/push/InputInfoHealthManagerFirstPage',
                'param' => [],
            ],
            'after_report' => [
                'title' => '复检报告',
                "content" => "请点击上传复检报告",
                'icon' => 'https://images.health.ufutx.com/202412/12/abc84f7b2b5dc2b94d6d27ca4eeb09ab.png',
                'url' => 'yfheal://app/push/MedicalExaminReport',
                'param' => [],
            ],
            'after_body_image' => [
                'title' => '方案后身体照片',
                "content" => "请点击上传方案后身体照片",
                'icon' => 'https://images.health.ufutx.com/202412/12/abc84f7b2b5dc2b94d6d27ca4eeb09ab.png',
                'url' => 'yfheal://app/push/UpdateHealthBodyPhotoAfter',
                'param' => [],
            ],
        ];
        $type = $request->input('type');
        if (empty($type) || !isset($send_config[$type])) {
            return $this->failure('请选择发送类型');
        }

        $config = $send_config[$type];
        if (strpos($config['url'], "https") !== false) {
            // 包含 "https"
            $config['url'] = $config['url'] . "?chat_id=" . $group->im_chat_id . '&is_im=1';
        }
        //记录是否发送餐单
        if ($type == "guide") {
            $today = date('Y-m-d');
            $date = $request->input('date', date('Y-m-d', strtotime(' +1 day')));
            $guide = Guide::where('order_id', $order->id)->where('phase_date', $date)->first();
            if (empty($guide)) {
                return $this->failure("当天未设置餐单");
            }
            $date_str = "明天";
            if ($date == $today) {
                $date_str = "今天";
            }
            if (!empty($guide)) {
                $key = Guide::SEND_GUIDE_MSG;
                $expire = getDayExpire();
                Redis::set($key . $guide->id, 1, $expire);

                $guide->send_status = 1;
                $guide->save();

                $menu_arr = json_decode($guide->menu, true);
                $hint_arr = json_decode($guide->hint, true);
                // $content = "{$date_str}（{$guide->phase_date}）是{$guide->phase_title}哦😊\n您的餐单如下:\n";
                $content = "{$date_str}（{$guide->phase_date}）\n您的餐单如下:\n";
                $keys = ["beforeMorning", "morning", "forenoon", "beforeNoon", "noon", "afternoon", "midnight", "evening", "sleep"];

                foreach ($keys as $key) {
                    foreach ($menu_arr as $menu_key => $value) {
                        if ($menu_key == $key) {
                            if ($key == "beforeMorning") {
                                $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
                                if ($hasData) {
                                    $content = $content . "\n❤早餐前:\n";
                                    if (isset($value['food']) && isset($value['nutrient'])) {
                                        $new_arr = array_merge($value['food'], $value['nutrient']);
                                        $length = count($new_arr);
                                        $i = 0;
                                        foreach ($new_arr as $item) {
                                            $content .= $item["title"] . $item["oneNum"] . $item["unit"];
                                            $i++;
                                            if ($i < $length) {
                                                $content .= "+";
                                            } elseif ($i == $length) {
                                                $content .= "\n";
                                            }
                                        }
                                    }
                                }
                            }

                            if ($key == "morning") {
                                $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
                                if ($hasData) {
                                    $content = $content . "\n❤早餐:\n";
                                    if (isset($value['food']) && isset($value['nutrient'])) {
                                        $new_arr = array_merge($value['food'], $value['nutrient']);
                                        $length = count($new_arr);
                                        $i = 0;
                                        foreach ($new_arr as $item) {
                                            $content .= $item["title"] . $item["oneNum"] . $item["unit"];
                                            $i++;
                                            if ($i < $length) {
                                                $content .= "+";
                                            } elseif ($i == $length) {
                                                $content .= "\n";
                                            }
                                        }
                                    }
                                }
                            }

                            if ($key == "forenoon") {
                                $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
                                if ($hasData) {
                                    $content = $content . "\n❤上午:\n";
                                    if (isset($value['food']) && isset($value['nutrient'])) {
                                        $new_arr = array_merge($value['food'], $value['nutrient']);
                                        $length = count($new_arr);
                                        $i = 0;
                                        foreach ($new_arr as $item) {
                                            $content .= $item["title"] . $item["oneNum"] . $item["unit"];
                                            $i++;
                                            if ($i < $length) {
                                                $content .= "+";
                                            } elseif ($i == $length) {
                                                $content .= "\n";
                                            }
                                        }
                                    }
                                }
                            }

                            if ($key == "beforeNoon") {
                                $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
                                if ($hasData) {
                                    $content = $content . "\n❤午餐前:\n";
                                    if (isset($value['food']) && isset($value['nutrient'])) {
                                        $new_arr = array_merge($value['food'], $value['nutrient']);
                                        $length = count($new_arr);
                                        $i = 0;
                                        foreach ($new_arr as $item) {
                                            $content .= $item["title"] . $item["oneNum"] . $item["unit"];
                                            $i++;
                                            if ($i < $length) {
                                                $content .= "+";
                                            } elseif ($i == $length) {
                                                $content .= "\n";
                                            }
                                        }
                                    }
                                }
                            }

                            if ($key == "noon") {
                                $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
                                if ($hasData) {
                                    $content = $content . "\n❤午餐:\n";
                                    if (isset($value['food']) && isset($value['nutrient'])) {
                                        $new_arr = array_merge($value['food'], $value['nutrient']);
                                        $length = count($new_arr);
                                        $i = 0;
                                        foreach ($new_arr as $item) {
                                            $content .= $item["title"] . $item["oneNum"] . $item["unit"];
                                            $i++;
                                            if ($i < $length) {
                                                $content .= "+";
                                            } elseif ($i == $length) {
                                                $content .= "\n";
                                            }
                                        }
                                    }
                                }
                            }

                            if ($key == "afternoon") {
                                $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
                                if ($hasData) {
                                    $content = $content . "\n❤下午:\n";
                                    if (isset($value['food']) && isset($value['nutrient'])) {
                                        $new_arr = array_merge($value['food'], $value['nutrient']);
                                        $length = count($new_arr);
                                        $i = 0;
                                        foreach ($new_arr as $item) {
                                            $content .= $item["title"] . $item["oneNum"] . $item["unit"];
                                            $i++;
                                            if ($i < $length) {
                                                $content .= "+";
                                            } elseif ($i == $length) {
                                                $content .= "\n";
                                            }
                                        }
                                    }
                                }
                            }

                            if ($key == "midnight") {
                                $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
                                if ($hasData) {
                                    $content = $content . "\n❤晚餐前:\n";
                                    if (isset($value['food']) && isset($value['nutrient'])) {
                                        $new_arr = array_merge($value['food'], $value['nutrient']);
                                        $length = count($new_arr);
                                        $i = 0;
                                        foreach ($new_arr as $item) {
                                            $content .= $item["title"] . $item["oneNum"] . $item["unit"];
                                            $i++;
                                            if ($i < $length) {
                                                $content .= "+";
                                            } elseif ($i == $length) {
                                                $content .= "\n";
                                            }
                                        }
                                    }
                                }
                            }

                            if ($key == "evening") {
                                $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
                                if ($hasData) {
                                    $content = $content . "\n❤晚餐:\n";
                                    if (isset($value['food']) && isset($value['nutrient'])) {
                                        $new_arr = array_merge($value['food'], $value['nutrient']);
                                        $length = count($new_arr);
                                        $i = 0;
                                        foreach ($new_arr as $item) {
                                            $content .= $item["title"] . $item["oneNum"] . $item["unit"];
                                            $i++;
                                            if ($i < $length) {
                                                $content .= "+";
                                            } elseif ($i == $length) {
                                                $content .= "\n";
                                            }
                                        }
                                    }
                                }
                            }
                            if ($key == "sleep") {
                                $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
                                if ($hasData) {
                                    $content = $content . "\n🌙睡前:\n";
                                    if (isset($value['food']) && isset($value['nutrient'])) {
                                        $new_arr = array_merge($value['food'], $value['nutrient']);
                                        $length = count($new_arr);
                                        $i = 0;
                                        foreach ($new_arr as $item) {
                                            $content .= $item["title"] . $item["oneNum"] . $item["unit"];
                                            $i++;
                                            if ($i < $length) {
                                                $content .= "+";
                                            } elseif ($i == $length) {
                                                $content .= "\n";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //                 foreach ($menu_arr as $key => $value) {
//                     if ($key == "beforeMorning") {
//                         $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
//                         if($hasData){
//                             $content = $content . "\n❤早餐前:\n";
//                             if (isset($value['food']) && isset($value['nutrient'])) {
//                                 $new_arr = array_merge($value['food'],$value['nutrient']);
//                                 $length = count($new_arr);
//                                 $i = 0;
//                                 foreach ($new_arr as $item){
//                                     $content .= $item["title"].$item["oneNum"].$item["unit"];
//                                     $i++;
//                                     if ($i < $length) {
//                                         $content .= "+";
//                                     }
//                                 }
//                             }
//                         }
//                     }

                //                     if ($key == "morning") {
//                         $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
//                         if($hasData){
//                             $content = $content . "\n早餐:";
//                             if (isset($value['food']) && isset($value['nutrient'])) {
//                                 $new_arr = array_merge($value['food'],$value['nutrient']);
//                                 $length = count($new_arr);
//                                 $i = 0;
//                                 foreach ($new_arr as $item){
//                                     $content .= $item["title"].$item["oneNum"].$item["unit"];
//                                     $i++;
//                                     if ($i < $length) {
//                                         $content .= "+";
//                                     }elseif ($i == $length){
//                                         $content .= "\n";
//                                     }
//                                 }
//                             }
//                         }
//                     }

                //                     if ($key == "forenoon") {
//                         $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
//                         if($hasData) {
//                             $content = $content . "\n上午:\n";
//                             if (isset($value['food']) && isset($value['nutrient'])) {
//                                 $new_arr = array_merge($value['food'],$value['nutrient']);
//                                 $length = count($new_arr);
//                                 $i = 0;
//                                 foreach ($new_arr as $item){
//                                     $content .= $item["title"].$item["oneNum"].$item["unit"];
//                                     $i++;
//                                     if ($i < $length) {
//                                         $content .= "+";
//                                     }elseif ($i == $length){
//                                         $content .= "\n";
//                                     }
//                                 }
//                             }
//                         }
//                     }

                // //                    if ($key == "beforeNoon") {
// //                        $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
// //                        if($hasData) {
// //                            $content = $content . "\n❤午餐前:\n";
// //                            if (isset($value['food']) && isset($value['nutrient'])) {
// //                                $new_arr = array_merge($value['food'],$value['nutrient']);
// //                                $length = count($new_arr);
// //                                $i = 0;
// //                                foreach ($new_arr as $item){
// //                                    $content .= $item["title"].$item["oneNum"].$item["unit"];
// //                                    $i++;
// //                                    if ($i < $length) {
// //                                        $content .= "+";
// //                                    }
// //                                }
// //                            }
// //                        }
// //                    }

                //                     if ($key == "noon") {
//                         $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
//                         if($hasData) {
//                             $content = $content . "\n❤午餐:\n";
//                             if (isset($value['food']) && isset($value['nutrient'])) {
//                                 $new_arr = array_merge($value['food'],$value['nutrient']);
//                                 $length = count($new_arr);
//                                 $i = 0;
//                                 foreach ($new_arr as $item){
//                                     $content .= $item["title"].$item["oneNum"].$item["unit"];
//                                     $i++;
//                                     if ($i < $length) {
//                                         $content .= "+";
//                                     }elseif ($i == $length){
//                                         $content .= "\n";
//                                     }
//                                 }
//                             }
//                         }
//                     }

                //                     if ($key == "afternoon") {
//                         $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
//                         if($hasData) {
//                             $content = $content . "\n下午:\n";
//                             if (isset($value['food']) && isset($value['nutrient'])) {
//                                 $new_arr = array_merge($value['food'],$value['nutrient']);
//                                 $length = count($new_arr);
//                                 $i = 0;
//                                 foreach ($new_arr as $item){
//                                     $content .= $item["title"].$item["oneNum"].$item["unit"];
//                                     $i++;
//                                     if ($i < $length) {
//                                         $content .= "+";
//                                     }elseif ($i == $length){
//                                         $content .= "\n";
//                                     }
//                                 }
//                             }
//                         }
//                     }

                // //                    if ($key == "midnight") {
// //                        $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
// //                        if($hasData) {
// //                            $content = $content . "\n❤晚餐前:\n";
// //                            if (isset($value['food']) && isset($value['nutrient'])) {
// //                                $new_arr = array_merge($value['food'],$value['nutrient']);
// //                                $length = count($new_arr);
// //                                $i = 0;
// //                                foreach ($new_arr as $item){
// //                                    $content .= $item["title"].$item["oneNum"].$item["unit"];
// //                                    $i++;
// //                                    if ($i < $length) {
// //                                        $content .= "+";
// //                                    }
// //                                }
// //                            }
// //                        }
// //                    }

                //                     if ($key == "evening") {
//                         $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
//                         if($hasData) {
//                             $content = $content . "\n❤晚餐:\n";
//                             if (isset($value['food']) && isset($value['nutrient'])) {
//                                 $new_arr = array_merge($value['food'],$value['nutrient']);
//                                 $length = count($new_arr);
//                                 $i = 0;
//                                 foreach ($new_arr as $item){
//                                     $content .= $item["title"].$item["oneNum"].$item["unit"];
//                                     $i++;
//                                     if ($i < $length) {
//                                         $content .= "+";
//                                     }elseif ($i == $length){
//                                         $content .= "\n";
//                                     }
//                                 }
//                             }
//                         }
//                     }
//                     if ($key == "sleep") {
//                         $hasData = (isset($value['food']) && !empty($value['food'])) || (isset($value['nutrient']) && !empty($value['nutrient']));
//                         if($hasData) {
//                             $content = $content . "\n🌙睡前:\n";
//                             if (isset($value['food']) && isset($value['nutrient'])) {
//                                 $new_arr = array_merge($value['food'],$value['nutrient']);
//                                 $length = count($new_arr);
//                                 $i = 0;
//                                 foreach ($new_arr as $item){
//                                     $content .= $item["title"].$item["oneNum"].$item["unit"];
//                                     $i++;
//                                     if ($i < $length) {
//                                         $content .= "+";
//                                     }elseif ($i == $length){
//                                         $content .= "\n";
//                                     }
//                                 }
//                             }
//                         }
//                     }
//                 }
                if (empty($hint_arr)) {
                    $type = GuideTemplate::TYPE_STR_ARR[$guide->phase_title] ?? 0;
                    $hint_arr = GuideHint::GetHint($type);
                    $hint_arr = json_decode($hint_arr, true);
                }

                foreach ($hint_arr as $hint) {
                    if (isset($hint["content"])) {
                        $content = $content . "\n{$hint["content"]}";
                    }
                }
                //                if(empty($hint_arr)){
//                    $type = GuideTemplate::TYPE_STR_ARR[$guide->phase_title]??0;
//                    $hint_arr = GuideHint::GetHint($type);
//
//                    $content .= "\n🚰累计一天饮水: 2400毫升\n🚶‍♀累计一天步数: 5000步";
//                }

                if (mb_strlen($content, 'UTF-8') > 800) {
                    $content = mb_substr($content, 0, 800, 'UTF-8') . '...';
                }
                //                if (strlen($content) > 800) {
//                    $content = substr($content, 0, 800) . '...';
//                }
                $config["param"]["guide"] = $content;
            }
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "send_date_guide", "转发每日餐单", auth()->user()->id ?? 0);
        } elseif ($type == "survey") {
            // 限制条件- 群内客服可操作
            $auth_status = $order->orderAuthStatus(auth()->id(), [ServiceRole::CUSTOMER]);
            if (empty($auth_status)) {
                return $this->failure("客服权限，您无权限操作");
            }
            $config['url'] = $config['url'] . '&survey_id=' . $survey_id;
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "system_send_question", "系统发送调查问卷通知", auth()->user()->id ?? 0);
        } else if ($type == "health") {
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "submit_health_info", "邀请用户填写健康档案", auth()->user()->id ?? 0);
        } else if ($type == "after_report") {
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "send_after_report_msg", "提醒上传复检报告通知", auth()->user()->id ?? 0);
        } else if ($type == "after_body_image") {
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "send_after_body_image", "提醒上传方案后身体照通知", auth()->user()->id ?? 0);
        }
        //查看用户是否已有订单
        $chatService = new \App\Services\ChatService();
        $chatService->sendGroupMsg($order->user_id, $config['title'], $config['content'], $config['icon'], $config['url'], $config['param'], $order);

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

    }
}
