<?php

namespace Application\Form;

use Application\Common\EventEnum;
use Application\Form\item\patient\PatientFormModel;
use Application\Form\project\AeForm;
use Application\Service\DB\Db;
use Application\Service\Extension\Helper\DataHelper;
use Application\Service\Extension\Helper\LogHelper;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Laminas\Json\Json;
use Laminas\Stdlib\ArrayUtils;

/**
 * @property-read int $cmContentId
 * @property-read string $note
 */
class CmAEModel extends PatientFormModel
{
    /**
     * 受试者新增AE
     * @return void
     * @throws \Exception
     */
    public function createNewPatientAE()
    {
        $aeFormId = SDMHelper::app()->form->getAeForm($this->validator->attributes['item_id'])['id'];
        $this->setPostValues(ArrayUtils::merge(Json::decode($this->validator->attributes['ae'], Json::TYPE_ARRAY), [
            'form_id' => $aeFormId,
            'cm_content_id' => $this->validator->attributes['id'] // 用药ID
        ]));

        Db::beginTransaction();

        // 清理表单的attach
        LogHelper::$attach = [];

        $this->event = EventEnum::EVENT_CM_AE_FORM_CONTENT_CREATE;



        $this->initLoggerData();

        $AeModel = new \Application\Form\project\AeForm();
        
        $branchHashString = StringHelper::generateHashValue();
        $contentId = Laminas::$serviceManager->itemPatientAeContent->save([
            'patient_id' => $this->patientId,
            'item_id' => $this->itemId,
            'itemsig_id' => $this->itemsigId,
            'data' => json_encode($this->postData),
            'is_del' => 0,
            'csae_id' => 0,
            'new_ae_list' => 0,
            'ae_type' => 6, // 受试者新增AE
            'branch' => $branchHashString,
            'form_id' => $aeFormId,
            'is_skip' => 0,
            'is_complete' => $AeModel->getIsComplete($this->validator->attributes,$aeFormId)
        ]);

        Laminas::$serviceManager->itemCsaeRelation->insert([
            'csae_id' => 0,
            'new_ae_list_id' => 0,
            'content_id' => $contentId,
            'patient_id' => $this->patientId,
            'branch' => $branchHashString,
            'cm_content_id' => $this->cmContentId
        ]);

        $this->h()->log->setTraceAttach('在CM判断中新增了受试者AE表单数据。');

        $this->logger->setContentId($contentId)->flush([
            'item_id' => $this->itemId,
            'patient_id' => $this->patientId,
            'form_id' => $aeFormId,
            'checktime_id' => $this->checktimeId ?: 0,
        ]);

        Db::commit();

        //异步处理访视进度情况信息
        Laminas::$serviceManager->swTaskClient->send([
            'svName' => 'projectPatientworkbatch',
            'methodName' => 'multipleUpdateData',
            'params' => [
                'item_id' => $this->itemId,
                'itemsig_id' => $this->itemsigId,
                'patient_id' => $this->patientId,
                'checktime_id' => -1,
                'form_id' => $aeFormId,
                'operate_type'=>10,
                'content_id'=>!empty($contentId) ? [$contentId] : [],
                'user_id' => Laminas::$serviceManager->identity->getId()
            ]
        ]);
    }

    public function createAlreadyHaveAE()
    {
        Db::beginTransaction();

        // 清理表单的attach
        LogHelper::$attach = [];

        $relationData = Laminas::$serviceManager->itemCsaeRelation->fetchOne([
            'where' => ['content_id' => $this->validator->attributes['checked_content_id']]
        ]);

        Laminas::$serviceManager->itemCsaeChecked->update([
            'is_del' => 1,
        ], ['cm_content_id' => $this->cmContentId, 'content_id' => StringHelper::jsonDecode($this->validator->attributes['ae'])['id']]);

        Laminas::$serviceManager->itemCsaeChecked->insert([
            'csae_id' => 0,
            'new_id' => 0,
            'content_id' => StringHelper::jsonDecode($this->validator->attributes['ae'])['id'],
            'branch' => $relationData['branch'],
            'cm_content_id' => $this->cmContentId
        ]);

        Db::commit();
    }

    public function updateNote()
    {
        Laminas::$serviceManager->patientFormContentCm->update(['note' => $this->note], ['content_id' => $this->cmContentId]);
    }

    public function getNewAEList()
    {
        $model = new AeForm($this->validator);
        $data = [];

        return $model->renderNewAeTable();
    }

    public function getAlreadyHaveAE()
    {
        $model = new AeForm($this->validator);
        $data = [];

        return $model->renderNewAeTable();
    }

    public function editAEForm()
    {
        $aeFormId = SDMHelper::app()->form->getAeForm($this->validator->attributes['item_id'])['id'];
        $this->setPostValues(ArrayUtils::merge($this->validator->attributes, [
            'form_id' => $aeFormId
        ]));

        $this->event = EventEnum::EVENT_CM_AE_FORM_CONTENT_EDIT;

        $this->initLoggerData();

        Laminas::$serviceManager->itemPatientAeContent->update([
            'data' => json_encode(DataHelper::handleFormData($this->validator->attributes, $aeFormId)),
        ], ['id' => $this->id]);

        $this->logger->setContentId($this->id)->flush([
            'item_id' => $this->itemId,
            'patient_id' => $this->patientId,
            'form_id' => $aeFormId,
            'checktime_id' => $this->checktimeId ?: 0,
        ]);

        //异步处理访视进度情况信息
        Laminas::$serviceManager->swTaskClient->send([
            'svName' => 'projectPatientworkbatch',
            'methodName' => 'multipleUpdateData',
            'params' => [
                'item_id' => $this->itemId,
                'itemsig_id' => $this->itemsigId,
                'patient_id' => $this->patientId,
                'checktime_id' => -1,
                'form_id' => $aeFormId,
                'operate_type'=>11,
                'content_id'=>!empty($this->id) ? [$this->id] : [],
                'user_id' => Laminas::$serviceManager->identity->getId()
            ]
        ]);

    }
}