<?php

namespace Application\Service\Extension\Helper;

use Application\Service\Extension\Laminas;

trait CheckLogicMessageFormatterHelper
{
    public static array $formatterCache = [];

    /** @var int|null 用户id */
    protected ?int $formatterCreateUserId = null;

    /** @var int|null 核查类型 */
    protected ?int $formatterCheckType = null;

    /** @var int|null 日期 */
    protected ?int $formatterCreateTime = null;

    /** @var int|null 用户角色 */
    protected ?int $role = null;

    /** @var int|null 质疑id */
    protected ?int $formatterLogicErrorId = null;

    /** @var int|null 平台 */
    protected ?int $formatterPlatform = null;

    protected ?int $formatterItemId = null;

    protected ?int $formatterErrorType = null;
    protected ?int $formatterIsAuditor = null;
    /** @var null 关闭角色 */
    protected $closeRole = null;

    /**
     * 沟通记录格式化
     * @param bool $isReply
     * @return string
     */
    protected function formatMessageLog(bool $isReply): string
    {
        $this->formatIsReply = $isReply;
        return sprintf('%s %s %s', $this->getRoleString(), $isReply ? $this->getReplyUserIdString() : $this->getUserIdString(), $this->getDateTimeString());
    }

    protected function formatMessage($content, $isReply = false): string
    {
        $this->formatIsReply = $isReply;
        return sprintf('%s %s %s %s %s', $this->getIsClosed(), $content, $this->getRoleString(), $isReply ? $this->getReplyUserIdString() : $this->getUserIdString(), $this->getDateTimeString());
    }

    protected function getRoleString(): string
    {
//        if ($this->formatterPlatform === null) {
            if ($this->formatIsReply == true) {
                return $this->getRoleStringSDM();
            }
            return $this->getRoleStringEDC();
//        }

        // EDC
        if ($this->formatterPlatform == 1) {
            return $this->getRoleStringEDC();
        } else { // SDM
            return $this->getRoleStringSDM();
        }
    }

    protected function getIsClosed(): string
    {
        $isClosed = $this->getLogicError()['is_closed'];
        return $isClosed ? '[已关闭]' : '';
    }

    private function getRoleStringEDC(): string
    {
        if ($this->formatterCreateUserId == 0) {
            return '';
        }

        $submitRole = $this->getLogicError()['submit_role'] ?? '';

        if (!$submitRole) {
            if ($this->formatterCreateUserId) {
                if($this->closeRole){ //如果有记录关闭质疑的角色 直接取出
                    return "[" . $this->closeRole . "]";
                }
                return "[" . $this->getEDCRole() . "]";
            }
            return '';
        }
        return sprintf('[%s]', $submitRole);
    }

    private function getRoleStringSDM(): string
    {
        // $isAuditor = $this->getLogicErrorQuery();

        if ($this->formatterIsAuditor) {
            return '[图片审核员]';
        }


        return "[{$this->getRole()}]";
    }

    /**
     * 获取提交回复人的所有权限
     * @return string
     */
    protected function getRole(): string
    {
        if (!isset(self::$formatterCache[__FUNCTION__][$this->formatterCreateUserId])) {
            $container = Laminas::$serviceManager;
            $itemId = $container->itemInfo->getOneFieldVal('fid',[
                'is_del' => 0,
                'id' => $_POST['item_id'] ?? 0,
            ]);
            $userId = $container->signatoryUser->findsignatoryUser($this->formatterCreateUserId);
            $roleId = ArrayHelper::getColumn($container->roleSignatoryRelation->changeUser($itemId, $userId, $_POST['itemsig_id']), 'role_id');
            self::$formatterCache[__FUNCTION__][$this->formatterCreateUserId] = implode('|', ArrayHelper::getColumn(Laminas::$serviceManager->realRole->fetchAll([
                'where' => [
                    'id' => $roleId
                ],
                'columns' => ['role_name']
            ]) ?: [], 'role_name'));
        }

        return self::$formatterCache[__FUNCTION__][$this->formatterCreateUserId];
    }

    protected function getEDCRole()
    {
        $container = Laminas::$serviceManager;
        $user_id = $container->signatoryUser->findsignatoryUser($this->formatterCreateUserId);
        //查询项目
        $itemInfoID = $container->itemInfo->getOneFieldVal('fid',[
            'is_del' => 0,
            'id' => $_POST['item_id'] ?? 0,
        ]);
        if (!$_POST['itemsig_id']) {
            $_POST['itemsig_id'] = $this->getLogicError()['sign_id'];
        }
        //查询角色下的角色管理用户信息
        $roleSignatoryRelationDatas = $container->roleSignatoryRelation->changeUser($itemInfoID, $user_id,  $_POST['itemsig_id'], 0);

        $role_id_arr = array_unique(array_column($roleSignatoryRelationDatas, 'role_id'));
        if (implode(',',$role_id_arr)) {
            $whererealRole['where'] = [
                'is_del' => 0,
                'status' => 0,
                'id' => StringHelper::toArray($role_id_arr),
            ];
            $whererealRole['columns'] = ['id', 'item_id','source_type','role_name','edc_type','code'];
            return implode('|', ArrayHelper::getColumn($container->realRole->fetchAll($whererealRole), 'role_name'));
        }
        return '';
    }

    protected function getUserIdString(): string
    {
        $errorType = $this->getLogicError()['error_type'];

        if ($errorType == 0 && $this->formatIsReply === false) {
            if ($this->formatterCreateUserId) {
                return $this->getUserName();
            }
            return 'System';
        }

        if ($this->formatIsReply === true) {
            return $this->getUserName();
        }

        return $this->formatterCreateUserId == 0 ? 'System' : $this->getUserName();
    }

    public function getReplyUserIdString(): string
    {
        $this->formatterCheckType = 1;

        return $this->getUserIdString();
    }

    protected function getUserName(): string
    {
        if (!isset(self::$formatterCache[__FUNCTION__][$this->formatterCreateUserId])) {
            self::$formatterCache[__FUNCTION__][$this->formatterCreateUserId] = Laminas::$serviceManager->SDMHelper->getUserHelper($this->formatterCreateUserId)->getUserName();
        }

        return self::$formatterCache[__FUNCTION__][$this->formatterCreateUserId];
    }

    protected function getFormatterCheckTypeString(int $checkType): string
    {
        $this->formatterCheckType = $checkType;
        return $this->formatterCheckType == 1 ? '人工质疑' : '系统质疑';
    }

    protected function getDateTimeString(): string
    {
        return $this->getDateTime() === null ? '' : date('Y/m/d H:i:s', $this->formatterCreateTime);
    }

    protected function getDateTime()
    {
        if ($this->formatterCreateTime) {
            return $this->formatterCreateTime;
        }

        if ($this->formatterLogicErrorId) {
            $this->formatterCreateTime = $this->getLogicError()['create_time'];
        }

        return $this->formatterCreateTime;
    }

    protected string $formatMessage = '';
    protected string $formatCreateTime = '';
    protected bool $formatIsReply = false;

    protected function setMessage(string $message = '', $isReply = false)
    {
        $this->formatterCreateTime = null;
        $this->formatMessage = $message;
        $this->formatIsReply = $isReply;
        return $this;
    }

    protected function setCreateTime(string $val = '')
    {
        $this->formatterCreateTime = $val;
        return $this;
    }


    protected function setCreateUserId(string $val = '')
    {
        $this->formatterCreateUserId = $val;
        return $this;
    }

    protected function setErrorId(string $val = '')
    {
        $this->formatterLogicErrorId = $val;
        return $this;
    }

    protected function setErrorIdAlias(string $val = '')
    {
        $this->formatterLogicErrorId = $val;
        return $this;
    }

    protected function setItemId(string $val = '')
    {
        $this->formatterItemId = $val;
        return $this;
    }

    protected function setcloseRole($val = '')
    {
        $this->closeRole = $val;
        return $this;
    }

    protected function format()
    {
        return $this->formatMessage($this->formatMessage, $this->formatIsReply);
    }

    protected function getLogicError()
    {
        if (!isset(self::$formatterCache[__FUNCTION__][$this->formatterLogicErrorId])) {
            self::$formatterCache[__FUNCTION__][$this->formatterLogicErrorId] = Laminas::$serviceManager->itemPatientFormLogicError->fetchOne([
                'where' => ['id' => $this->formatterLogicErrorId]
            ]);
        }

        return self::$formatterCache[__FUNCTION__][$this->formatterLogicErrorId];
    }

    protected function getLogicErrorQuery()
    {
        if (!isset(self::$formatterCache[__FUNCTION__][$this->formatterLogicErrorId])) {
            self::$formatterCache[__FUNCTION__][$this->formatterLogicErrorId] = Laminas::$serviceManager->itemPatientFormLogicErrorQuery->fetchOne([
                'order' => ['id desc'],
                'where' => ['error_id' => $this->formatterLogicErrorId]
            ]);
        }

        return self::$formatterCache[__FUNCTION__][$this->formatterLogicErrorId];
    }
}