<?php

namespace App\Console\Commands;

use App\Facades\ChatService;
use App\Models\Band;
use App\Models\BatteryHistory;
use App\Models\DailyStep;
use App\Models\Guide;
use App\Models\GuideTemplate;
use App\Models\Order;
use App\Models\ServiceRole;
use Illuminate\Console\Command;

class RemindDailyStep extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'remind:daily_step';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 正在进行中的订单
        $orders = Order::whereHas("guides", function ($sql) {
            $sql->where("phase_date", ">=", date("Y-m-d", strtotime("-1 day")));
        })->where("status", Order::STARTING_STATUS)->get();
        foreach ($orders as $order) {
            // 用户的步数
            $step = $this->getDailyStep($order->user_id);
            // 餐单模板步数
            $templateStep = $this->getTemplateStep($order->id);
            if (empty($templateStep))
                continue;
            // 电量
            list($timestamp, $battery_percentage) = $this->getBatteryInfo($order->user_id);
            // 获取消息内容
            $noticeMsg = $this->getNoticeMsg((string) $order->name, $step, $templateStep, (int) $battery_percentage, $timestamp);
            // 发送消息
            ChatService::sendImMsgUserToUser($order->id, "系统通知", $noticeMsg, "", "", [ServiceRole::MAIN_COACH, ServiceRole::COACH, ServiceRole::CUSTOMER]);
        }
        return Command::SUCCESS;
    }

    public function getDailyStep(int $userId): int
    {
        $time = date("Y-m-d", strtotime("-1 day"));
        $step = DailyStep::where(["user_id" => $userId, "date" => $time])->value("step");
        return $step ?: 0;
    }

    public function getTemplateStep(int $orderId): int
    {
        $step = 0;
        $time = date("Y-m-d", strtotime("-1 day"));
        $guide = Guide::where(["order_id" => $orderId, "phase_date" => $time])->first();
        if (empty($guide))
            return $step;
        switch ($guide->phase_title) {
            case "装修日":
                $type = 0;
                break;
            case "准备日":
                $type = 1;
                break;
            case "清洁日":
                $type = 2;
                break;
            default:
                return $step;
        }
        $step = GuideTemplate::where(["order_id" => $orderId, "type" => $type])->value("step");
        return $step ?: 0;
    }

    public function getBatteryInfo(int $userId): array
    {
        $timestamp = $battery_percentage = "";
        $band = Band::where(["user_id" => $userId, "status" => 1])->first();
        if (empty($band))
            return [$timestamp, $battery_percentage];

        $log = BatteryHistory::where(["band_id" => $band->id])->orderByDesc("timestamp")->first();
        if (empty($log))
            return [$timestamp, $battery_percentage];

        return [$log->timestamp, $log->battery_percentage];
    }

    public function getNoticeMsg(string $name, int $step, int $templateStep, int $battery_percentage, string $timestamp): string
    {
        $status = ($step >= $templateStep) ? "完成了" : "未完成";
        $msg = "用户【" . $name . "】" . $status . "走路目标：实际步数:" . $step . "步, 目标步数：" . $templateStep . "步 \n";
        if ($battery_percentage) {
            $msg .= "最后一次数据同步时间：" . $timestamp . " (当时电量：" . $battery_percentage . "%)";
        } else {
            $msg .= "没有最近一次手环电量同步信息";
        }
        return $msg;
    }
}
