<?php 
namespace model;
use \model;

class freyApi extends \model
{   
    protected $tokenName = 'frey.access_token.json';

    /**
     * @method 获取token
     * @author zhengweihua 
     * @copyright 2023-12-12
     */
    public function getToken()
    {   
        if($this->hasValidToken())
        {
            return json_decode(file_get_contents($this->getTokenFile()), true)['token'];
           
        }
        $urlPath = '/login/index';
        $data =  [
            'AccessKeyId'=>\mvc::$cfg['freyApi']['AccessKeyId'],
            'AccessKeySecret'=>\mvc::$cfg['freyApi']['AccessKeySecret']
        ];
        $res = $this->httpCurl($urlPath, 'POST', $data);
        $token = $res['data'];
        $this->setToken($token['token'], $token['exp_time']);

        return $token['token'];
    }

    /**
     * @method token文件
     * @author zhengweihua 
     * @copyright 2023-12-19
     */
    protected function getTokenFile()
    {
        return \mvc::$cfg['siteDir'] . '/' . $this->tokenName;
    }

    /**
     * @param  string $token
     * @param  string $expiresAt
     * @method 设置token
     * @author zhengweihua 
     * @copyright 2023-12-19
     */
    public function setToken($token,$expiresAt)
    {
        $payload = [
            'token' => $token,
            'exp_time' => $expiresAt,
        ];

        file_put_contents($this->getTokenFile(), json_encode($payload));
    }
    /**
     * @method 判断token是否有效
     * @author zhengweihua 
     * @copyright 2023-12-19
     * @return bool
     */
    protected function hasValidToken()
    {
        if (! file_exists($this->getTokenFile())) {
            return false;
        }

        $token = json_decode(file_get_contents($this->getTokenFile()));

        if ($token->exp_time<time()) {
            return false;
        }

        return true;
    }

    /**
     * @method curl请求
     * @author zhengweihua 
     * @copyright 2023-12-12
     */
    public function httpCurl($urlPath = '', $method = 'GET', $data = [], $header = [])
    {
		return [];
        try {
            $url = \mvc::$cfg['freyApi']['url'] . $urlPath;
            $ch = curl_init();
			if(empty($data['token']) && stripos($urlPath, 'login') === false)
				$header[] = 'token:'.$this->getToken();

            ## 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, 'image/') !== 0){
              
                $output_json =  json_decode($output, true);
                return $output_json; 
               
            }else{
                $mimeMap = [
                    'image/jpg' => 'jpg',
                    'image/jpeg' => 'jpg',
                    'image/png' => 'png',
                    'image/gif' => 'gif',
                    'image/bmp' => 'bmp',
                    'image/webp' => 'webp'
                ];
                $mintype = explode(';',$contentType);
                return ['data'=>['data'=>$output,'ext'=>$mimeMap[$mintype[0]]]];
            }
           
        } catch (\Exception $e) {
            return  $e->getMessage();
        }
    }
}
