<?php

namespace app\task;

use app\common\logic\task\TaskLogic;
use app\common\model\Company;
use app\common\model\task_scheduling\TaskScheduling;
use app\common\model\task_template\TaskTemplate;
use app\job\TaskAdd;
use app\job\TownTaskAdd;
use think\facade\Log;
use yunwuxin\cron\Task;

class TownTaskCron extends Task {

    public function configure()
    {
        $this->daily(); //设置任务的周期,每天执行一次,更多的方法可以查看源代码,都有注释
        // $this->everyMinute();//每分钟
    }
    /**
     *  镇农科公司任务下发
     */
    protected function execute()
    {
        //任务下发
        $time = strtotime(date('Y-m-d'));
        // 查询系统 所有镇农科公司 未下发 的 任务安排
        $taskSchedulingList = TaskScheduling::where('cron_time', '<', $time)->where('status', 1)->where('company_type', 41)->with('company_info')->select()->toArray();

        $taskSchedulingIds = [];
        $companyIds = [];
        foreach ($taskSchedulingList as $k => $taskScheduling) {
            $templateList = TaskTemplate::where('status', 1)->where('task_scheduling', $taskScheduling['id'])->limit(30)->select()->toArray();
            $taskSchedulingIds[] = $taskScheduling['id'];
            $companyIds[] = $taskScheduling['company_id'];
            foreach ($templateList as $template) {
                queue(TownTaskAdd::class, $template);
//                TaskLogic::TownCronAdd($template); // 手动下发用
            }

            if (empty($templateList)) {
                unset($taskSchedulingList[$k]);
            }
        }
        Company::where('id', 'in', $companyIds)->inc('day_count')->update();
        TaskScheduling::where('id', 'in', $taskSchedulingIds)->update(['cron_time' => time()]);
        Log::info('定时任务下发执行成功' . date('Y-m-d H:i:s'));
    }

}