<?php
namespace model\user;

use model\user;

class ddtalk extends \model
{
    public $base_uri = 'https://api.dingtalk.com';

    public function dingtalkLogin($authCode)
    {
        $userid = $this->getUserId($authCode);
        if($userid){
            $row = $this->db->get('adm_user','*',['au_dingtalk_uid'=>$userid]);
            if($row){
                $user = new user();
                $user->logined($row);
                $user->toLog('系统','登录系统');
                $_SESSION['verificode'] = '*&^$^^@';
                return '';
            }else{
                return lg('用户不存在');
            }
        }
        return lg('用户不存在');
    }

    public function getUserId($authCode)
    {
        $arr = $this->getUserAccessToken($authCode);
        $token = $arr['accessToken'];
        //获取unionid
        $info = $this->getUserInfo($token);
        $unionId = $info['unionId'];
        //获取userid
        $userid = $this->getByUnionid($unionId);
        return $userid;
    }
    public function getUserAccessToken($authCode)
    {   
        if(!$authCode) return lg('授权码为空');
        $header = [
            'Content-Type: application/json',
        ];
        $res = $this->httpCurl('/v1.0/oauth2/userAccessToken', 'POST', $header, json_encode([
            'clientId' => \mvc::$cfg['dingtalk']['AppKey'],
            'clientSecret' => \mvc::$cfg['dingtalk']['AppSecret'],
            'code' => $authCode,
            'grantType' => 'authorization_code',
        ]));
        return $res;
    }

    public function getOrgAccessToken()
    {
        //https://oapi.dingtalk.com/gettoken
        if (isset($_SESSION['dingtalk']['access_token']) && isset($_SESSION['dingtalk']['token_expires_at'])) {
            // 如果当前时间小于过期时间，则直接返回存储的 access_token
            if (time() < $_SESSION['dingtalk']['token_expires_at']) {
                return $_SESSION['dingtalk']['access_token'];
            }
        }

        $urlPath = sprintf('/gettoken');
        $this->base_uri = 'https://oapi.dingtalk.com';
        $res = $this->httpCurl($urlPath, 'GET', [], [
            'appkey' => \mvc::$cfg['dingtalk']['AppKey'],
            'appsecret'=>\mvc::$cfg['dingtalk']['AppSecret'],
        ]);

        $accessToken = $res['access_token'];

        $expiresIn = $res['expires_in'] ?? 7200;
        $expiresAt = time() + $expiresIn - 300; 

        // 将 access_token 和过期时间存储到 SESSION 中
        $_SESSION['dingtalk']['access_token'] = $accessToken;
        $_SESSION['dingtalk']['token_expires_at'] = $expiresAt;
        return $accessToken;
    }

    public function getUserInfo($accessToken)
    {
        if(!$accessToken) return lg('token为空');
        $header = [
            'Content-Type: application/json',
            'x-acs-dingtalk-access-token: ' . $accessToken,
        ];
        $res = $this->httpCurl('/v1.0/contact/users/me', 'GET', $header, []);
        return $res;

    }

    public function getByUnionid($unionid)
    {   
        $urlPath = sprintf('/topapi/user/getbyunionid?access_token=%s', $this->getOrgAccessToken());
        $this->base_uri = 'https://oapi.dingtalk.com';
        $res = $this->httpCurl($urlPath, 'POST', [], [
            'unionid' => $unionid,
        ]);
        if($res['errmsg']=='ok'){
            return $res['result']['userid'];
        }
        return exitJson(0, $res['errmsg']);
    }


    /**
     * @method curl请求
     * @author zhengweihua 
     * @copyright 2023-12-12
     */
    public function httpCurl($urlPath = '', $method = 'GET', $header = [], $data = [])
    {
        try {
            $url = $this->base_uri . $urlPath;
            $ch = curl_init();

            ## POST数据
            if ($method == 'POST') {
                curl_setopt($ch, CURLOPT_POST, 1);

                if (!empty($data)) {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                }
            }

            ## GET带参数请求
            if ($method == 'GET') {
                if (!empty($data)) {
                    $url .= '?' . http_build_query($data);
                }
            }
            
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

            if ($error = curl_error($ch)) {
                throw new \Exception($error, 1);
            }
            $output = trim(curl_exec($ch));
            $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
            curl_close($ch);
            if(strpos($contentType, 'application/json') === 0){
                
                $output_json =  json_decode($output, true);
                return $output_json; 
               
            }else{
                
                return $output; 
            }
           
        } catch (\Exception $e) {
            return  $e->getMessage();
        }
    }

}