<?php
namespace Addons\QyWechat\Services;
use Services\Service;
use Addons\QyWechat\Services\QyWechatApi;

class JsSdk extends Service
{
    private $corp_id;
    private $agent_id;
    private $secret;

    public function __construct($corp_id,$agent_id,$secret){
        $this->corp_id = $corp_id;
		$this->agent_id = $agent_id;
		$this->secret = $secret;
    }
    /**
     * 获取jssdk签名参数
     * @param string $url
     * @param string $type
     * @return array
     */
    public function getSignPackage($url='',$type='') {
		if($type == 'agent'){
			$jsapiTicket = $this->getAgentJsApiTicket();
		}else{
			$jsapiTicket = $this->getJsApiTicket();
		}
        
        if(empty($url)){
			// 注意 URL 一定要动态获取，不能 hardcode.
			$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $url = "$protocol$_SERVER[HTTP_HOST]/$_SERVER[REQUEST_URI]";
        }else{
            $url = html_entity_decode($url);
        }
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $this->corp_id,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }
	
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    //获取企业的jsapi_ticket
    public function getJsApiTicket() {
        $ticket_key="qy_jsapi_ticket_".$this->agent_id;
        $data =  \Cache::get($ticket_key);
        if ($data['expire_time'] < time()) {
            $accessToken = $this->getAccessToken();
            $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            $res = json_decode(curlGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data['expire_time'] = time() + 7000;
                $data['jsapi_ticket'] = $ticket;

                \Cache::set($ticket_key,$data,2);
            }else{
                return $this->error($res->errmsg);
            }
        }
        $ticket = $data['jsapi_ticket'];

        return $ticket;
    }
	//获取应用的jsapi_ticket
    public function getAgentJsApiTicket() {
        $ticket_key="qy_agent_jsapi_ticket_".$this->agent_id;
        $data =  \Cache::get($ticket_key);
        if ($data['expire_time'] < time()) {
            $accessToken = $this->getAccessToken();
            $url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=$accessToken&type=agent_config";
            $res = json_decode(curlGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data['expire_time'] = time() + 7000;
                $data['jsapi_ticket'] = $ticket;

                \Cache::set($ticket_key,$data,2);
            }else{
                return $this->error($res->errmsg);
            }
        }
        $ticket = $data['jsapi_ticket'];

        return $ticket;
    }
	//获取access_token
	public function getAccessToken(){
		$QyWechatApi = QyWechatApi::getInstance();
		$app = $QyWechatApi->get_qy_agent_app($this->corp_id,$this->agent_id,$this->secret);
		$access_token = $app->access_token->getToken()['access_token'];
		return $access_token;
	}
}
