<?php
/**
 * 头条小程序接口类
 * Created by PhpStorm.
 * User: phperstar
 * Date: 2020/6/16
 * Time: 6:35 PM
 */

namespace Util\ByteDance;

use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Factory;

class Microapp
{
    /**
     * 小程序 appId
     * @var string $appid
     */
    private $appid;

    /**
     * 小程序 appSecret
     * @var string $appSecret
     */
    private $appSecret;

    /**
     * openId 和 session_key关联关系缓存key
     */
    private $openidAndSessionKey = 'byteDanceOpenidAndSessionKey';

    // access_token 全局唯一接口调用凭据
    private $access_token = 'byteDanceAccessToken';

    /**
     * path和小程序码地址关联关系缓存key
     */
    private $pathAndWxacodeunlimitKey = 'byteDanceQRCode';

    /**
     * 微信小程序接口主域名
     * @var string $apiUrl
     */
    private $apiUrl = 'https://developer.toutiao.com/api/apps/';




    public function __construct($appid='', $appsecret='')
    {
        $this->appid = $appid;
        $this->appSecret = $appsecret;
    }

    /**
     * 登录凭证校验
     * 官方文档对应地址:https://microapp.bytedance.com/dev/cn/mini-app/develop/server/log-in/code2session
     * @param string $jsCode 通过 wx.login 接口获得临时登录凭证 code
     * @return ResultWrapper
     */
    public function code2session($jsCode)
    {
        $apiUrl = $this->apiUrl.'jscode2session?appid='.$this->appid.'&secret='.$this->appSecret.'&code='.$jsCode;
        $reponse =  request($apiUrl);

        if($reponse['httpcode'] != 200){
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }else{
            $reponseData = json_decode($reponse['content'], true);
            if( isset($reponseData['errcode']) ){
                return ResultWrapper::fail($reponseData['errmsg'], $reponseData['errcode']);
            }
            Factory::cache('default')->hset($this->openidAndSessionKey, $reponseData['openid'], $reponseData['session_key']);
            return ResultWrapper::success(['openid'=>$reponseData['openid']]);
        }
    }

    /**
     * 获取基础access_token
     * 官方文档对应地址:https://microapp.bytedance.com/dev/cn/mini-app/develop/server/interface-request-credential/getaccesstoken
     * @return ResultWrapper
     */
    public function token()
    {
        $access_token =  Factory::cache('default')->get($this->access_token.':'.$this->appid);
        if(!empty($access_token)){
            return ResultWrapper::success($access_token);
        }

        $apiUrl = $this->apiUrl.'token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->appSecret;
        $reponse =  request($apiUrl);

        if($reponse['httpcode'] != 200){
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }else{
            $reponseData = json_decode($reponse['content'], true);
            if( isset($reponseData['errcode']) && $reponseData['errcode'] != 0){
                return ResultWrapper::fail($reponseData['errmsg'], $reponseData['errcode']);
            }

            Factory::cache('default')->set($this->access_token.':'.$this->appid, $reponseData['access_token'], 7000);
            return ResultWrapper::success($reponseData['access_token']);
        }
    }

    /**
     * 获取小程序/小游戏的二维码
     * 官方文档地址：https://microapp.bytedance.com/dev/cn/mini-app/develop/server/qr-code/createqrcode
     */
    public function createQRCode($access_token, $path)
    {
        $key = md5($this->appid.$path);
        $imgsrc = Factory::cache('default')->hget($this->pathAndWxacodeunlimitKey, $key);
        if(!empty($imgsrc)){
            return ResultWrapper::success($imgsrc);
        }

        $postData = [
            'access_token' => $access_token,
            'appname'      => 'douyin',
            'path' => $path,
            'width' => 430,
            'set_icon' => true,
        ];

        $curl_option = [
            CURLOPT_HTTPHEADER => [
                'Content-Type:application/json',
            ],
        ];

        $apiUrl = $this->apiUrl.'qrcode';
        $reponse =  request($apiUrl, json_encode($postData), 10, true, $curl_option);

        if($reponse['httpcode'] != 200){
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }else{
            if( $reponse['content_type'] == 'image/png' ){
                $base64   = 'data:image/png;base64,'.base64_encode($reponse['content']);
                $upload = Factory::baseImg();
                $upload->move($base64);
                $imgsrc = $upload->getSaveName();
                Factory::cache('default')->hset($this->pathAndWxacodeunlimitKey, $key, $imgsrc);
                return ResultWrapper::success($imgsrc);
            }

            $reponseData = json_decode($reponse['content'], true);
            if( isset($reponseData['errcode']) && $reponseData['errcode'] != 0 ){
                return ResultWrapper::fail($reponseData['errmsg'], $reponseData['errcode']);
            }
        }
    }
}