<?php

namespace model;

use \model;

/**
 * Class 宜配COM接口
 * @package model
 */
class ypApiCom
{
	protected $config = null;

	function __construct()
	{
		$this->config = \mvc::$cfg['YPAPICOM'];
	}

	/**
	 * @method 发送
	 * @http  POST
	 * @param  $url_path           string [必填] action/method
	 * @param  $get_arr            array  [可选] ['name'=>'soul',....]
	 * @param  $post_arr           array  [可选] ['name'=>'soul',....]
	 * @author hongzhang
	 * @copyright 2025-10-30
	 * @return array
	 */
	public function Get($url_path, $get_arr = [], $post_arr = [], $run = 0)
	{
		try {
			$run++;
			$url = $this->config['base_url'] . $url_path;
			if (stripos($url_path, 'base/buildToken') === false) {
				$apiToken = $this->getApiToken();
				$get_arr['token'] = $apiToken;
			}
			$url = $url . '?' . http_build_query($get_arr);
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_TIMEOUT, 60000);
			// Token 构建接口采用 Basic Auth
			if (stripos($url_path, 'base/buildToken') !== false) {
				$userName = $this->config['appkey'];
				$password = $this->config['appsecret'];
				// 使用 cURL 的原生 Basic 认证参数，自动添加 Authorization: Basic xxx
				curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
				curl_setopt($ch, CURLOPT_USERPWD, $userName . ':' . $password);
			}
			if (!empty($post_arr)) {
				curl_setopt($ch, CURLOPT_POST, true);
				curl_setopt($ch, CURLOPT_POSTFIELDS, ['data' => json_encode($post_arr)]);
			}
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$ssl = substr($url, 0, 8) == "https://" ? true : false;
			if ($ssl) {
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
			}
			$html = curl_exec($ch);
			curl_close($ch);
			//处理错误提示
			$return = json_decode($html, true);
			if (is_array($return) && (!isset($return['status']) || $return['status'])) return $return;

			if ($run < 5) return $this->Get($url_path, $get_arr, $post_arr, $run);
			errorLog(['url' => $url, 'post' => $post_arr, 'html' => $html], 'ypapi');
			exitJson('ypapi:' . $html);
		} catch (Exception $e) {
			if ($run < 5) return $this->Get($url_path, $get_arr, $post_arr, $run);
			errorLog(['url' => $url, 'post' => $post_arr, 'html' => $e->getMessage()], 'ypapi');
			exitJson('ypapi:' . $e->getMessage());
		}
	}

	/**
	 * @method 获取客服token 含缓存
	 * @author hongzhang
	 * @copyright 2025-10-30
	 */
	public function getApiToken()
	{
		$now = time();
		$ckv = new \model\ckv();
		$token = '';

		$tokenInfo = json_decode($ckv->getKV('yp_api_com_token'), true);

		// 如果解析失败，重新初始化
		if (empty($tokenInfo)) {
			$tokenInfo = ['token' => '', 'expireTime' => 0];
		}
		$expireTime = $tokenInfo['expireTime'];
		if ($now > $expireTime) {
			// 过期重新获取
			$tokenRes = $this->Get('base/buildToken');
			if ($tokenRes['status']) {
				$successTime = time();
				$token = $tokenRes['data']['token'];
				$tokenInfo = ['token' => $token, 'expireTime' => $successTime + 7200]; // 2小时后过期 (2 * 60 * 60 = 7200秒)
				$ckv->setKV('yp_api_com_token', json_encode($tokenInfo));
			} else {
				exitJson('error code:' . $tokenRes['code']);
			}
		} else {
			$token = $tokenInfo['token'];
		}
		return $token;
	}
}
