<?php

namespace App\Console\Commands;

use App\Facades\TaskService;
use App\Models\DmaProcessLog;
use App\Models\Order;
use App\Facades\CommonService;
use App\Models\ServerQuestion;
use App\Models\ServiceRole;
use cccdl\yunxin_sdk\Im\Msg;
use Illuminate\Console\Command;
use App\Services\ChatService;
use Log;

class DmaQuestionNotice extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:finished {notice}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $notice = $this->argument("notice");

        if ($notice == "quesiotn_notice") {// 方案后问卷调查提醒
            $this->sendQuestionNotice();
        } elseif ($notice == "clean_notice") { // 方案后清洁提醒
            $this->sendCleanNotice();
        } elseif ($notice == "after_body_image") {// 方案后身体照提醒
            $this->sendAfterBodyImageNotice();
        } elseif ($notice == "after_body_image_task") {// 方案后身体照任务
            $this->sendAfterBodyImageTask();
        } elseif ($notice == "server_question_3") {// 方案结束后教练评估
            $this->sendServerQuestionTask3();
        } elseif ($notice == "server_question_60") {// 方案结束后教练评估表
            $this->sendServerQuestionTask60();
        }
        return Command::SUCCESS;
    }

    public function sendServerQuestionTask3()
    {
        $start_time = date("Y-m-d ", strtotime("-4 day"));
        $end_time = date("Y-m-d ", strtotime("-3 day"));
        $orders = Order::with("user")->whereHas("group")->whereHas("user")->where("status", "FINISHED")->whereBetween("end_time", [$start_time, $end_time])->get();
        foreach ($orders as $order) {
            // $theme = "请填写「用户" . $order->name . "」的【方案后第3天】评估表";
            $theme = "【" . $order->name . "】方案已结束3天，请所有教练填写用户第一次评价表";
            $user_ids = ServerQuestion::where('order_id', $order->id)->where('type', 1)->pluck("user_id")->toArray();
            TaskService::AddTask(0, 0, $theme, [1, 2, 3], $order->id, "", "", "", "", $user_ids);

            $chatService = new ChatService();
            $chatService->sendImMsgUserToUser($order->id, '系统通知', $theme, '', '', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER], [], $user_ids);

            DmaProcessLog::addUserProcessLog(0, $order->id, 1, "system_send_server_question_3_msg", $theme, 5);
        }
    }

    public function sendServerQuestionTask60()
    {
        $start_time = date("Y-m-d ", strtotime("-61 day"));
        $end_time = date("Y-m-d ", strtotime("-60 day"));
        $orders = Order::whereHas("group")->whereHas("user")->where("status", "FINISHED")->whereBetween("end_time", [$start_time, $end_time])->get();
        foreach ($orders as $order) {
            // $theme = "请填写「用户" . $order->name . "」的【方案后第60天】评估表";
            $theme = "【" . $order->name . "】方案已结束60天，请所有教练填写用户第二次评价表";
            $user_ids = ServerQuestion::where('order_id', $order->id)->where('type', 2)->pluck("user_id")->toArray();
            TaskService::AddTask(0, 0, $theme, [1, 2, 3], $order->id, "", "", "", "", $user_ids);

            $chatService = new ChatService();
            $chatService->sendImMsgUserToUser($order->id, '系统通知', $theme, '', '', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER], [], $user_ids);

            DmaProcessLog::addUserProcessLog(0, $order->id, 1, "system_send_server_question_60_msg", $theme, 5);
        }
    }

    public function sendAfterBodyImageNotice()
    {
        $start_time = date("Y-m-d", strtotime("-1 day"));
        $end_time = date("Y-m-d");
        $orders = Order::whereHas("group")->whereHas("user")->where("status", "FINISHED")->whereBetween("end_time", [$start_time, $end_time])->get();
        foreach ($orders as $order) {
            if (empty($order->user->after_body_image))
                continue;
            $chatService = new ChatService();
            $chatService->sendGroupMsg($order->user_id, '方案后身体照片', '请点击上传方案后身体照片', 'https://images.health.ufutx.com/202412/12/abc84f7b2b5dc2b94d6d27ca4eeb09ab.png', "yfheal://app/push/UpdateHealthBodyPhotoAfter", []);
        }
    }

    public function sendAfterBodyImageTask()
    {
        $start_time = date("Y-m-d ", strtotime("-4 day"));
        $end_time = date("Y-m-d ", strtotime("-3 day"));
        $orders = Order::whereHas("group")->whereHas("user")->where("status", "FINISHED")->whereBetween("end_time", [$start_time, $end_time])->get();
        foreach ($orders as $order) {
            if (empty($order->user->after_body_image))
                continue;
            $theme = "请跟进【" . $order->name . "】上传【方案后照片】";
            TaskService::AddTask(0, 0, $theme, [1, 2, 3], $order->id);
        }
    }

    public function sendCleanNotice()
    {
        $start_time = date("Y-m-d H:i:s", strtotime("-3 month"));
        $orders = Order::whereHas("group")->where("status", "FINISHED")->where("end_time", ">", $start_time)->get();
        foreach ($orders as $order) {
            // $msg = "😊亲爱的【{$order->name}】，一份温馨小建议轻轻来送达！每周抽出 1 天做清洁保养巩固，有助于维持良好的身体状态，能让您的健康生活持续向好，更加精彩。";
            // $imMsg = new Msg(config('chat.im.app_id'), config('chat.im.app_secret'));
            // $imMsg->sendMsg(make_wangyiyun_accid($order->group->owner_id), 1, $order->group->im_chat_id, 0, json_encode(['msg' => $msg]));
            // 改为通知教练
            $chatService = new ChatService();
            $msg = "请提醒用户【{$order->name}】每周抽出1-3天做清洁保养巩固，有助于维持良好的身体状态。（可根据客户具体身体情况进行建议）";
            $chatService->sendImMsgUserToUser($order->id, '系统通知', $msg, '', '', [ServiceRole::MAIN_COACH, ServiceRole::COACH], [], []);

        }
    }

    public function sendQuestionNotice()
    {
        Log::info("方案后服务问卷提醒");
        $nowDate = date("Y-m-d");
        $orders = Order::whereDoesntHave("afterDmaQuestion")->whereDoesntHave("orderSurveys")->where("service_status", "FINISHED")->get();
        foreach ($orders as $order) {
            $log_at = DmaProcessLog::where("order_id", $order->id)->where("key_name", "mark_order_finish")->orderBy("id", "desc")->value("created_at");
            if ($log_at) {
                $log_at = $log_at->toDateString();
            }
            $day = CommonService::diffDays($nowDate, $log_at);
            Log::info("订单id:" . $order->id . " day=" . $day);
            if ($day >= 60 && $day <= 70 && $day % 3 == 0 && $order->group && $order->group->im_chat_id) {
                // $imMsg = new Msg(config('chat.im.app_id'), config('chat.im.app_secret'));
                // $imMsg->sendMsg(make_wangyiyun_accid($order->group->owner_id), 1, $order->group->im_chat_id, 0, json_encode(['msg' => "【{$order->name}】请抽空完成方案后服务问卷，您的反馈非常重要，可以帮助我们了解您方案中的感受，感谢您的支持！"]));
                $chatService = new ChatService();
                $msg = "提醒【{$order->name}】抽空完成方案后服务问卷";
                $chatService->sendImMsgUserToUser($order->id, '系统通知', $msg, '', '', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER], [], []);

            }
        }
    }
}

