<?php

namespace Application\Service\Extension\Helper\components;

use Application\Service\Extension\Helper\base\BaseHelper;
use Application\Service\Extension\Laminas;
use Exception;

class SignHelper extends BaseHelper
{
    protected ?int $signId = null;
    protected ?int $signInfoId = null;

    protected function setCache($value, string $helperKey = self::HELPER_KEY_BASE)
    {
        self::$cache[$this->getCacheKey()][$this->signId][$helperKey] = $value;
    }

    protected function setFunctionCache(string $functionName, string $key, $value)
    {
        self::$cache[$this->getCacheKey()][$functionName][$key] = $value;
    }

    protected function getFunctionCache(string $functionName, string $key = 'default')
    {
        return self::$cache[$this->getCacheKey()][$functionName][$key] ?? [];
    }

    protected function getCacheKey(): string
    {
        return self::class;
    }

    protected function getCache(string $helperKey = self::HELPER_KEY_BASE)
    {
        return self::$cache[$this->getCacheKey()][$this->signId][$helperKey] ?? [];
    }

    protected function getSignInfoCache(string $helperKey = self::HELPER_KEY_BASE)
    {
        return self::$cache[$this->getCacheKey()][$this->signInfoId][$helperKey] ?? [];
    }

    private function _getCacheData()
    {
        if (!$this->getCache()) {
            $this->setCache(Laminas::$serviceManager->itemSignatory->fetchOne(['where' => ['id' => $this->signId]]));
        }

        return $this->getCache();
    }

    /**
     * 获取中心编号
     * @return mixed|null
     * @throws Exception
     */
    public function getSignNumber(int $signId = null)
    {
        if ($signId) {
            $this->signId = $signId;
        }
        return $this->getProperty($this->_getCacheData(), 'number');
    }

    /**
     * 获取中心编号
     * @return mixed|null
     * @throws Exception
     */
    public function getSignName(int $signId = null)
    {
        if ($signId) {
            $this->signId = $signId;
        }

        $signId = $this->getProperty($this->_getCacheData(), 'signatory_id');

//        $this->signInfoId = $signId;
        return $this->_getSignatoryInfoCache($signId)['info_name'];
    }

    public function _getSignatoryInfoCache(int $infoId)
    {
        if (!$this->getFunctionCache(__FUNCTION__, $infoId)) {
            $this->setFunctionCache(__FUNCTION__, $infoId , Laminas::$serviceManager->signatoryInfo->fetchOne(['where' => ['id' => $infoId]]));
        }

        return $this->getFunctionCache(__FUNCTION__, $infoId);
    }
}