<?php

namespace Application\Form\project;

use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\ErrorHandler;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Laminas\Db\Sql\Predicate\Operator;

class LogicAeForm extends AeForm
{
    protected int $currentContentId = 0;

    // 把已有ae变成受试者ae
    public function updateAeType($csaeId)
    {
        if ($this->validator->attributes['type'] == 6) {
            $this->updateToPatientAE($csaeId);
            return;
        }

        // 取消勾选
        $originCheckedData = Laminas::$serviceManager->itemCsaeChecked->fetchAll([
            'where' => ['is_del' => 0, 'csae_id' => $csaeId]
        ]) ?: [];

        Laminas::$serviceManager->itemCsaeChecked->update([
            'is_del' => 1
        ], ['id' => ArrayHelper::getColumn($originCheckedData, 'id')]);
        // 变成未判断
        Laminas::$serviceManager->itemCsae->update(['ae_type' => 0, 'is_ae_sure' => 0], ['id' => $csaeId]);

        Laminas::$serviceManager->itemCsae->isAnnulChecknameSaveAction($csaeId);
    }

    protected function updateToPatientAE($csaeId)
    {
        Laminas::$serviceManager->itemPatientAeContent->update(['csae_id' => 0, 'new_ae_list' => 0, 'ae_type' => 0], ['csae_id' => $csaeId, 'ae_type' => 6]);
        Laminas::$serviceManager->itemCsaeRelation->update(['csae_id' => 0, 'new_ae_list_id' => 0], ['csae_id' => $csaeId]);
        Laminas::$serviceManager->itemCsaeChecked->update(['new_id' => 0], ['new_id' => $csaeId]);
    }

    protected function getPrevNode($branch)
    {
        $content = Laminas::$serviceManager->itemPatientAeContent->fetchOne([
            'order' => 'id desc',
            'where' => [
                'branch' => $branch,
                new Operator('id', Operator::OP_LT, $this->currentContentId)
            ]
        ]);

        if ($content) {
            return $content['id'];
        }

        throw new InvalidArgumentException('获取上一个node失败');
    }
}