<?php

namespace app\common\wework\api;

use think\Cache;

class Api {
    /**
     * @var object 对象实例
     */
    protected static $instance;
    protected static $baseUrl = 'https://qyapi.weixin.qq.com/cgi-bin/';

    protected static $getAccessToken = 'gettoken';
    protected static $contactInfo = 'externalcontact/get';

    protected $corpId = '';
    protected $corpSecret = '';

    protected $accessToken = '';

    function __construct($corpId, $corpSecret)
    {
        $this->corpId = $corpId;
        $this->corpSecret = $corpSecret;
    }

    /**
     * 获取客户详情
     * @param $externalUserId
     * @return mixed
     */
    function contactInfo($externalUserId) {
        return $this->get(self::$contactInfo, [
            'access_token' => $this->getAccessToken(),
            'external_userid' => $externalUserId
        ]);
    }

    /**
     * 获取accessToken
     * @return false|mixed
     */
    protected function getAccessToken() {
        if ($this->accessToken == '') {
            $this->accessToken = Cache::get('accessToken:' . $this->corpId);
            if ($this->accessToken == '') {
                $result = $this->get(self::$getAccessToken, [
                    'corpid' => $this->corpId,
                    'corpsecret' => $this->corpSecret
                ]);
                if (isset($result['access_token']) && $result['access_token']) {
                    Cache::set('accessToken:' . $this->corpId, $result['access_token'],$result['expires_in']-60);
                    $this->accessToken = $result['access_token'];
                }
            }
        }
        return $this->accessToken;
    }



    protected function get($action, $data) {
        return json_decode(Curl::get(self::$baseUrl . $action,null,$data), true);
    }
}