<?php

namespace App\Services\Vendor\QQprogram;

use App\Exceptions\AlertException;
use App\Jobs\WelcomeJob;
use App\Models\Log\FpdxMiniprogramIntoQueueModel;
use App\Services\Service;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Ixudra\Curl\Facades\Curl;

class AuthService extends Service
{

    /**
     * 通过code换取session
     * @param  string  $jscode
     * @return Arr|mixed
     * @throws AlertException
     */
    public function code2Session(string $jscode)
    {
        $appid = config("qqprogram.app_id");
        $secret = config("qqprogram.app_secret");
        $url = "https://api.q.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$jscode}&grant_type=authorization_code";
        $result = Curl::to($url)->asJsonResponse(true)->get();
        if (0 == $result['errcode']) {
            try {
                if ($result['openid'] && !FpdxMiniprogramIntoQueueModel::where('openid', $result['openid'])->exists()) {
                    WelcomeJob::dispatch($result['openid'])->delay(Carbon::now()->addHours(1));
                    FpdxMiniprogramIntoQueueModel::create(['openid' => $result['openid'], 'created_at' => time()]);
                }
            } catch (\Exception $exception) {
            }

            return $result;
        } else {
            throw new AlertException($result['errmsg'], $result['errcode']);
        }
    }
}
