<?php

namespace App\libs\wechat\auth\Gateways;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

class Base
{
    protected $config = [];

    public function __construct()
    {
        $this->config = Config::get('swdz.wechat');
    }

    /**
     * @desc    快速授权
     */
    public function auth(string $scope = 'snsapi_userinfo', string $redirect = null)
    {
        $code = request()->get('code', null);
        if (!$code) {
            header('Location: ' . $this->authUrl($scope, $redirect));

            exit;
        }

        $openInfo = $this->code2Openid($code);
        if (isset($openInfo['errcode']) && \in_array($openInfo['errcode'], [40163, 40029], true)) {
            header('Location: ' . $this->authUrl($scope, $redirect));

            exit;
        }
        if (isset($openInfo['errcode'])) {
            exit($openInfo['errmsg']);
        }
        if ('snsapi_userinfo' === $scope) {
            $userInfo = $this->userSimpleInfo($openInfo['access_token'], $openInfo['openid']);
        } else {
            $userInfo['openid'] = $openInfo['openid'];
        }
        $baseTable = $this->config['appid'] . '_user';
        $userId    = Db::table($baseTable)->where('openid', $userInfo['openid'])->value('user_id');
        if (empty($userId)) {
            $userId = Db::table($baseTable)
                ->insertGetId([
                    'openid'     => $userInfo['openid'],
                    'unionid'    => $userInfo['unionid']    ?? '',
                    'nickname'   => $userInfo['nickname']   ?? '',
                    'headimgurl' => $userInfo['headimgurl'] ?? '',
                    'sex'        => $userInfo['sex']        ?? '',
                    'country'    => $userInfo['country']    ?? '',
                    'province'   => $userInfo['province']   ?? '',
                    'city'       => $userInfo['city']       ?? '',
                    'language'   => $userInfo['language']   ?? '',
                    'created_at' => time(),
                ])
            ;
        }
        $userInfo['user_id'] = $userId;

        return $userInfo;
    }

    /**
     * @desc    获取jssdk
     *
     * @param string $url 需要授权的地址
     * @param array  $api 开放接口列表
     * @param array  $tag 开发能力列表
     *
     * @return array
     */
    public function jssdk(string $url, $api = [], $tag = [])
    {
        $jsApiList = array_merge($api, [
            'checkJsApi',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'hideMenuItems',
            'showMenuItems',
            'hideAllNonBaseMenuItem',
            'getLocalImgData',
            'chooseImage',
        ]);
        $openTagList = array_merge($tag, ['wx-open-launch-weapp', 'wx-open-launch-app']);
        $jsApiTicket = $this->jsApiTicket();
        $timestamp   = time();
        $nonceStr    = uniqid();

        return [
            'debug'       => false,
            'appId'       => $this->config['appid'],
            'timestamp'   => $timestamp,
            'nonceStr'    => $nonceStr,
            'signature'   => sha1('jsapi_ticket=' . $jsApiTicket . '&noncestr=' . $nonceStr . '&timestamp=' . $timestamp . '&url=' . $url),
            'jsApiList'   => $jsApiList,
            'openTagList' => $openTagList,
        ];
    }

    /**
     * @desc    获取授权地址
     *
     * @param string $scope 授权方式 snsapi_base|snsapi_userinfo
     */
    public function authUrl(string $scope = 'snsapi_userinfo', string $redirect = null): string
    {
    }

    /**
     * @desc    使用授权code换取openid
     */
    public function code2Openid(string $code): array
    {
    }

    /**
     * @desc    获取用户基础信息
     */
    public function userSimpleInfo(string $accessToken, string $openid): array
    {
    }

    /**
     * @desc    获取用户详细信息
     */
    public function userDetailInfo(string $openid): array
    {
    }

    /**
     * @desc    获取 JSAPI TICKET
     *
     * @return string
     */
    public function jsApiTicket()
    {
    }
}
