<?php

namespace App\Console\Commands\Video;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Modules\Video\Services\WechatCheckSyncService;

class WechatCheckGetTask extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'Video:WechatCheckGetTask {--task_ids= : 英文逗号分割的任务id}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '查询短剧同步到微信的任务状态';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $task_ids = $this->option('task_ids');
        $taskIdArr = null;
        if($task_ids) {
            $taskIdArr = explode(',', trim($task_ids, ','));
        }
        DB::table('video_series_wechat_check')
            ->whereIn('sync_status', [1,2])
            ->where('sync_task_id', '<>', '')
            ->where('is_enabled', 1)
            ->when($taskIdArr, function ($query, $taskIdArr) {
                return $query->whereIn('task_id', $taskIdArr);
            })->orderBy('id', 'asc')
            ->chunk(100, function ($items) {
                $now = date('Y-m-d H:i:s');
                foreach ($items as $item) {
                    $taskInfo = WechatCheckSyncService::getTask($item);
                    if($taskInfo && 1 == $taskInfo['task_type']) {
                        if(in_array($taskInfo['status'], [3,4])) {
                            DB::table('video_series_wechat_check')
                                ->where(['id' => $item->id])
                                ->update([
                                    'status' => $taskInfo['status'],
                                    'remark' => $taskInfo['errmsg'] ?? '',
                                    'media_id' => $taskInfo['media_id'] ?? '',
                                    'updated_at' => $now,
                                    'sync_task_info' => \json_encode($taskInfo),
                                ]);
                        }
                    }
                }
            });
    }
}