<?php
// +------------------------------------------------+
// |http://www.cjango.com                           |
// +------------------------------------------------+
// | 修复BUG不是一朝一夕的事情，等我喝醉了再说吧！  |
// +------------------------------------------------+
// | Author: 小陈叔叔 <Jason.Chen>                  |
// +------------------------------------------------+
namespace src\Dingtalk;

use src\Dingtalk;

/**
 *
 */
class AppClient extends Dingtalk
{

    /**
     * 初始化APP端钉钉配置
     * @param  string $agentId   agentId
     * @param  array  $jsApiList 需要使用的jsapi列表
     * @return array
     */
    public static function init($agentId, $jsApiList = [])
    {
        $return = '<script src="https://g.alicdn.com/dingding/open-develop/0.7.0/dingtalk.js" type="text/javascript" charset="utf-8"></script>';
        $return .= '<script type="text/javascript" charset="utf-8">';
        $return .= 'dd.config(';
        $return .= self::ddConfig($agentId, $jsApiList);
        $return .= ');';
        $return .= '</script>' . "\r\n";
        return [
            'init'   => $return,
            'corpid' => parent::$config['corpid'],
        ];
    }

    /**
     * JS-API权限验证参数生成
     * @return array
     */
    private static function ddConfig($agentId, $jsApiList)
    {
        $nonceStr  = uniqid();
        $timestamp = time();
        $config    = [
            'agentId'   => $agentId,
            'corpId'    => parent::$config['corpid'],
            'timeStamp' => $timestamp,
            'nonceStr'  => $nonceStr,
        ];
        $config['signature'] = self::sign($nonceStr, $timestamp);
        $config['jsApiList'] = $jsApiList;
        return json_encode($config);
    }

    /**
     * 钉钉签名算法
     * @param  string $noncestr
     * @param  string $timestamp
     * @return string
     */
    private static function sign($noncestr, $timestamp)
    {
        $jsapi_ticket = parent::$config['jsapi_ticket'];
        if (empty($jsapi_ticket)) {
            $jsapi_ticket = Token::jsapi();
        }

        $signArr = [
            'jsapi_ticket' => $jsapi_ticket,
            'noncestr'     => $noncestr,
            'timestamp'    => $timestamp,
            'url'          => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], // 获取当前页面地址 有待优化
        ];
        ksort($signArr);
        $signStr = urldecode(http_build_query($signArr));
        return sha1($signStr);
    }
}
