<?php

namespace App\Console\Commands\Video\WechatCheck;

use App\Service\Miniprogram\Wechat\AccessTokenService;
use App\Service\Util\Support\Http\HttpRequestService;
use App\Service\Util\Support\Http\WechatURL;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Modules\Common\Support\Http\HttpRequest;
use Modules\Manage\Services\WechatMiniprogramService;
use Modules\Video\Services\WechatCheckSyncService;

class GetTaskInfo extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'WechatCheck:GetTaskInfo {--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('sync_task_id', $taskIdArr);
            })->orderBy('id')
            ->chunk(100, function ($items) {
                $now = date('Y-m-d H:i:s');
                foreach ($items as $item) {
                    $taskInfo = $this->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),
                                ]);
                        }
                    }
                }
            });
    }

    private function getTask($syncInfo) {
        $appid = $syncInfo->appid ?: config('wechat.duanju.masterAppid');
        $accessToken = Redis::get(AccessTokenService::getAccessTokenRedisKey($appid));
        $parsedContent = HttpRequestService::simplePost(WechatURL::vod_gettask . $accessToken, [
            'task_id' => $syncInfo->sync_task_id
        ]);
        if(false === $parsedContent || (0 != $parsedContent['errcode'] ?? 0)) {
            myLog('GetTaskInfo')->error('拉取上传短剧任务查询失败', [
                'task_id' => $syncInfo->sync_task_id,
                'appid' => $appid,
                'result' => $parsedContent,
            ]);
            return [];
        } else {
            return $parsedContent['task_info'];
        }

    }
}