<?php

namespace App\Console\Commands;

use App\Facades\GuideService;
use App\Facades\TaskService;
use App\Facades\WechatService;
use App\Models\DmaProcessLog;
use App\Models\Food;
use App\Models\Guide;
use App\Models\GuideScheme;
use App\Models\Order;
use App\Models\ServiceRole;
use App\Models\ServiceRoleOrder;
use App\Models\ServiceUser;
use App\Services\ChatService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class OrderSchemeRemainMsg extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:scheme:remain:msg {--order_id=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '方案营养素余量通知';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $order_id = $this->option('order_id');
        // 需要检查的餐单方案
        $schemes = $this->getStartingSchemes($order_id);
        // 检查方案中的营养素是否预警
        foreach ($schemes as $scheme) {
            $msg = $this->rateResult($scheme);
            Log::info($msg);
            $this->info($msg);
            if ($msg) {
                $url = "https://health.ufutx.com/go_html/dma_h5_biz/app/exercise/exerciseDetail?orderId=" . $scheme->order_id . "&tabIndex=1";
                $chatService = new ChatService();
                $chatService->sendImMsgUserToUser($scheme->order_id, '系统通知', $msg, 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', $url, [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER]);
            }

        }
        return Command::SUCCESS;
    }



    public function getStartingSchemes($order_id)
    {
        $order_ids = Order::where('status', 'STARTING')->where('user_id', '<>', 0);
        if ($order_id) {
            $order_ids = $order_ids->where("id", $order_id);
        }
        $order_ids = $order_ids->select('id')->pluck('id')->toArray();
        $schemes = GuideScheme::whereIn('order_id', $order_ids)->select('order_id', 'scheme')->select('scheme', 'order_id')->get();

        return $schemes;
    }

    public function rateResult($scheme)
    {
        $order = Order::find($scheme->order_id);
        $msg = "";
        // 当天营养素和使用量
        $guideFoods = $this->getGuideFood($scheme);
        // 方案中所有营养素和份数
        $scheme = $scheme->scheme;
        foreach ($guideFoods as $food) {
            // 营养素信息
            $foodObj = Food::find($food["id"]);
            if (empty($foodObj))
                continue;
            // 总量 = 份数 * 量
            $schemeObj = collect($scheme)->where("id", $food["id"])->first();
            if (empty($schemeObj))
                continue;
            $num = $schemeObj->num;
            $total_num = round($num * $foodObj->quantity);
            // 已使用的量
            $use_num = $this->getUseGuideNum($order->id, $foodObj->id);
            // 余量
            $remain_num = round($total_num - $use_num);
            if ($remain_num < 0) {
                $remain_num = 0;
            }
            // 比例
            $rate = round($remain_num / $total_num, 2);
            // 是否超过10%
            if ($rate < 0.1) {
                Log::info("总量：" . $total_num . " 使用量：" . $use_num . " 剩余量：" . $remain_num . " 剩余比例：" . $rate);
                $msg .= '营养素id:' . $foodObj->id . ' 营养素:' . $foodObj->name . ' 余量:' . $remain_num . " 剩余率:" . $rate . '%' . "\n";
            }
        }
        $msg_title = '订单号:' . $order->trade_no . "\n" . "餐单日期：" . date("Y-m-d") . "\n" . '用户:' . $order->name . "\n" . '电话:' . $order->mobile . "\n";
        if ($msg) {
            $msg = $msg_title . $msg;
        }
        return $msg;
    }

    public function getUseGuideNum($order_id, $food_id)
    {
        $num = 0;
        $guides = Guide::where("order_id", $order_id)->where("phase_date", "<=", date("Y-m-d"))->get();
        foreach ($guides as $guide) {
            $menu = json_decode($guide->menu);
            foreach ($menu as $item) {
                foreach ($item->nutrient as $nutrient) {
                    if ($nutrient->id != $food_id)
                        continue;
                    $num += $nutrient->oneNum;
                }
            }
        }
        return $num;
    }

    public function getGuideFood($scheme)
    {
        Log::info("获取当天餐单营养素订单：" . $scheme->order_id);
        $idArr = [];
        $array = [];
        // 餐单日历
        $guide = Guide::where("order_id", $scheme->order_id)->where("phase_date", date("Y-m-d"))->first();
        if (empty($guide))
            return $array;
        $menu = json_decode($guide->menu);
        foreach ($menu as $item) {
            foreach ($item->nutrient as $nutrient) {

                if (in_array($nutrient->id, $idArr)) {
                    $array[$nutrient->title] = ["id" => $nutrient->id, "title" => $nutrient->title, "num" => $nutrient->oneNum + $array[$nutrient->title]["num"]];
                } else {
                    $idArr[] = $nutrient->id;
                    $array[$nutrient->title] = ["id" => $nutrient->id, "title" => $nutrient->title, "num" => $nutrient->oneNum];
                }

            }
        }
        return $array;
    }


    public function backup()
    {
        $order_ids = Order::where('status', 'STARTING')->where('user_id', '<>', 0)->select('id')->pluck('id')->toArray();

        $schemes = GuideScheme::whereIn('order_id', $order_ids)->select('order_id', 'scheme')->pluck('scheme', 'order_id');
        $guides = Guide::whereIn('order_id', $order_ids)->orderBy('phase_date', 'asc')->get();
        $new_guides = [];
        foreach ($guides as $guide) {
            $new_guides[$guide->order_id]['guides'][] = $guide;

            if (!isset($new_guides[$guide->order_id]['scheme'])) {
                $new_guides[$guide->order_id]['scheme'] = [];
            }
            if (isset($schemes[$guide->order_id])) {
                $new_guides[$guide->order_id]['scheme'] = json_decode($schemes[$guide->order_id]);
            }
        }

        $order_scheme = [];
        foreach ($new_guides as $order_id => $item) {
            [$guides_arr, $scheme_food, $flag, $msg] = GuideService::getQuantity($item['scheme'], $item['guides']);
            if (empty($msg)) {
                continue;
            }
            $order_scheme[] = $msg;
        }
        //重组数组
        $new_scheme = [];
        foreach ($order_scheme as $sub_array) {
            foreach ($sub_array as $item) {
                $new_scheme[] = $item;
            }
        }
        //遍历数据
        $orderIds = [];
        foreach ($new_scheme as $value) {
            if ($value['rate'] > 20) {
                continue;
            }

            if (in_array($value["order_id"], $orderIds))
                continue;
            $orderIds[] = $value["order_id"];
            $order = Order::where('id', $value['order_id'])->first();
            // $service_user_ids = ServiceRoleOrder::where('order_id',$value['order_id'])->distinct()->pluck('user_id');
            // $work_user_ids = ServiceUser::whereIn('user_id',$service_user_ids)->pluck('work_user_id');

            $message = '订单号:' . $order->trade_no . "\n" . '餐单日期:' . $value['phase_date'] . "\n" . '餐单类型:' . $value['phase_title'] . "\n" . '用户:' . $order->name . "\n" . '电话:' . $order->mobile . "\n" . '营养素:' . $value['title'] . "\n" . '余量:' . $value['remain_quantity'] . "\n" . "剩余率:" . $value['rate'] . '%';
            // foreach ($work_user_ids as $work){
            //     if(!$work){
            //         continue;
            //     }
            // WechatService::sendWorkMessage($work,'text',['content'=>$message]);
            // }
            $chatService = new ChatService();
            $chatService->sendImMsgUserToUser($order->id, '系统通知', $message, 'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png', 'yfheal://app/push/IMGroup', [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER]);

        }

        foreach ($orderIds as $orderId) {
            $order = Order::where('id', $orderId)->first();
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "lack_nutrient", "用户营养素余量不足", 0, 5);
            DmaProcessLog::addUserProcessLog($order->user_id ?? 0, $order->id ?? 0, 1, "send_lack_nutrient", "系统发送营养素余量通知", 0, 5);

        }
    }
}
