<?php

namespace Application\Service\Extension\Helper\components;

use Application\Common\DictionaryVarNameEnum;
use Application\Form\item\patient\PatientFormModel;
use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\base\BaseHelper;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Laminas\Db\Sql\Predicate\Operator;

class AEHelper extends BaseHelper
{
    protected ?int $signId = null;  // 中心ID

    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();
    }

    /**
     * 删除受试者新增AE
     * @param null $AEContentId
     */
    public function deleteCMNewAE($AEContentId = null)
    {
        $checkedData = Laminas::$serviceManager->itemCsaeChecked->fetchOne([
            'where' => ['content_id' => $AEContentId, 'is_del' => 0]
        ]);

        if ($checkedData) {
            throw new InvalidArgumentException('当前新增AE已被调用, 无法删除。');
        }

        Laminas::$serviceManager->itemCsaeRelation->update(['is_del' => 1], ['content_id' => $AEContentId]);
        Laminas::$serviceManager->itemPatientAeContent->update(['is_del' => 1], ['id' => $AEContentId]);
    }

    /**
     * CM断开受试者新增AE
     * @param int $CMContentId
     * @param null $AEContentId
     */
    public function discardCMNewAE(int $CMContentId, $AEContentId = null)
    {
        $branch = ArrayHelper::getColumn(Laminas::$serviceManager->itemCsaeRelation->fetchAll([
            'columns' => ['branch'],
            'where' => array_filter([
                'cm_content_id' => $CMContentId,
                'is_del' => 0,
                'content_id' => $AEContentId
            ])
        ]), 'branch');
        if ($branch) {
            Laminas::$serviceManager->itemCsaeRelation->update(['cm_content_id' => 1], ['branch' => $branch]);
        }
    }

    /**
     * AE断开受试者新增AE
     * @param null $AEContentId
     */
    public function discardAENewAE(int $CSAEId, $AEContentId = null): int
    {
        $branch = ArrayHelper::getColumn(Laminas::$serviceManager->itemCsaeRelation->fetchAll([
            'columns' => ['branch'],
            'where' => array_filter([
                'is_del' => 0,
                'content_id' => $AEContentId
            ])
        ]), 'branch');

        // 把已有ae的挂靠的新增指标ae处理成受试者ae
        if ($branch) {
            Laminas::$serviceManager->itemCsaeRelation->update(['csae_id' => 0, 'new_ae_list_id' => 0], ['branch' => $branch, 'csae_id' => $CSAEId]);
            Laminas::$serviceManager->itemPatientAeContent->update(['ae_type' => 0, 'new_ae_list' => 0], ['branch' => $branch, 'csae_id' => $CSAEId]);
            Laminas::$serviceManager->itemCsaeChecked->update(['new_id' => 0], ['content_id' => $AEContentId]);
        }

        return count(Laminas::$serviceManager->itemCsaeRelation->fetchAll([
            'columns' => ['id'],
            'where' => [
                new Operator('csae_id', Operator::OP_EQ, $CSAEId),
                'is_del' => 0
            ]
        ]));
    }

    /**
     * CM判断删除已有AE关联状态
     * @param int $AEContentId
     * @param int $cmContentId
     * @return bool 是否还有剩余的数据
     */
    public function discardCMListIsAlreadyAE(int $AEContentId, int $cmContentId): bool
    {
        Laminas::$serviceManager->itemCsaeChecked->update(['is_del' => 1], ['content_id' => $AEContentId, 'cm_content_id' => $cmContentId]);
        return (bool)Laminas::$serviceManager->itemCsaeChecked->fetchAll([
            'where' => ['cm_content_id' => $cmContentId, 'is_del' => 0]
        ]);
    }

    /**
     * AE判断删除已有AE关联状态
     * @param int $CSAEId
     * @param int|null $AEContentId 空值就是删除所有的
     * @return int
     */
    public function discardAEHasAE(int $CSAEId, ?int $AEContentId = null): int
    {

        if (!$AEContentId) {
            Laminas::$serviceManager->itemCsaeChecked->update(['is_del' => 1], ['csae_id' => $CSAEId]);
        } else {
            $content = Laminas::$serviceManager->itemPatientAeContent->fetchAll([
                'where' => array_filter([
                    'is_del' => 0,
                    'id' => $AEContentId
                ])
            ]);
//var_dump($content);die;
            Laminas::$serviceManager->itemCsaeChecked->update(['is_del' => 1], ['content_id' => $AEContentId, 'csae_id' => $content['csae_id'], 'branch' => $content['branch']]);
        }

        $count = Laminas::$serviceManager->itemCsaeChecked->fetchAll([
            'where' => [
                'csae_id' => $content['csae_id'],
                'is_del' => 0
            ]
        ]) ?: [];

        return count($count);
    }

    /**
     * 删除已有AE关联状态
     */
    public function deleteAllCMListIsAlreadyAE(int $cmContentId)
    {
        Laminas::$serviceManager->itemCsaeChecked->update(['is_del' => 1], ['cm_content_id' => $cmContentId]);
    }

    public function setCMAEEstimate(int $CMContentId, int $status = 0)
    {
        Laminas::$serviceManager->patientFormContentCm->update(['status' => 0, 'cmindc_status' => ''], ['content_id' => $CMContentId]);
    }

    public function getCMINDCId(int $formId)
    {
        $versionData = ArrayHelper::index(SDMHelper::app()->form->getVersionData($formId), 'var_name');
        if (!isset($versionData[DictionaryVarNameEnum::COLLECT_MEDICAL_TAKE_CMINDC]['id'])) {
            return false;
        }

        return $versionData[DictionaryVarNameEnum::COLLECT_MEDICAL_TAKE_CMINDC]['id'];
    }

    public function flushCMINDCContent(int $contentId)
    {
        $query = Laminas::$serviceManager->patientFormContent->fetchOne([
            'where' => ['id' => $contentId]
        ]);
        if (!$query) {
            throw new InvalidArgumentException('未找到该AE数据');
        }

        $originData = StringHelper::jsonDecode($query['data']);
        $originData[$this->getCMINDCId($query['form_id'])] = '';
        $model = new PatientFormModel();
        $model->setPostValues($originData);
        $model->editForm($originData);
    }

    /**
     * 当前AE类型能否切换
     * @param int $CSAEId 指标id
     * @param int $currentType
     * @return bool
     */
    public function isAEEstimateTypeUpdate(int $CSAEId, int $currentType): bool
    {
        if ($CSAEId == 0) {
            return false;
        }

        $query = Laminas::$serviceManager->itemCsae->fetchOne([
            'where' => [
                'id' => $CSAEId
            ]
        ]);

        $isUpdate = $query && $query['ae_type'] != $currentType;

        if (!$isUpdate) {
            return false;
        }

        if ($query && ($query['ae_type'] == 6 && $currentType == 5)) {
            throw new \Application\Service\Exceptions\InvalidArgumentException('新增ae不能修改成已有ae');
        }

        $isChecked = Laminas::$serviceManager->itemCsaeChecked->fetchOne([
            'where' => ['new_id' => $CSAEId, 'is_del' => 0]
        ]);

        if ($isChecked) {
            throw new InvalidArgumentException('当前指标已被调用啦, 无法切换');
        }

        return true;
    }
}