<?php
/**
 *
 * @author：llbjj
 * @DateTime：2024/7/9 10:07
 * @Description：
 *
 */

namespace Application\Service\OA;

use Application\Service\BaseService;
use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\OA\Config\ApiConfig;
use Application\Service\Redis\RedisExtend;
use Interop\Container\ContainerInterface;
use Laminas\Cache\Exception\ExceptionInterface;
use Laminas\Stdlib\ArrayUtils;

class OaClient extends BaseService
{
    const ACCESS_TOKEN_REDIS_KEY = 'ACCESS_TOKEN';
    private string $domain;
    private string $appId;
    private string $secretKey;
    private string $redisNamespace;
    private string $redisTtl;
    private string $signName;
    private bool $isHttps;
    private RedisExtend $redis;
    public function __construct(ContainerInterface $container)
    {
        parent::__construct($container);
        $this->_init();

        $this->redis = $this->LocalService()->redisExtend->setDatabase(6)->setNamespace($this->redisNamespace)->setTtl($this->redisTtl);
    }

    /**
     * Notes: 文档信息列表
     * User: llbjj
     * DateTime: 2024/7/12 15:40
     *
     * @param array $data
     * @return mixed
     */
    public function documentInfo(array $data = []) {
        return $this->httpSv(ApiConfig::DOCUMENT_INFO_API, $data);
    }

    /**
     * Notes: 保存文档
     * User: llbjj
     * DateTime: 2024/7/12 15:40
     *
     * @param array $data
     * @return mixed
     */
    public function documentSave(array $data) {
        return $this->httpSv(ApiConfig::DOCUMENT_INFO_SAVE_API, $data);
    }

    /**
     * Notes: 保存文档附件
     * User: llbjj
     * DateTime: 2024/7/12 15:40
     *
     * @param array $data
     * @return mixed
     */
    public function documentannexSave(array $data) {
        return $this->httpSv(ApiConfig::DOCUMENT_ANNEX_SAVE_API, $data);
    }

    /**
     * Notes: 文档分类列表
     * User: llbjj
     * DateTime: 2024/7/12 15:40
     *
     * @param array $data
     * @return mixed
     */
    public function documentCategoryList(array $data = []) {
        return $this->httpSv(ApiConfig::DOCUMENT_CATREGORY_LIST_API, $data);
    }

    /**
     * Notes: 中心列表
     * User: llbjj
     * DateTime: 2024/7/12 15:41
     *
     * @param array $data
     * @return mixed
     */
    public function signatoryInfoList(array $data = []) {
        return $this->httpSv(ApiConfig::SIGNATORY_INFO_LIST_API, $data);
    }

    /**
     * Notes: 项目列表
     * User: llbjj
     * DateTime: 2024/7/12 15:42
     *
     * @param array $data
     * @return mixed
     */
    public function itemInfoList(array $data = []) {
        return $this->httpSv(ApiConfig::ITEM_INFO_LIST_API, $data);
    }

    /**
     * Notes: 项目中心信息
     * User: llbjj
     * DateTime: 2024/7/12 15:41
     *
     * @param array $data
     * @return mixed
     */
    public function itemsignatoryInfoList(array $data = []) {
        return $this->httpSv(ApiConfig::ITEM_SIGNATORY_INFO_LIST_API, $data);
    }

    /**
     * Notes: 项目中心对应关系数组
     * User: llbjj
     * DateTime: 2024/7/12 15:41
     *
     * @param array $data
     * @return mixed
     */
    public function itemsignatoryList(array $data = []) {
        return $this->httpSv(ApiConfig::ITEM_SIGNATORY_INFO_API, $data);
    }


    /**
     * Notes:处理之前未同步过去的附件信息
     * @param
     * @return
     * @author haojinhua
     * @date 2025-01-13
     */
    public function documentannexInfo(array $data = []) {
        return $this->httpSv(ApiConfig::DOCUMENT_ANNEX_INFO_API, $data);
    }


    private function httpSv(string $api, array $params = [], array $headers = [], bool $isToken = true) {
        if($isToken) $cookies = ['PHPSESSID' => $this->accessToken()];
        return $this->LocalService()->httpSv
            ->setCookies($cookies ?? [])
            ->setHeader($headers)
            ->setStatusField('status', 'msg')
            ->setSignName($this->signName)
            ->post(($this->isHttps ? 'https' : 'http') . "://{$this->domain}{$api}", $params);
    }

    /**
     * @throws ExceptionInterface
     */
    private function accessToken() {
        $accessToken = '';
        $redisKey = self::ACCESS_TOKEN_REDIS_KEY . ':' . $this->LocalService()->identity->getMobile();
        if(!$this->redis->hasItem($redisKey)) {
            $authResult = $this->httpSv(ApiConfig::AUTH_API, [
                'mobile' => $this->LocalService()->identity->getMobile()
            ], [
                'appid' => $this->appId,
                'secretKey' => $this->secretKey,
            ], false);

            $accessToken = $authResult['access_token'];

            if(!$accessToken) throw new InvalidArgumentException('OASys授权登录失败！');
        }

        if(empty($accessToken)) $accessToken = $this->redis->getItem($redisKey);
        $this->redis->setItem($redisKey, $accessToken);
        return $accessToken;
    }

    private function _init() {
        $config = $this->LocalService()->config['oa'];

        if(empty($config)) throw new InvalidArgumentException('请配置OA信息！');

        foreach ($config as $key => $val) {
            $this->{$key} = $val;
        }
    }
}