<?php

namespace App\Crontab;

use EasySwoole\Crontab\JobInterface;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;
use App\Models\BalancePushSet;
use App\Models\ShopGoods;
use App\Models\SeckillGoods;


class SeckillCrontab implements JobInterface
{

    protected $set; //秒杀库存归还

    public function jobName(): string
    {
        // 定时任务的名称
        return 'SeckillCrontab';
    }

    public function crontabRule(): string
    {
        // 定义执行规则 根据 Crontab 来定义
        // 每分钟执行一次
        return '*/1 * * * *';
    }

    public function run()
    {
        // 定时任务的执行逻辑
        $this->set = BalancePushSet::create()->get()->toArray();
        //是否启用
        if($this->set['enable']!=1){
            return;
        }
        $endTime = time();
        $sql = "SELECT a.`name`,b.active_id,b.operators_id,b.goodsid,b.total FROM ims_superdesk_shop_seckill_active a LEFT JOIN ims_superdesk_shop_seckill_active_operators_goods b ON a.id=b.active_id WHERE a.endtime<{$endTime} AND b.total>0";
        $queryBuild = new QueryBuilder();
        $queryBuild->raw($sql);
        $res_data = DbManager::getInstance()->query($queryBuild, true, 'default')->toArray();
        foreach($res_data['result'] as $k=>$val){
            ShopGoods::create()->update([
                'total' => QueryBuilder::inc(intval($val['total'])),
            ], ['id' => $val['goodsid']]);
            SeckillGoods::create()->update([
                'total' => 0,
            ], ['active_id' => $val['active_id'], 'operators_id' => $val['operators_id'], 'goodsid' => $val['goodsid']]);
        }
    }

    public function onException(\Throwable $throwable)
    {
        // 捕获 run 方法内所抛出的异常
    }


}