<?php

namespace Application\Service\Extension\Middleware\components;

use Application\Form\item\patient\PatientFormModel;
use Application\Service\DB\Dictionary\Form;
use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Middleware\BaseMiddlewareComponent;

/**
 * @property PatientFormModel $owner
 */
class ValidIsRepeatCreate extends BaseMiddlewareComponent
{

    function execute()
    {
        if (in_array($this->owner->scenario, [$this->owner::SCENARIO_EXCEL_IMPORT, $this->owner::SCENARIO_OUT_FORM, $this->owner::SCENARIO_USING_SCORE])) {
            return;
        }

        if (SDMHelper::app()->setAttributes(['form_id' => $this->owner->formId])->form->getType() == Form::FORM_TYPE_MULTI) {
            return;
        }

        // 因为是共享的, 所以可能有问题, 先跳过去
        if (SDMHelper::app()->setAttributes(['form_id' => $this->owner->formId])->form->getGroupId() == FormGroup::NORMAL_OCR) {
            return;
        }

        $isRepeated = Laminas::$serviceManager->patientForm->fetchOne([
            'column' => ['id'],
            'where' => [
                'item_id' => $this->owner->itemId,
                'itemsig_id' => $this->owner->itemsigId,
                'patient_id' => $this->owner->patientId,
                'form_id' => $this->owner->formId,
                'checktime_id' => $this->owner->checktimeId ?: 0,
                'is_del' => 0
            ]
        ]);

        if ($isRepeated) {
            throw new InvalidArgumentException('您已经填写过了~');
        }
    }
}