<?php
namespace app\common\lib\built;
use app\platform\model\AppletGrant;
class WxApplet
{
    public $platform_applet_config; 
    protected $platform_id; 
    protected $request;
    public function __construct($platform_id)
    {
        $where = [
            ['platform_id', '=', $platform_id]
        ];
        $fields = [
            'authorizer_appid',
            'authorizer_access_token',
            'access_token_time',
            'authorizer_refresh_token',
            'user_desc',
            'tag'
        ];
        $AppletGrantModel = new AppletGrant();
        $this->platform_applet_config = $AppletGrantModel->getFindField($where, $fields);
        if (empty($this->platform_applet_config)) {
            echo json_encode(callBack('error', 'param_error', '小程序未授权'), JSON_UNESCAPED_UNICODE);
            die();
        }
        $this->platform_id = $platform_id;
        $this->request = new ThirdRequest();
        $this->getAccessToken(); 
    }
    
    public function release()
    {
        $url = "https://api.weixin.qq.com/wxa/release?access_token=" . $this->platform_applet_config['authorizer_access_token'];
        $result = $this->request->curlPostRaw($url, "{}");
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return callBack('error', 'param_error', '发布小程序失败' . $result['errmsg']);
        }
        return callBack('success', 'success', '发布成功');
    }
    
    public function bindUser($wx_number)
    {
        $url = "https://api.weixin.qq.com/wxa/bind_tester?access_token=" . $this->platform_applet_config['authorizer_access_token'];
        $data = [
            'wechatid' => $wx_number,
        ];
        $result = $this->request->curlPostRaw($url, json_encode($data));
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return callBack('error', 'param_error', '绑定失败' . $result['errmsg'], $result);
        }
        return callBack('success', 'success', '绑定成功');
    }
    
    public function modifyDomain($domain_name)
    {
        $url = "https://api.weixin.qq.com/wxa/modify_domain?access_token=" . $this->platform_applet_config['authorizer_access_token'];
        $data = [
            "action" => "add",
            "requestdomain" => ["https://" . $domain_name],
            "uploaddomain" => ["https://" . $domain_name],
            "downloaddomain" => ["https://" . $domain_name],
        ];
        $result = $this->request->curlPostRaw($url, json_encode($data, JSON_UNESCAPED_SLASHES));
        $result = json_decode($result, true);
        if ($result['errcode'] != 0 && $result['errcode'] != 85017) {
            return callBack('error', 'param_error', '设置服务器域名失败' . $result['errmsg']);
        }
        return callBack('success', 'success', '设置服务器域名成功');
    }
    
    public function auditStatus($audit_id)
    {
        $data = [
            'auditid' => $audit_id,
        ];
        $url = "https://api.weixin.qq.com/wxa/get_auditstatus?access_token=" . $this->platform_applet_config['authorizer_access_token'];
        $result = $this->request->curlPostRaw($url, json_encode($data));
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return callBack('error', 'param_error', '指定版本审核状态查询失败' . $result['errmsg']);
        }
        return callBack('success', 'success', '查询成功', $result);
    }
    
    public function latestAuditStatus()
    {
        $url = "https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=" . $this->platform_applet_config['authorizer_access_token'];
        $result = $this->request->curlGet($url);
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return callBack('error', 'param_error', '查询最新一次提交的审核状态失败' . $result['errmsg']);
        }
        return callBack('success', 'success', '查询成功', $result);
    }
    
    public function undoCodeAudit()
    {
        $url = "https://api.weixin.qq.com/wxa/undocodeaudit?access_token=" . $this->platform_applet_config['authorizer_access_token'];
        $result = $this->request->curlGet($url);
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return callBack('error', 'param_error', '撤销审核失败' . $result['errmsg'], $result);
        } else {
            return callBack('success', 'success', '撤销审核成功');
        }
    }
    
    public function submitAudit($data)
    {
        $url = 'https://api.weixin.qq.com/wxa/submit_audit?access_token=' . $this->platform_applet_config['authorizer_access_token'];
        $result = $this->request->curlPostRaw($url, json_encode($data, JSON_UNESCAPED_UNICODE));
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return callBack('error', 'param_error', '提交审核失败');
        }
        return callBack('success', 'success', '提交审核成功', $result['auditid']);
    }
    
    public function commit($template_id)
    {
        $domain = 'https://' . config('super.domain_name');
        $platform_id = $this->platform_id;
        $authorizer_appid = $this->platform_applet_config['authorizer_appid'];
        $data = [
            'template_id' => $template_id,
            "user_version" => "V" . $template_id,
            'ext_json' => "{
                \"extEnable\":true,
                \"extAppid\": \"$authorizer_appid\",
                \"ext\":{\"platform_id\":\"$platform_id\",\"appid\":\"$authorizer_appid\",\"domain\":\"$domain\"}
                }",
            "user_desc" => $this->platform_applet_config['user_desc'],
        ];
        $url = "https://api.weixin.qq.com/wxa/commit?access_token=" . $this->platform_applet_config['authorizer_access_token'];
        $result = $this->request->curlPostRaw($url, json_encode($data, JSON_UNESCAPED_UNICODE));
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return callBack('error', 'param_error', '上传失败', $result);
        }
        return callBack('success', 'success', '上传成功', $result);
    }
    
    public function getQRCode()
    {
        $url = "https://api.weixin.qq.com/wxa/get_qrcode?access_token=" . $this->platform_applet_config['authorizer_access_token'];
        $result = $this->request->curlGet($url);
        if (($result['errcode'] ?? 0) != 0) {
            return callBack('error', 'param_error', '获取体验版二维码失败', $result);
        }
        return callBack('success', 'success', '获取成功', $result);
    }
    
    public function getCategory()
    {
        $url = "https://api.weixin.qq.com/wxa/get_category?access_token=" . $this->platform_applet_config['authorizer_access_token'];
        $result = $this->request->curlGet($url);
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return callBack('error', 'param_error', '获取授权小程序帐号的可选类目:' . $result['errmsg'], $result);
        } else {
            return callBack('success', 'success', '获取成功', $result['category_list']);
        }
    }
    
    public function getPage()
    {
        $url = 'https://api.weixin.qq.com/wxa/get_page?access_token=' . $this->platform_applet_config['authorizer_access_token'];
        $result = $this->request->curlGet($url);
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return callBack('error', 'param_error', '获取小程序的第三方提交代码的页面配置接口错误' . $result['errmsg'], $result);
        } else {
            return callBack('success', 'success', '获取成功', $result['page_list']);
        }
    }
    
    public function privacySetting($param)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/component/setprivacysetting?access_token=' . $this->platform_applet_config['authorizer_access_token'];
        $param = [
            'owner_setting' => $param['owner_setting'],
            'setting_list' => $param['setting_list']
        ];
        $result = $this->request->curlPostRaw($url, json_encode($param));
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return callBack('error', 'param_error', '设置失败' . $result['errmsg']);
        }
        return callBack('success', 'success', '设置成功');
    }
    
    public function setWebViewDomain($domain_name)
    {
        $url = "https://api.weixin.qq.com/wxa/setwebviewdomain?access_token=" . $this->platform_applet_config['authorizer_access_token'];
        $data = [
            'action' => 'add',
            'webviewdomain' => ['https://' . $domain_name]
        ];
        $data = json_encode($data);
        $result = $this->request->curlPostRaw($url, $data);
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return callBack('error', 'param_error', '小程序业务域名设置失败');
        }
        return callBack('success', 'success', '设置成功');
    }
    
    public function getAccessToken()
    {
        if ($this->platform_applet_config['access_token_time'] < time() || empty($this->platform_applet_config['authorizer_access_token'])) {
            
            
            $WxOpenPlatformClass = new WxOpenPlatform();
            $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' . $WxOpenPlatformClass->open_platform_config['component_access_token'];
            $data = [
                'component_appid' => $WxOpenPlatformClass->open_platform_config['component_appid'],
                'authorizer_appid' => $this->platform_applet_config['authorizer_appid'],
                'authorizer_refresh_token' => $this->platform_applet_config['authorizer_refresh_token']
            ];
            $data = json_encode($data);
            $result = $this->request->curlPostRaw($url, $data);
            file_put_contents('./z2.txt', $result);
            $result = json_decode($result, true);
            if (empty($result['authorizer_access_token'])) {
                echo json_encode(callBack('error', 'param_error', '调用微信接口令牌刷新失败' . $result['errmsg']), JSON_UNESCAPED_UNICODE);
                die();
            }
            $content = [
                'authorizer_access_token' => $result['authorizer_access_token'],
                'authorizer_refresh_token' => $result['authorizer_refresh_token'],
                'access_token_time' => time() + $result['expires_in'] - 200
            ];
            $where = [
                ['platform_id', '=', $this->platform_id]
            ];
            $AppletGrantModel = new AppletGrant();
            $AppletGrantModel->updateInfo($where, $content);
            $this->platform_applet_config['authorizer_access_token'] = $result['authorizer_access_token'];
        }
    }
}