<?php
namespace Base\Domain\Authorization\AuthorizationType;

use Base\Domain\Authorization\AuthorizationBase;
use Base\Domain\lib\WeChatOpen\WeChatLogin\WeChatLogin as WeChatLoginLib;
use PhalApi\Exception\BadRequestException;
use PhalApi\Logger;
use PhalApi\Logger\FileLogger;

class WeChat extends AuthorizationBase {

    //第三方登录类型 1微信----对应数据库表pp_authorization中的authorization_type字段
    protected $authorizationType = 1;

    //基础配置
    protected $config = [];

    //微信工具类对象
    protected $weChatLibObject = null;

    //初始化配置和对象
    public function ini(){
        //获取微信配置
        $this->config = \PhalApi\DI()->config->get('app.authorization_app.weChat');

        $this->weChatLibObject = new WeChatLoginLib();
        //配置初始化
        $this->weChatLibObject->init($this->config['appid'], $this->config['secret'], $this->config['login_redirect_uri']);
    }

    //获取微信code码，也就是获取微信登录链接
    public function getCode($successJump = '', $extraInfo = ''){
        //获取微信code
        $state = md5(uniqid('wechatlogin')); // 升级版，使用官方函数生成
        $weChatUrl =  $this->weChatLibObject->getWeChatCode($state);


        //额外换成数据
        $stateData = [
            'successJump' => $successJump, //成功后重定向的页面
            'extraInfo' => $extraInfo, //额外信息
        ];

        //设置缓存
        \PhalApi\DI()->cache->set($state, json_encode($stateData), 600);

        //判断是否有token
        $access_token = \PhalApi\DI()->request->get('access_token');
        if (!empty($access_token)){
            //绑定的，缓存token
            \PhalApi\DI()->cache->set($state."_token", $access_token, 600);
        }

        $result = $weChatUrl;
        return $result;
    }
    //获取access_token
    protected function getAccessToken($code){
       return $this->weChatLibObject->getAccessToken($code);
    }
    //获取用户信息
    protected function getUserInfo($accessToken, $openid){
        return $this->weChatLibObject->getUserinfo($accessToken, $openid);
    }

    //获取第三方信息(微信用户的信息)
    protected function getWeChatUserInfo($requestArr){
        //获取微信AccessToken
        $accessTokenInfo = $this->getAccessToken($requestArr['code']);
        if (empty($accessTokenInfo)){
            throw new BadRequestException('获取AccessToken失败');
        }

        //获取第三方信息
        $weChatuserInfo = $this->getUserInfo($accessTokenInfo['access_token'], $accessTokenInfo['openid']);

        if (empty($weChatuserInfo)){
            throw new BadRequestException('获取微信用户信息失败');
        }
        return $weChatuserInfo;
    }

    //微信回调处理
    public function weChatCallback(){
        //直接获取信息
        $parmStrArr = [
            'code'=>$_GET['code'],
            'state'=>$_GET['state'],
        ];

        //调试
//        $parmStrArr = [
//            'code'=>1,
//            'state'=>1,
//        ];
//        \PhalApi\DI()->cache->set($parmStrArr['state'],1);


//        //记录请求日志
        //记录日志
        \PhalApi\DI()->logger = new FileLogger(API_ROOT . '/runtime/weChatLogin', Logger::LOG_LEVEL_DEBUG | Logger::LOG_LEVEL_INFO | Logger::LOG_LEVEL_ERROR);
        \PhalApi\DI()->logger->log('info', '测试', json_encode($parmStrArr));

        //判断是否是非法请求
        if (empty(\PhalApi\DI()->cache->get($parmStrArr['state']))){

            //过期的往首页跳
            $vuePage = \PhalApi\DI()->config->get('app.vue');
            $url = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'].$vuePage['index'];
            header("Location: {$url}");

            \PhalApi\DI()->logger->log('info', '非法登录，或已过期', $parmStrArr['state']);
            header("Location: /platform/login");
            exit;
        }


        //单独的处理
        $weChatInfo =  $this->getWeChatUserInfo($parmStrArr);

        //调试
//        $weChatInfo = [
//            'openid' => 'o_bna6kxhdKXJ0873CmS0vBt28II',
//            'nickname' => 'nickname',
//            'sex' => 1,
//            'language' => 'zh_CN',
//            'city' => 'Zhanjiang',
//            'province' => 'Guangdong',
//            'country' => 'CN',
//            'headimgurl' => 'https://thirdwx.qlogo.cn/mmopen/vi_32/9bYp0ibib3sibvgR8icI2MyslWs30icIvAUo7QseWgpDD66tgpibm4bC6VJbDsqLJOQT7Cv14T7srW0GACqpPjRY1myA/132',
//            'unionid' => 'oXLtB1UOxLC19jiaUAV5L4D5g3mQ'
//        ];

        //进行业务业务处理
        $weChatBusiness =  new WeChatBusiness();
        $weChatBusiness->state = $parmStrArr['state'];
        $weChatBusiness->businessHandle($weChatInfo);
    }

}
