<?php

namespace Application\Service\Extension\Helper\components;

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

class LogicMessageFormatter extends BaseHelper
{
    protected ?int $errorId = null;
    protected string $message = '';
    protected ?int $signId = null;
    protected ?int $itemId = null;
    protected ?int $createUserId = null;
    protected ?int $createTime = null;

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

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

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

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

        return $this->getCache();
    }

    public function setMessage(string $message): LogicMessageFormatter
    {
        $this->message = $message;
        return $this;
    }

    public function setErrorId(int $errorId): LogicMessageFormatter
    {
        $this->errorId = $errorId;
        return $this;
    }

    public function format(): string
    {
        if ($this->errorId) {
            $query = Laminas::$serviceManager->itemPatientFormLogicError->fetchOne([
                'where' => ['id' => $this->errorId]
            ]);

            $this->message = $query['expression_note'];
            $this->itemId = $query['item_id'];
            $this->signId = $query['sign_id'];
            $this->createUserId = $query['create_user_id'];
            $this->createTime = $query['create_time'];
        }

        $roleName = SDMHelper::app()->user->getEDCRoleNameString($this->createUserId, $this->itemId, $this->signId);
        $name = SDMHelper::app()->user->getRealName($this->createUserId);
        if(empty($this->createUserId)){
            $name = 'System';
            $roleName = '系统';
        }
        return $this->message . " [$roleName] $name " . date('Y-m-d H:i:s', $this->createTime);
    }
}