<?php

namespace app\admin\command;

use app\admin\model\TaskSteps;
use app\admin\services\MqttMessageClient;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\helper\Arr;

class AutoTask extends Command
{
    public function configure()
    {
        $this
            ->setName('AutoTask')
            ->setDescription('自动下发定时指令');
    }

    public function execute(Input $input, Output $output)
    {
        while (true) {
            $time = Date('H:i');
            $list = TaskSteps::with(['task.device'])->whereRaw("DATE_FORMAT(start_time, '%H:%i')='{$time}'")->whereOrRaw("DATE_FORMAT(end_time, '%H:%i')='{$time}'")->select();
            if ($list) {
                foreach ($list as $item) {
                    $device_sn = $item->task->device[0]->device_sn;
                    if ($device_sn && substr($item->start_time, 0, 5) === $time) {
                        // 发送开始
                        $this->publish($device_sn, 'RUN', $item->name, [
                            'SCRIPT' => base64_encode("log('aa')"),
                            'CONFIG' => [],
                        ]);
                        $this->publish($device_sn, 'START', $item->name, []);
                    }
                    if ($device_sn && substr($item->end_time, 0, 5) === $time) {
                        // 发送结束
                        $this->publish($device_sn, 'STOP', $item->name, []);
                    }
                }
            }
            sleep(60);
        }
    }

    public function publish($device_sn, $action, $name, $data = [])
    {
        MqttMessageClient::getInstance()->publish('/device/' . $device_sn . '/master', json_encode([
            'SCRIPT_ACTION' => $action,
            'SCRIPT_NAME' => $name,
            'SCRIPT_DATA' => $data,
        ]), 0);
        echo sprintf("发送指令 %s %s %s %s\n", $device_sn, $action, $name, json_encode($data));
    }
}