<?php

namespace App\Console\Commands\Wechat;

use App\Models\Common\TokenModel;
use Illuminate\Console\Command;

class AccessTokenCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wechat:access-token';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '公众号刷新access-token';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $medias = TokenModel::whereIn('type', ['微信小程序', '微信公众号', '微信服务号', '微信订阅号', '微信移动App'])->get();
        foreach ($medias as $media) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$media->app_id}&secret={$media->app_secret}";
            $response = \Curl::to($url)->asJson()->get();
            if (isset($response->errcode) && $response->errcode != 0) {
                continue;
            }
            $media->access_token = $response->access_token;
            $media->save();

            \DB::connection('mysql_datalog')
                ->table('koudai.public_access_token')
                ->where('user_name', $media->user_name)
                ->update([
                    'access_token' => $response->access_token,
                    'updated_at' => time()
                ]);
        }


        $medias = TokenModel::where('type', 'QQ小程序')->get();
        foreach ($medias as $media) {
            $url = "https://api.q.qq.com/api/getToken?grant_type=client_credential&appid={$media->app_id}&secret={$media->app_secret}";
            $response = \Curl::to($url)->asJson()->get();
            if (isset($response->errcode) && $response->errcode != 0) {
                continue;
            }
            $media->access_token = $response->access_token;
            $media->save();

            \DB::connection('mysql_datalog')
                ->table('koudai.public_access_token')
                ->where('user_name', $media->user_name)
                ->update([
                    'access_token' => $response->access_token,
                    'updated_at' => time()
                ]);
        }
    }
}
