<?php

namespace App\Console\Commands\Callback;

use App\Modules\Advertiser\Models\AdvertiserPromotionConfigTime;
use App\Modules\Advertiser\Models\TiktokAdvertiser;
use App\Modules\Advertiser\Services\AdvertiserService;
use App\Modules\Advertiser\Services\TimeConfigService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '巨量账户级回传比例自动刷新';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $this->start();
    }

    public function start(){
        $list = DB::table('juliang_account_promotion_config_time')
            ->where('is_enable',1)->orderBy('id')->get();

        foreach ($list as  $item) {
            $is_exec = $this->timeThan($item->config_time);
            if (!$is_exec || $item->next_exec_time != date("Y-m-d")) {
                continue;
            }
            $this->setReportType($item);
        }
    }

    /**
     * 判断任务时间点和 当前的时间点比对
     * @param  [type] $str [description]
     * @return [type]      [description]
     */
    private function timeThan($str)
    {
        $config_time = strtotime(date('Y-m-d').' '.$str);
        if (time() >= $config_time) {
            return true;
        }
        return false;
    }


    public  function setReportType($item){
        $now = date('Y-m-d H:i:s');
        $res = DB::table('juliang_account_promotion_config_time')->where('id',$item->id)
            ->update(['latest_exec_time'=> date('Y-m-d H:i:s',time()),
                'next_exec_time'=>date("Y-m-d",strtotime('+1 day')),
                'updated_at'  => $now]);
        if ($res) {
            DB::table('juliang_account_rate_config_log')
                ->where(['company_uid' => $item->company_uid, 'account_id' => $item->account_id, 'is_enabled' => 1])
                ->update(['is_enabled' => 0, 'updated_at' => $now]);
            DB::table('juliang_account_promotion_protect_record')
                ->where('optimizer_uid', $item->company_uid)
                ->where('advertiser_id', $item->account_id)
                ->where('is_enabled', 1)
                ->update(['is_enabled' => 0, 'updated_at' => $now]);
            DB::table('juliang_account_rate_config_log')
                ->insert([
                    'company_uid' => $item->company_uid,
                    'account_id' => $item->account_id,
                    'config_per' => $item->config_per,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
        }
    }
}