<?php

namespace App\Console\TikTok;

use App\Dao\Account\AccountDao;
use App\Services\OpenApi\OpenService;
use App\Libs\TikTok\Kernel\Exceptions;
use Illuminate\Console\Command;

class ClientTokenManage extends Command
{
    /**
     * @var string
     */
    protected $signature = 'tiktok:clientToken:refresh';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '抖音client token刷新管理';

    private $accountDao;
    private $openService;

    public function __construct(
        AccountDao  $accountDao,
        OpenService $openService
    )
    {
        parent::__construct();
        $this->accountDao  = $accountDao;
        $this->openService = $openService;
    }

    /**
     * @return void
     * @throws Exceptions\HttpException
     * @throws Exceptions\InvalidArgumentException
     * @throws Exceptions\InvalidConfigException
     * @throws Exceptions\RuntimeException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function handle()
    {
        // 获取所有小程序
        $apps = $this->accountDao->getMiniApps();
        if (empty($apps)) {
            return;
        }

        foreach ($apps as $app) {
            // 数据库记录的token到期时间
            $tokenExpiresAt = getProp($app, 'client_token_expires_at');

            // token到期前10分钟开始更新
            if (strtotime($tokenExpiresAt) - time() > 600) {
                continue;
            }

            // 实例化并获取token
            $tokenData = $this->openService->getOpenInstance([
                'app_id'  => getProp($app, 'app_id'),
                'secret'  => getProp($app, 'app_secret'),
            ])->getClientToken(true);
            if ($tokenData) {
                // 更新数据库
                $seconds = (int)getProp($tokenData, 'expires_in');
                $this->accountDao->updateMiniApp(['id' => getProp($app, 'id')], [
                    'client_token'            => getProp($tokenData, 'access_token'),
                    'client_token_expires_at' => date('Y-m-d H:i:s', strtotime("+ $seconds second")),
                ]);
            }
        }
    }

}