<?php
namespace Application\Service\DB\Dictionary;

use Application\Common\DictionaryVarNameEnum;
use Application\Common\Enum;
use Application\Service\Extension\CheckLogic\Pointer;
use Application\Service\Extension\ErrorHandler;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\DataHelper;
use Application\Service\Extension\Helper\FormHelper;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\ValidatorV2\RulesContainer;
use Exception;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\Like;
use Laminas\Db\Sql\Predicate\PredicateSet;

class Form extends \Application\Service\DB\AbstractDb
{
    public array $_attachField = [];

    private array $_attachFieldVersion = [];

    private ?array $formExpression = [];

    private ?array $contentData = [];

    private ?bool $isUsingScoreAdmin = null;

    private ?array $requestParams = [];

    public static int $isFieldScore = 0;

    private ?int $errorId = null;

    /**
     * 逻辑核查: 渲染锁定的化验单表单
     * @var bool
     */
    public bool $renderAnnexLockForm = false;

    /**
     * [yikeen_item_form]
     * @var array
     */
    private array $formData = [];

    /**
     * version缓存数据
     * @var array|null
     */
    private ?array $versionData = [];

    /** @var string 手动填写KEY */
    public const ATTACH_SDTX = 'sdtx';

    public const ATTACH_SDTX_ANNEX_TITLE = '5562ea08df706f1_1659504863.webp';

    public const ATTACH_SDTX_ANNEX_PATH = '/upload/2022-08-03/5562ea08df706f1_1659504863.webp';

    /** @var string 手动填写填充文件路径 */
    public const ATTACH_CDTX_NAME = '/upload/2022-08-03/5562ea08df706f1_1659504863.webp';

    /** @var int 表单类型 - 一对一 */
    public const FORM_TYPE_SINGLE = 0;

    /** @var int 表单类型 - 一对多 */
    public const FORM_TYPE_MULTI = 1;

    /** @var int 表单完成条件 - 任意一个 */
    public const FORM_FINISH_CONDITION_ANYONE = 0;

    /** @var int 表单完成条件 - 全部完成 */
    public const FORM_FINISH_CONDITION_ALL = 1;

    private array $generateFields = [];

    protected string $previewScenario = 'default';

    /**
     * 质疑沟通预览场景
     */
    const SCENARIO_PREVIEW_QUESTION = 'question';

    /**
     * 逻辑核查场景
     */
    const SCENARIO_PREVIEW_LOGIC_CHECK = 'logicCheck';

    /** @var string 分值功能 */
    const SCENARIO_PREVIEW_USING_SCORE = 'usingScore';

    /** @var string 共享表单预览 */
    const SCENARIO_SHARE_FORM_UNLOCK = 'previewShareFormUnlock';

    const SCENARIO_CM_LIST_VIEW = 'CM_LIST_VIEW';

    public ?array $isWrite = null;

    const ITEM_FORM_SOURCE_URL = 'item/form/itemFormSource';

    private array $checkDetailOcrTemplate = [];

    public ?array $contentUpdatedData = null;
    public function __construct($dbAdapter, ContainerInterface $container)
    {
        if (!$this->tableName) {
            $this->tableName = 'yikeen_dictionary_form';
        }

        parent::__construct($dbAdapter, $container);
    }

    public function setRequestParams(array $params): Form
    {
        $this->requestParams = $params;
        return $this;
    }

    /**
     * 获取请求参数
     * @param string $name key
     * @param int $default default val.
     * @return int|mixed
     */
    private function getRequestParams(string $name, $default = 0)
    {
        return $this->requestParams[$name] ?? ($_POST[$name] ?? $default);
    }

    public function getCreateTime()
    {
        return time();
    }

    public function setLogicErrorId($id)
    {
        $this->errorId = $id;
        return $this;
    }

    public function getLogicExpression(string $expressionHash)
    {
        return Laminas::$serviceManager->itemPatientFormLogic->fetchOne([
            'where' => ['expression_hash' => $expressionHash]
        ]);
    }

    /**
     * 获取是否有受试者填写过此表单
     * @param int $formId
     * @return bool
     */
    public function getIsPatientWrite(int $formId): bool
    {
        return Laminas::$serviceManager->patientFormContent->fetchOne([
            'where' => ['form_id' => $formId, 'is_del' => 0]
        ]) || Laminas::$serviceManager->itemPatientAeContent->fetchOne([
                'where' => ['form_id' => $formId, 'is_del' => 0]
            ]);
    }

    /**
     * @return FormVersion
     */
    protected function getFormVersion(): FormVersion
    {
        return Laminas::$serviceManager->dictionaryFormVersion;
    }

    /**
     * 生成字典项表单 code 值
     * @return string
     */
    public function generateFormCode(): string
    {
        return 'DIC_' . StringHelper::generateHashValue();
    }

    protected function getFormField()
    {
        return Laminas::$serviceManager->dictionaryFormField;
    }

    /**
     * 重新生成version数据
     * @param int $formId
     * @return false|string
     */
    public function buildFieldVersion(int $formId)
    {
        self::$isFieldScore = 0;
        $query = $this->getFormField()->fetchAll([
            'where' => [
                'is_del' => 0,
                'version' => 'v1.0',
                'form_id' => $formId
            ]
        ]) ?: [];

        $field = [];
        $this->buildFirstLevel($query, $field);

        foreach ($field as $key => &$item) {
            // 移除已经添加过的子集
            if (!isset($item['id'])) {
                unset($field[$key]);
            }

            // 处理 form_type
            if (isset($item['children']) || in_array($item['type'] ?? '', [Enum::FORM_FIELD_TYPE_RADIO, Enum::FORM_FIELD_TYPE_CHECKBOX, Enum::FORM_FIELD_TYPE_DROPDOWN])) {
                $item['form_type'] = FormField::FORM_CONFIG_TEXT;
                $item['children_form_type'] = FormField::FORM_CONFIG_RADIO;
                if (isset($item['children']) && is_array($item['children'])) {
                    foreach ($item['children'] as &$child) {
                        $childData = $this->getFormField()->getFormData($child['id'], FormField::FORM_CONFIG_RADIO);
                        $child['form_type'] = FormField::FORM_CONFIG_RADIO;
                        $child['value'] = $childData['value'] ?? 0;
                        $child['is_check'] = $childData['is_check'] ?? 0;
                        $child['score'] = $childData['score'] ?? 0;
                        $child['is_score'] = $this->getIsFieldScore($childData['is_score'] ?? 0);
                        $child['var_name'] = $childData['var_name'];
                        $child['relation_information'] = $childData['relation_information'] ?? [];
                        $child['relation_classification'] = $childData['relation_classification'] ?? 0;
                        if ($child['relation_information']) {
                            foreach ($child['relation_information'] as $information) {
                                if ($information == 0) {
                                    continue;
                                }

                                $field[$information]['parent'][] = $child['id'];
                            }
                        }
                    }
                    $item['children_list'] = array_keys($item['children'] ?? []);
                }
            } else {
                if (isset($item['id'])) {
                    $rowData = $this->getFormField()->getFormData($item['id'], FormField::FORM_CONFIG_TEXT);
                    $item['placeholder'] = $rowData['placeholder'] ?? '';
                    $item['tips'] = $rowData['tips'] ?? '';
                    $item['form_type'] = FormField::FORM_CONFIG_TEXT;
                    $item['var_name'] = $rowData['var_name'] ?? '';
                    $item['unit'] = $rowData['unit'] ?? '';
                    $item['is_csae'] = $rowData['is_csae'] ?: 0;
                    $item['remind_type'] = $rowData['remind_type'] ?: 0;
                    $item['showfiled_name'] = $rowData['showfiled_name'] ?: 0;
                }
            }
        }

        // 处理子集排序
        array_walk($field, function (&$item) {
            if (isset($item['children'])) {
                $item['children'] = $this->orderField($item['children']);
            }
        });

        // 处理父集排序
        $field = $this->orderField($field);

        return json_encode($field);
    }

    public function buildFirstLevel($query, &$field)
    {
        foreach ($query as $value) {
            // 无父级字段
            if (!$value['parent']) {
                $field[$value['id']]['id'] = $value['id'];
                $field[$value['id']]['name'] = $value['name'];
                $field[$value['id']]['order'] = $value['order'] ?: 1;
                $field[$value['id']]['type'] = $value['type'];
                $field[$value['id']]['is_list'] = $value['is_list'];
                $field[$value['id']]['is_hide'] = $value['is_hide'];
                $field[$value['id']]['is_anchor'] = $value['is_anchor'];
                $field[$value['id']]['is_booked_time'] = $value['is_booked_time'];
                $field[$value['id']]['var_name'] = $value['var_name'];
                $field[$value['id']]['showfiled_name'] = $value['showfiled_name'];
                $field[$value['id']]['default'] = $value['default'];
                $field[$value['id']]['unit'] = $value['unit'];
                $field[$value['id']]['rules'] = $value['rules'];
                $field[$value['id']]['item_form_source_set'] = $value['item_form_source_set'];
            } else {
                $field[$value['parent']]['children'][$value['id']] = [
                    'id' => $value['id'],
                    'name' => $value['name'],
                    'order' => $value['order'] ?: 1,
                    'type' => $value['type'],
                    'parent' => $value['parent'],
                ];
            }
        }
    }

    private function getIsFieldScore($data)
    {
        if ($data == 1) {
            self::$isFieldScore = 1;
        }
        return $data ?? 0;
    }

    // 修改排序顺序
    protected function orderField(array $field)
    {
        ArrayHelper::multisort($field, 'order');
        return array_column($field, null, 'id');
    }

    /**
     * 获取表单数据
     * @param array $condition
     * @return mixed
     */
    private function getFormData(array $condition)
    {
        return $this->memoryCache()->fetchOne([
            'where' => $condition
        ]);
    }


    /**
     * 质疑的数据和普通的表单数据不太一样。
     * 设置表单结构预览场景。
     * 默认default.
     * 质疑设置为 @see Form::SCENARIO_PREVIEW_QUESTION
     * 逻辑核查 @see Form::SCENARIO_PREVIEW_LOGIC_CHECK
     * $this->LocalService()->itemForm->setPreviewScenario(Form::SCENARIO_PREVIEW_QUESTION)->getPreviewConfig($id);
     * @param string $scenario
     * @return $this
     */
    public function setPreviewScenario(string $scenario): Form
    {
        $this->previewScenario = $scenario;
        return $this;
    }

    public function reset()
    {
        $this->formData = [];
        $this->versionData = [];
        $this->renderAnnexLockForm = false;
        return $this;
    }

    /**
     * 获取表单预览配置
     *
     * @param  int    $formId
     * @param  false  $debugMode 开启了会输出生成了哪些key
     *
     * @return array|mixed|void
     * @throws Exception
     */
    public function getPreviewConfig(int $formId, bool $debugMode = false, bool $usingCache = true)
    {
        if ($usingCache === false) {
            $this->formData = $this->generateFields = [];
        }

        $config = $this->generateFields = [];

        $this->formData = $this->getFormData(['id' => $formId]) ?: [];

        if (!$this->formData) {
            return [];
        }
        // 表达式
        if ($expression = FormHelper::getFormatFormExpression($this->formData['expression'], 'preview')) {
            $this->formExpression = $expression;
        }

        $this->versionData = $this->getFormVersion()->getField([
            'version' => 'v1.0',
            'form_id' => $formId,
        ], true);

        // 如果有手写签名, 就追加一个字段
        if ($this->formData['is_handwritten_signature'] == 1) {
            $this->versionData[] = [
                'id' => -1,
                'type' => 'canvasButton',
                'name' => '手写签名',
                'prop' => 'handwritten_signature'
            ];
        }

        // 渲染被锁定的化验单的表单
        if ($this->renderAnnexLockForm === true) {
            return $this->renderAnnexLockForm();
        }
        if ($this->formData['type'] == self::FORM_TYPE_MULTI) { // 处理 一对多
            if (SDMHelper::app()->form->getIsCMINDCForm($formId) && $this->previewScenario == 'default') {
                foreach ($this->getAEResultString() as $k => $item) {
                    $this->versionData["ae_result_{$k}"] = [
                        'name' => $item,
                        'type' => FormField::FORM_FIELD_TYPE_SPAN
                    ];
                }
            }

            $config = $this->_handleMultiType($this->versionData);
        } elseif ($this->formData['type'] == self::FORM_TYPE_SINGLE) { // 处理 一对一
            $config = $this->_handleSingleType($this->versionData);
        }
        if (!$config) {
            throw new Exception("未知的表单类型");
        }
        if ($debugMode) {
            return [
                'config' => $config,
                'generateFields' => $this->generateFields
            ];
        }

        if (isset($config['form']) && !$config['form'] && $this->previewScenario === 'previewShareFormUnlock') {
            $config['form'] = array_fill(0, 10, [
                    'type' => 'Span',
                    'label' => '',
                    'tips' => '',
                    'prop' => 'span',
                    'imageUrl' => '',
                    'fileListImg' => '',
                    'action' => '',
                    'var_name' => '',
                    'rules' => '',
                    'field_id' => '0',
                    'is_csae' => '0',
                    'is_have_child' => '0',
                ]);
        }

        //合并用药表单 - 药物名称增加触发事件【用来实现固定药物 默认用药原因】
        if(!empty($config['form'])){
            $configFormFieldVarNameArr = array_values(array_column($config['form'],'var_name'));
            if(in_array('CMNAM',$configFormFieldVarNameArr) && in_array('CMINDC100',$configFormFieldVarNameArr)){
                foreach($config['form'] as &$configFormField){
                    if($configFormField['var_name'] == 'CMNAM'){
                        $configFormField['trigger_event'] = [
                            'url'=>'item/form/getdrugcm',
                            'params'=>['item_id'=>$this->formData['item_id']]
                        ];
                    }
                }
            }
            unset($configFormFieldVarNameArr);
        }
        return $config;
    }

    private function renderAnnexLockForm(): array
    {
        $annexId = Laminas::$serviceManager->itemPatientFormLogicError->fetchOne([
            'where' => ['id' => $this->errorId]
        ])['multi_id'];

        $isCollectData = Laminas::$serviceManager->itemPatientFormLogicErrorPointer->fetchOne([
                'order' => ['id DESC'],
                'where' => ['error_id' => $this->errorId, 'form_id' => $this->formData['id'], 'is_del' => 0]
            ])['prop'] ?? false;

        $isCollectDate = in_array($isCollectData, ['collect_date', 'OCR_CHECK_TIME']);

        $annexData = Laminas::$serviceManager->itemIdentificationresultchange->fetchOne([
            'where' => ['id' => $annexId]
        ]);

        //获取该副项目设置的采集时间类型
        $dateType = 1;
        if(!empty($annexData['item_id'])){
            $dateType = Laminas::$serviceManager->itemCheckdate->getOneFieldVal('date_type','is_del = 0 and item_id = '.$annexData['item_id']);
            $dateType = empty($dateType) ? 1 : $dateType;
        }

        $dateTypeIndex = [
            '1' => FormField::FORM_FIELD_TYPE_LABEL,
            '2' => FormField::FORM_FIELD_TYPE_DATETIME,
            '3' => FormField::FORM_FIELD_TYPE_DATE_SECOND
        ];
        // 如果质疑的是检查时间只显示检查时间
        if ($isCollectDate) {

            $fakeData = [
                [
                    'id' => $isCollectData,
                    'name' => '检查时间',
//                    'placeholder' => date('Y-m-d', $annexData['collect_date']),
                    'placeholder' => $annexData['collect_date'],
                    'is_report_special' => false,
                    'type' => $dateTypeIndex[$dateType]
//                    'type' => FormField::FORM_FIELD_TYPE_LABEL
                ]
            ];

//            if($dateType == 2){//年月日(时分)
//                $fakeData = [
//                    [
//                        'id' => $isCollectData,
//                        'name' => '检查时间',
//                        'placeholder' => date('Y-m-d H:i', $annexData['collect_date']),
//                        'type' => FormField::FORM_FIELD_TYPE_DATETIME
//                    ]
//                ];
//            }
//            if($dateType == 3){//年月日(时分秒)
//                $fakeData = [
//                    [
//                        'id' => $isCollectData,
//                        'name' => '检查时间',
//                        'placeholder' => date('Y-m-d H:i:s', $annexData['collect_date']),
//                        'type' => FormField::FORM_FIELD_TYPE_DATE_SECOND
//                    ]
//                ];
//            }
        } else {
            $fakeData = [
                [
                    'id' => 'collect_date',
                    'name' => '检查时间',
//                    'placeholder' => date('Y-m-d', $annexData['collect_date']),
                    'placeholder' => $annexData['collect_date'] != '' ? $annexData['collect_date'] : '',
//                    'type' => FormField::FORM_FIELD_TYPE_LABEL,
                    'type' => $dateTypeIndex[$dateType],
                ],
                [
                    'id' => 'item_name',
                    'name' => '指标名称',
                    'placeholder' => $annexData['item_name'] ?: '--',
                    'type' => FormField::FORM_FIELD_TYPE_LABEL
                ],
                [
                    'id' => 'unit',
                    'name' => '单位',
                    'placeholder' => $annexData['unit'] ?: '--',
                    'props' => 'unit',
                    'type' => FormField::FORM_FIELD_TYPE_LABEL,
                ],
                [
                    'id' => 'result',
                    'name' => '结果',
                    'placeholder' => $annexData['result'] ?: '--',
                    'type' => FormField::FORM_FIELD_TYPE_LABEL
                ],
                [
                    'id' => 'range',
                    'name' => '取值范围',
                    'placeholder' => call_user_func(function() use ($annexData) {
                        $res = [];
                        if ($annexData['reference_range_min']) {
                            $res[] = $annexData['reference_range_min'];
                        }
                        if ($annexData['reference_range_max']) {
                            $res[] = $annexData['reference_range_max'];
                        }
                        return implode('~', $res) ?: '--';
                    }),
                    'type' => FormField::FORM_FIELD_TYPE_LABEL
                ],
                [
                    'id' => 'normal',
                    'name' => '正常',
                    'placeholder' => $annexData['is_normal_type'] == 1 ? '√' : '--',
                    'type' => FormField::FORM_FIELD_TYPE_LABEL
                ],
                [
                    'id' => 'cs',
                    'name' => 'CS',
                    'placeholder' => $annexData['is_normal_type'] == 2 ? '√' : '--',
                    'type' => FormField::FORM_FIELD_TYPE_LABEL
                ],
                [
                    'id' => 'ncs',
                    'name' => 'NCS',
                    'placeholder' => $annexData['is_normal_type'] == 3 ? '√' : '--',
                    'type' => FormField::FORM_FIELD_TYPE_LABEL
                ],
                [
                    'id' => 'is_identification',
                    'name' => '未查',
                    'placeholder' => $annexData['is_identification'] == true ? '√' : '--',
                    'type' => FormField::FORM_FIELD_TYPE_LABEL
                ],
            ];

//            if($dateType == 2){//年月日(时分)
//                $fakeData[0] = [
//                    'id' => '??', //$isCollectData,
//                    'name' => '检查时间',
//                    'placeholder' => date('Y-m-d H:i', $annexData['collect_date']),
//                    'type' => FormField::FORM_FIELD_TYPE_DATE_SECOND
//                ];
//            }
//            if($dateType == 3){//年月日(时分秒)
//                $fakeData[0] = [
//                    'id' => '??', //$isCollectData,
//                    'name' => '检查时间',
//                    'placeholder' => date('Y-m-d H:i:s', $annexData['collect_date']),
//                    'type' => FormField::FORM_FIELD_TYPE_DATETIME
//                ];
//            }
        }

        $res = [];
        foreach ($fakeData as $datum) {
            $res[] = $this->buildConfig($datum);
        }

        return [
            'form' => $res
        ];
    }

    private function buildConfigV2(array $data, string $prop, array $versionData, &$map = [])
    {
        $this->generateFields[] = $prop;
        $hasChild = (isset($data['children']) && is_array($data['children'])) || ($data['hasChild'] ?? false);

        if ($hasChild) {
            foreach ($data['children'] as $child) {
                $currentProp = "{$prop}-{$child['value']}";

                // 构建关联字段
                $relationConfig = $this->buildRelationConfig(
                    $child['relation_information'] ?? [],
                    $versionData,
                    $currentProp
                );

                if ($buildConfig = ArrayHelper::getColumn($relationConfig, 'buildConfig')) {
                    // 对化验单的单独处理
                    $config = $this->handleBuildResult(array_values($buildConfig), $child);
                    $map[$prop][$child['value']] = $config;
                }

                foreach ($relationConfig as $value) {
                    $this->buildConfigV2($value['versionData'] ?: [], $value['prop'], $versionData, $map);
                }
            }

            return $map;
        }

        return $map;
    }

    private function handleBuildResult(array $result, array $child): array
    {
        $tmp = [];

        // 处理多选关联字段
        $appendParent = false;
        if (isset($child['parent']) && $this->versionData[$child['parent']]['type'] == FormField::FORM_FIELD_TYPE_CHECKBOX) {
            $appendParent = true;
        }

//        var_dump($result);
        foreach ($result as $k => &$v) {
            // 如果是多选关联字段, 需要在关联的字段后面追加选项值的名字
            if ($appendParent === true) {
                $v['label'] = "{$v['label']}({$child['name']})";
            }

            // 表单计算公式
            if ($this->formExpression && $v['var_name'] === $this->formExpression['result']) {
                $h = function ($expression) {
                    $fields = Laminas::$serviceManager->itemFormField->fetchAll([
                        'where' => ['form_id' => $this->formData['id'], 'parent' => 0]
                    ]);

                    $allVarName = implode('|', ArrayHelper::getColumn($fields, 'var_name'));
                    $pregStr = "($allVarName)";
                    preg_match_all("/\b{$pregStr}\b/", $this->formExpression['expression'][0], $matches);

                    return array_values(array_unique(array_filter($matches[0])));
                };

                $res['expression'] = $h($this->formExpression['expression']);
            }

            $tmp[] = $v;
            if ($this->previewScenario === 'default' || $this->previewScenario == 'logicCheck') {
                // 对化验单的单独处理
                // 不是医嘱类型的化验单, 需要移除手动填写
                if ($v['var_name'] === 'CHECKIMG' && $this->formData['group_id'] != FormGroup::CHECK_DO) {
                    $tmp[] = [
                        'type' => 'TableButton',
                        'prop' => self::ATTACH_SDTX,
                        'label' => '手动填写',
                    ];
                }
            }
        }

        foreach ($tmp as &$r) {
            $this->setNote($r);
        }
        return $tmp;
    }

    //新加
    private function setCheckLogicError(array &$res)
    {
        $field = $res['prop']; // DataHelper::getFieldId($res['prop']);
        $isProcess = $this->formData['group_id'] == FormGroup::THROUGH_PROCESS;
        $pid = $_POST['patient_id'] ?: 0;
        $res['is_update'] = $this->getFieldIsUpdate($field);
        // 界面不让编辑
        $res['disabled'] = true;
        // 逻辑核查表单预览
        $g = new Pointer();
        $g->setIsProcess($this->formData['group_id'] == FormGroup::THROUGH_PROCESS);
        $g->setFormId($this->formData['id']);
        if ($this->previewScenario === self::SCENARIO_PREVIEW_LOGIC_CHECK) {
//            $g = new Pointer();
            $g->setErrorId(array($_POST['error_id']));
            $g->setPatientId($pid);
            $usingField = $g->getUsingField();
            if (isset($usingField) && (in_array($field, $usingField) !== false || in_array($field.'-normal_type', $usingField) !== false || in_array(DataHelper::getFieldId($res['prop']), $usingField) !== false || in_array(DataHelper::getFieldId($res['prop'].'-normal_type'), $usingField) !== false)) {
                $res['is_logic_error'] = true;
                $res['logic_error_message'] = $res['normal_type_logic_error_message'] = [];
                if(in_array($field, $usingField) !== false || in_array(DataHelper::getFieldId($res['prop']), $usingField) !== false) {
                    $res['logic_error_message'] = $g->getFieldError($field);
                }
                if(in_array($field.'-normal_type', $usingField) !== false || in_array(DataHelper::getFieldId($res['prop'].'-normal_type'), $usingField) !== false){
                    $res['normal_type_logic_error_message'] = $g->getFieldError($field.'-normal_type');
                }
                $res['error_id'] = intval($_POST['error_id']);
                // 质疑详情ocr模板设置
                $this->checkDetailOcrTemplate = [
                    $res
                ];

                return $res;
            }
        } elseif ($this->previewScenario === 'default') {
            // 进度管理场景
//            $g = new Pointer();
            $g->setPatientId($pid);
            $condition = [
                'patient_id' => $pid,
//                'is_report' => 0,
                'form_id' => $this->formData['id']
//                'is_del' => 0 // 关闭的也展示
            ];

            if ($isProcess === false && $_POST['checktime_id']) {
                $condition[] = new \Laminas\Db\Sql\Predicate\Expression("FIND_IN_SET('{$_POST['checktime_id']}',checktime_id)");
            }

            if (!$err = Laminas::$serviceManager->itemPatientFormLogicErrorPointer->memoryCache()->fetchAll([
                'order' => ['id DESC'],
                'where' => $condition
            ])) {
                return $res;
            }

            $error = Laminas::$serviceManager->itemPatientFormLogicError->memoryCache()->fetchAll([
                'order' => ['id DESC'],
                'where' => ['id' => ArrayHelper::getColumn($err, 'error_id'), 'patient_id' => $pid]
            ]);
            if (!$error) {
                return $res;
            }

            $g->setErrorId(ArrayHelper::getColumn($error, 'id'));

            if ($_POST['content_id'] && $_POST['content_id'] !== 'undefined') {
                $g->setMultiId($_POST['content_id']);
            }

            if ($_POST['checktime_id'] && $_POST['checktime_id'] !== 'undefined') {
                $g->setCheckTimeId($_POST['checktime_id']);
            }

            $usingField = $g->getUsingField();

            if (isset($usingField) && (in_array($field, $usingField) !== false || in_array($field.'-normal_type', $usingField) !== false || in_array(DataHelper::getFieldId($res['prop']), $usingField) !== false || in_array(DataHelper::getFieldId($res['prop'].'-normal_type'), $usingField) !== false)) {
                // 关闭的质疑不展示
                $res['is_logic_error'] = true;
                $res['logic_error_message'] = $res['normal_type_logic_error_message'] = [];
                if(in_array($field, $usingField) !== false || in_array(DataHelper::getFieldId($res['prop']), $usingField) !== false){
                    $res['logic_error_message'] = $g->getFieldError($field);
                }
                if(in_array($field.'-normal_type', $usingField) !== false || in_array(DataHelper::getFieldId($res['prop'].'-normal_type'), $usingField) !== false){
                    $res['normal_type_logic_error_message'] = $g->getFieldError($field.'-normal_type');
                }
                $res['error_id'] = $g->errorId;
                // 质疑详情ocr模板设置
                $this->checkDetailOcrTemplate = [
                    $res
                ];

                return $res;
            }
        }

        return $res;
    }

    //新加
    private function getFieldIsUpdate($fieldId): bool
    {
        $request = Laminas::$serviceManager->request;
        $contentId = $request->getPost('content_id');
        if ($contentId && $contentId !== 'undefined') {
            if ($this->contentUpdatedData === null) {
                $this->contentUpdatedData = json_decode(Laminas::$serviceManager->patientFormContentUpdated->memoryCache()->fetchOne([
                    'where' => ['content_id' => $contentId, 'is_del' => 0]
                ])['fields'] ?? '[]', true);
            }
        } else {
            $this->contentUpdatedData = json_decode(Laminas::$serviceManager->patientFormContentUpdated->memoryCache()->fetchOne([
                'where' => [
                    'item_id' => $request->getPost('item_id'),
                    'checktime_id' => $request->getPost('checktime_id'),
                    'form_id' => $request->getPost('id'),
                    'patient_id' => $request->getPost('patient_id'),
                    'is_del' => 0
                ]
            ])['fields'] ?? '[]', true);
        }

        if (in_array($fieldId, array_keys($this->contentUpdatedData))) {
            return true;
        }

        return false;
    }


    /**
     * 处理匹配配置
     * @param array $data
     * @param string $prop
     * @param array $versionData
     * @return array
     */
    private function handleMatchConfig(array $data, string $prop, array $versionData)
    {
        return $this->buildConfigV2($data, $prop, $versionData);
    }

    private function buildRelationConfig(array $relationInformation, array $versionData, string $prop): array
    {
        $config = [];

        // 去除空数组
        $relationInformation = array_filter($relationInformation);

        foreach ($relationInformation as $k => $information) {
            if (isset($versionData[$information])) {
                // 当前选项值 + 上一级的prop
                $config[$k]['prop'] = $information . '-' . $prop;
                $config[$k]['buildConfig'] = $this->_buildConfigV2($versionData[$information], $config[$k]['prop']);
                $config[$k]['versionData'] = $versionData[$information] ?: [];
                $config[$k]['hasChild'] = isset($versionData[$information]['children']);
            }
        }

        return $config;
    }

    private function _handleMultiType(array $versionData)
    {
        $shareImageFieldId = 0;

        $map = $form = $table = [];
        foreach ($versionData as $versionKey => $versionDatum) {
//            if($versionKey != 266452) continue;
            if (!isset($versionDatum['parent'])) {
                $form[$versionKey] = $this->_buildConfigV2($versionDatum, $versionKey);

                $map = (ArrayHelper::merge($map, $this->handleMatchConfig($versionDatum, $versionKey, $versionData)));
            }

            if ($versionDatum['type'] === FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE) {
                $shareImageFieldId = $versionDatum['id'];
            }
        }

        // 一对多表格第一个表头要加上宽度
        $index = 0;
        // 哪些是表格上展示的字段
        foreach ($versionData as $versionDatum) {
            if ($versionDatum['is_list'] == 1) {
                $table[$versionDatum['id']] = [
                    'label' => $form[$versionDatum['id']]['label'] ?? $versionDatum['name'],
                    'prop' => $form[$versionDatum['id']]['prop'] ?? $versionDatum['id'],
                ];

                // 一对多表格第一个表头要加上宽度
                if ($index == 0) {
                    $table[$versionDatum['id']]['width'] = '200';
                }
            }
            $index++;
        }

        // 表格上展示的字段追加分值列
        if ((bool)Laminas::$serviceManager->itemFormFieldRadio->memoryCache()->fetchOne([
            'columns' => ['id'], 'where' => ['is_score' => 1, 'form_id' => $this->formData['id']]
        ])) {
            $table['score'] = [
                'label' => "分值", //"分值(合计: {$this->getTotalScore()})",
                'prop' => 'score',
            ];
        }

        $table = array_values($table);

        // 如果只有一个表头, 就去掉宽度
        if (count($table) == 1) {
            unset($table[0]['width']);
        }

        // 质疑沟通对常规识别表单一对多类型的做的特殊处理。
        if ($this->previewScenario === self::SCENARIO_PREVIEW_QUESTION && $this->formData['group_id'] == FormGroup::NORMAL_OCR) {
            return ArrayHelper::merge([
                'form' => array_filter([
                            [
                                'type' => 'UploadImg',
                                'label' => '图片',
                                'tips' => '请输入图片',
                                'prop' => $shareImageFieldId,
                                'imageUrl' => '',
                                'fileListImg' => '',
                                'action' => '',
                                'var_name' => '',
                                'rules' => '',
                                'field_id' => $shareImageFieldId,
                                'is_csae' => '0',
                                'is_have_child' => '0',
                            ]
                        ]),
                'table' => array_values($table)],
                $map
            );
        }

        return ArrayHelper::merge(['form' => array_values(array_filter($form)), 'table' => array_values($table)], $map);
    }

    private function getTotalScore()
    {
        $c = Laminas::$serviceManager->patientFormContent->fetchAll([
            'columns' => ['data'],
            'where' => [
                'patient_id' => $_POST['patient_id'] ?? 0,
                'form_id' => $this->formData['id'],
                'checktime_id' => $_POST['checktime_id'] ?? 0,
                'itemsig_id' => $_POST['itemsig_id'] ?? 0,
                'is_del' => 0
            ]
        ]);

        $totalScore = 0;
        foreach ($c as $item) {
            $item = StringHelper::jsonDecode($item['data']);
            $totalScore += $item['score'];
        }
        return $totalScore;
    }

    /**
     * 处理一对一表单
     * @param array $versionData
     * @return mixed|void
     */
    private function _handleSingleType(array $versionData)
    {
        $matchConfig = $cache = [];
        foreach ($versionData as $versionKey => $versionDatum) {
//            if($versionKey <> 275683){ continue;}
//            if($versionKey <> 266096){ continue;}
            // 处理首层数据
            if (!isset($versionDatum['parent'])) {
                $config = $this->_buildConfigV2($versionDatum, $versionKey);
                if($this->previewScenario == 'previewShareFormUnlock'){
                    if(!empty($config) && !isset($config['logic_error_message'])){
                        unset($config['rules']);
                    }
                }
                //logic_error_message
                if ($config) {
                    //字段整数类型 需要将Input改为Number
                    if($versionDatum['type'] == 6) $config['type'] = 'Number';
                    if(isset($config['rules'])){
                        $ruleType = array_column($config['rules'],'type');
                        if(in_array('number',$ruleType)) $config['type'] = 'Number';
                    }
                    $form[] = $cache[$versionKey] = $config;
                    $matchConfig = ArrayHelper::merge($matchConfig, $this->handleMatchConfig($versionDatum, $versionKey, $versionData));
                }
            }
        }

        foreach ($this->_attachField as $fieldId => $fieldConfig) {
            if (isset($cache[$fieldId])) {
                $matchConfig = ArrayHelper::merge($matchConfig, $this->handleMatchConfig($fieldConfig, $fieldId, $this->_attachFieldVersion));
            }
        }


        return ArrayHelper::merge(['form' => $form ?: []], $matchConfig);
    }

    public function buildConfig(array $data)
    {
        return $this->_buildConfigV2($data);
    }

    public function getRules(array $rowData)
    {
        $rules = [];
        if (isset($rowData['rules']) && $rowData['remind_type'] == 0) {
            /** @var RulesContainer $rulesContainer */
            $rulesContainer = unserialize($rowData['rules']);
            $containerRules = ArrayHelper::index($rulesContainer->rules ?? [], 'method');
            if (isset($containerRules['required'])) {
                $rules[] = ['required' => true, 'message' => "{$rowData['name']} 不能为空."];
            }
            if(isset($containerRules['uppercase'])){
                $rules[] = ['validator'=>'uppercase', 'message' => "{$rowData['name']} 必须全部大写."];

            }
            if (isset($containerRules['string'])) {
                $max = 0;
                $min = 0;
                foreach ($rulesContainer->rules as $k=>$v){
                    if($v['method'] != 'string') continue;
                    if(isset($v['attr']['max'])){
                        $max = $v['attr']['max'];
                    }
                    if(isset($v['attr']['min'])){
                        $min = $v['attr']['min'];
                    }
                }

                $rules[] = ['min'=> (int)$min,'max'=>(int)$max, 'message' => "{$rowData['name']} 长度不能大于".$max."或小于".$min];
            }

            if (isset($containerRules['number'])) {
                $minVal = -99999999;
                $maxVal = 99999999;
                foreach($rulesContainer->rules as $k=>$v){
                    if($v['method'] <> 'number') continue;
                    if(isset($v['attr']['min'])) $minVal = $v['attr']['min'] + 0;
                    if(isset($v['attr']['max'])) $maxVal = $v['attr']['max'] + 0;
                }
                $rules[] = ['type'=>'number','min'=> $minVal,'max'=>$maxVal,'message' => "{$rowData['name']} 不能小于".$minVal."且不能大于".$maxVal];
            }
        }

        return $rules;
    }

    private function getTips($row): string
    {
        if ($row['type'] == FormField::FORM_FIELD_TYPE_SPAN) {
            return $row['placeholder'] ?: "{$row['name']}";
        }
        return $row['placeholder'] ?: "请输入{$row['name']}";
    }

    private function getPlaceholder($rowData): string
    {
        if ($rowData['type'] == FormField::FORM_FIELD_TYPE_SPAN) {
            return $rowData['placeholder'] ?: "{$rowData['name']}";
        }
        return $rowData['placeholder'] ?: "请输入{$rowData['name']}";
    }

    private function _buildConfigV2(array $row, $prop = null)
    {

        $row = $this->beforeBuild($row);
        //遇到隐私字段直接返回 不显示 但项目图库的常规识别入口需要展示隐私字段
        if($this->previewScenario <> self::SCENARIO_SHARE_FORM_UNLOCK && $row['is_hide'] == 1){
            return ;
        }

        if($row['var_name'] == DictionaryVarNameEnum::COLLECT_MEDICAL_TAKE_CMINDC && $this->previewScenario == self::SCENARIO_CM_LIST_VIEW){
            $row['type'] = FormField::FORM_FIELD_TYPE_DROPDOWN;
            $row['name'] = 'CM判断结果';
        }

        $originType = $row['type'];
        if (
            in_array($row['type'], [
                    FormField::FORM_FIELD_TYPE_DATE_UK,
                    FormField::FORM_FIELD_TYPE_DATETIME_UK,
                    FormField::FORM_FIELD_TYPE_DATETIME_SECOND_UK,
                    FormField::FORM_FIELD_TYPE_TEXT,
                    FormField::FORM_FIELD_TYPE_TEXTAREA,
                    FormField::FORM_FIELD_TYPE_DATE,
                    FormField::FORM_FIELD_TYPE_DATE_SECOND,
                    FormField::FORM_FIELD_TYPE_DATETIME,
                    FormField::FORM_FIELD_TYPE_TIME_UK,
                    FormField::FORM_FIELD_TYPE_TIME_SECOND_UK,
                    FormField::FORM_FIELD_TYPE_DATETIME,
                    FormField::FORM_FIELD_TYPE_INTEGER,
                    FormField::FORM_FIELD_TYPE_FLOAT_1,
                    FormField::FORM_FIELD_TYPE_FLOAT_2,
                    FormField::FORM_FIELD_TYPE_FLOAT_3,
                    FormField::FORM_FIELD_TYPE_LABEL,
                    FormField::FORM_FIELD_TYPE_SPAN,
            ])
        ) {
            $res = [
                'type' => $this->_getType($row['type']),
                'label' => $row['type'] == FormField::FORM_FIELD_TYPE_SPAN ? '' : $row['name'],
                'placeholder' => $this->getPlaceholder($row),
                'tips' => $this->getTips($row),
                'prop' => strval($prop ?: $row['id']),
                'rules' => $this->getRules($row),
                'var_name' => $row['var_name'],
            ];
            // 返回默认值
            if (
                in_array($row['type'], [
                    FormField::FORM_FIELD_TYPE_TEXT,
                    FormField::FORM_FIELD_TYPE_INTEGER,
                    FormField::FORM_FIELD_TYPE_FLOAT_1,
                    FormField::FORM_FIELD_TYPE_FLOAT_2,
                    FormField::FORM_FIELD_TYPE_FLOAT_3,
                    FormField::FORM_FIELD_TYPE_DATE,
                    FormField::FORM_FIELD_TYPE_DATE_UK,
                    FormField::FORM_FIELD_TYPE_DATE_SECOND,
                    FormField::FORM_FIELD_TYPE_DATETIME,
                    FormField::FORM_FIELD_TYPE_LABEL,
                    FormField::FORM_FIELD_TYPE_SPAN,
                ]) && isset($row['default'])
            ) {
                $res['default'] = in_array($row['type'], [FormField::FORM_FIELD_TYPE_LABEL, FormField::FORM_FIELD_TYPE_SPAN]) ? $this->getPlaceholder($row) : $row['default'];
            }

            // 返回单位
            if (
                in_array($row['type'], [
                    FormField::FORM_FIELD_TYPE_TEXT,
                    FormField::FORM_FIELD_TYPE_INTEGER,
                    FormField::FORM_FIELD_TYPE_FLOAT_1,
                    FormField::FORM_FIELD_TYPE_FLOAT_2,
                    FormField::FORM_FIELD_TYPE_FLOAT_3
                ]) && isset($row['unit'])
            ) {
                $res['unit'] = $row['unit'];
            }
            // label 标签
            if ($row['type'] == FormField::FORM_FIELD_TYPE_LABEL) {
                $res['disabled'] = true;
            }

        } elseif (in_array($row['type'], [Enum::FORM_FIELD_TYPE_RADIO, Enum::FORM_FIELD_TYPE_CHECKBOX, FormField::FORM_FIELD_TYPE_DROPDOWN, FormField::FORM_FIELD_TYPE_REGION_OPTION])) {
            $config = [
                'type' => $this->_getType($row['type']),
                'label' => $row['name'],
                'prop' => strval($prop ?: $row['id']),
                'rules' => $this->getRules($row),
                'var_name' => $row['var_name'],
                'random' => $row['random'] ?? '',
            ];

            if ($default = $this->_getDefault($row)) {
                $config['default'] = $default;
            }

            if ($child = $this->_getChild($row)) {
                $config[$child[0]] = $child[1];
            }
            $config['disabled'] = $row['disabled'] ?? false;

            $res = $config;
        } elseif (in_array($row['type'], [Enum::FORM_FIELD_TYPE_UPLOAD_IMAGE, FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE])) {
            $res = [
                'type' => $this->_getType($row['type']),
                'label' => $row['name'],
                'tips' => $this->getTips($row),
                'prop' => strval($prop ?: $row['id']),
                'imageUrl' => '',
                'fileListImg' => [],
                'action' => \Application\Controller\CommonController::UPLOAD_IMG_URL,
                'var_name' => $row['var_name'],
                'rules' => $this->getRules($row),
            ];

            // 识别类表单在图文识别的地方不要展示图片的字段
            if ($this->previewScenario === self::SCENARIO_SHARE_FORM_UNLOCK && $row['type'] == FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE) {
                $res = [];
            } elseif ($this->formData['type'] == Form::FORM_TYPE_MULTI && in_array($this->previewScenario, ['default', self::SCENARIO_PREVIEW_LOGIC_CHECK]) && $row['type'] == FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE) {
                $res = [];
            }
        } elseif ($row['type'] == Enum::FORM_FIELD_TYPE_UPLOAD_FILE) {
            $res = [
                'type' => $this->_getType($row['type']),
                'label' => $row['name'],
                'tips' => $this->getTips($row),
                'prop' => strval($prop ?: $row['id']),
                'fileList' => [],
                'action' => \Application\Controller\CommonController::UPLOAD_URL,
                'var_name' => $row['var_name'],
                'rules' => $this->getRules($row),
            ];
        } elseif ($row['type'] == Enum::FORM_FIELD_TYPE_EDITOR) {
            $res = [
                'type' => $this->_getType($row['type']),
                'label' => $row['name'],
                'prop' => strval($prop ?: $row['id']),
                'var_name' => $row['var_name'],
            ];
        } elseif ($row['type'] == FormField::FORM_FIELD_TYPE_ITEM_FORM_SOURCE) {
            [$form_id, $field_id] = explode('|', $row['item_form_source_set']);
            $res = [
                'type' => $this->_getType($row['type']),
                'label' => $row['name'],
                'placeholder' => $this->getPlaceholder($row),
                'tips' => $this->getTips($row),
                'prop' => strval($prop ?: $row['id']),
                'rules' => $this->getRules($row),
                'var_name' => $row['var_name'],
                'remote' => [
                    'url'=> self::ITEM_FORM_SOURCE_URL,
                    'params'=>[
                        'patient_id' => $this->getRequestParams('patient_id', 0),
                        'item_form_source_set' => $row['item_form_source_set'] ?? ''
                    ]
                ],
                'defaultProps' => [
                    'value' => $field_id,
                    'title' => $field_id
                ]
            ];
        } elseif (is_string($row['type'])) { // 如果是文本类型的, 就返回自身 (手写签名)
            $res = [
                'type' => $row['type'],
                'label' => $row['name'],
                'prop' => $row['prop'] ?? '',
            ];
        }

        // 处理正则表达式
        if ($regex = $this->getRegex($originType)) {
            $res['regex'] = $regex;
        }

        if (is_string($row['id']) && isset($row['is_report_special'])) {
            $res['is_report_special'] = $row['is_report_special'];
        }
        if ($res) {
            $res['field_id'] = $row['id'];
            $res['is_csae'] = isset($row['is_csae']) && !empty($row['is_csae']) ? $row['is_csae'] : 0;
            $res['is_have_child'] = $res['is_csae'] == 1 ? 1 : 0;
        }

        return $this->afterBuild($res);
    }

    private function beforeBuild(array $row)
    {
        return $row;
    }

    private function afterBuild($res)
    {
        // 表单计算公式
        if ($this->formExpression && isset($res['var_name']) &&$res['var_name'] === $this->formExpression['result']) {
            $h = function ($expression) {
                $fields = Laminas::$serviceManager->itemFormField->fetchAll([
                    'where' => ['form_id' => $this->formData['id'], 'parent' => 0]
                ]);

                $allVarName = implode('|', ArrayHelper::getColumn($fields, 'var_name'));
                $pregStr = "($allVarName)";

                $ex = $expression[0];
                // 兼容旧版本公式
                if (count($expression) > 1) {
                    $ex = implode($this->formExpression['expression']);
                }
                preg_match_all("/\b{$pregStr}\b/", $ex, $matches);
                return array_values(array_unique(array_filter($matches[0])));
            };

            $res['expression'] = $h($this->formExpression['expression']);
        }

        // 共享识别类表单, 除了上传图片这个字段都需要禁止掉
        if ($res && $this->previewScenario != self::SCENARIO_SHARE_FORM_UNLOCK && $this->formData['group_id'] == FormGroup::NORMAL_OCR && $res['type'] != 'UploadImg') {
            if (SDMHelper::app()->form->getIdentificationEdit($this->formData['id']) == 2) {
                $res['disabled'] = false;
            }elseif (SDMHelper::app()->form->getIdentificationEdit($this->formData['id']) == 1 && SDMHelper::app()->form->getIsShareFormLock($this->formData['id'], $this->getRequestParams('patient_id', 0), $this->getRequestParams('checktime_id', 0))) { // 只有锁定了, 这个控制才会生效
                $res['disabled'] = false;
            } else {
                $res['disabled'] = true;
            }
        }

        if ($this->previewScenario === self::SCENARIO_CM_LIST_VIEW) {
            if ($res['var_name'] !== DictionaryVarNameEnum::COLLECT_MEDICAL_TAKE_CMINDC) {
                $res['disabled'] = true;
            } else {
                $res['is_select_change'] = true;
            }
        }

        // 给合并用药设置默认值
        if ($this->formData['var_name'] === 'CM' && $defaultVal = $this->getRequestParams('form_default')) {

            $varMap = ['CMDOS' => 2, 'CMD' => 4, 'CMROU' => 3, 'CMINDC100' => 6];
            $allMedicalTake = Laminas::$serviceManager->collectMedicaltake->fetchAll([
                'where' => ['take_type' => array_values($varMap)]
            ]);

            $medicalTakeEnglishMap = ArrayHelper::index($allMedicalTake, null, [function ($element) {
                return $element['take_type'];
            }, 'english']);

            $medicalTakeMap = ArrayHelper::index($allMedicalTake, null, [function ($element) {
                return $element['take_type'];
            }, 'name']);
            
            $defaultVal = StringHelper::jsonDecode($defaultVal);
            if (isset($defaultVal[$res['var_name']])) {
                $labelValue = SDMHelper::app()->form->field->getLabelValue(DataHelper::getFieldId($res['prop']), $defaultVal[$res['var_name']]);
                if ($labelValue) {
                    $res['default'] = $labelValue;
                } elseif ($varMap[$res['var_name']] == 6 && $res['var_name'] == 'CMINDC100') {
                    $def = '';
                    if(isset($medicalTakeEnglishMap[$varMap[$res['var_name']]][$defaultVal[$res['var_name']]])){
                        $def = current($medicalTakeEnglishMap[$varMap[$res['var_name']]][$defaultVal[$res['var_name']]])['id'];
                    }
                    $res['default'] = $def;
                } elseif (isset($medicalTakeMap[$varMap[$res['var_name']]][$defaultVal[$res['var_name']]])) {
                    $def = '';
                    $currentMedicalTypeValue = current($medicalTakeMap[$varMap[$res['var_name']]][$defaultVal[$res['var_name']]])['id'];
                    $query = Laminas::$serviceManager->itemFormField->fetchOne([
                        'where' => ['form_id' => $this->formData['id'], new Like('medical_type', "%{$currentMedicalTypeValue}%"), 'id' => array_keys($this->versionData[DataHelper::getFieldId($res['prop'])]['children'])]
                    ]);

                    if ($query) {
                        $def = $this->versionData[DataHelper::getFieldId($res['prop'])]['children'][$query['id']]['value'] ?? '';
                    }
                    $res['default'] = $def;
                }
            }
        }

        $this->setNote($res);
        // 为类型为 `文本` 加上默认值

        // 在常规识别界面中, 如果锁定了并且没提出质疑的字段 要给禁止掉。防止回复质疑的时候把其他的字段也给改了
        if ($res && $this->previewScenario == self::SCENARIO_SHARE_FORM_UNLOCK && !isset($res['is_logic_error']) && SDMHelper::app()->form->getIsShareFormLock($this->formData['id'], $this->getRequestParams('patient_id', 0), $this->getRequestParams('checktime_id', 0))) {
            $res['disabled'] = true;
        }
        return $res;
    }

    /**
     * @param array $res 返回结果
     */
    private function setNote(array &$res)
    {
        $field = $res['prop'];
        $pid = $this->getRequestParams('patient_id') ?: 0;
        $g = new Pointer();
        if ($this->previewScenario === self::SCENARIO_SHARE_FORM_UNLOCK) {

            // 进度管理场景
//            $g = new Pointer();
            $g->setPatientId($pid);
            $condition = [
                'patient_id' => $pid,
                'form_id' => $this->formData['id']
//                'is_del' => 0 // 关闭的也展示
            ];

//            if ($isProcess === false && $_POST['checktime_id']) {
//                $condition[] = new \Laminas\Db\Sql\Predicate\Expression("FIND_IN_SET('{$_POST['checktime_id']}',checktime_id)");
//            }

            if (!$err = Laminas::$serviceManager->itemPatientFormLogicErrorPointer->memoryCache()->fetchAll([
                'order' => ['id DESC'],
                'where' => $condition
            ])) {
                return $res;
            }

            $error = Laminas::$serviceManager->itemPatientFormLogicError->memoryCache()->fetchAll([
                'order' => ['id DESC'],
                'where' => ['id' => ArrayHelper::getColumn($err, 'error_id'), 'patient_id' => $pid, 'is_report_special' => 1]
            ]);
            if (!$error) {
                return $res;
            }

            $g->setErrorId(ArrayHelper::getColumn($error, 'id'));

            if ($_POST['content_id'] && $_POST['content_id'] !== 'undefined') {
                $g->setMultiId($_POST['content_id']);
            }

            if ($_POST['checktime_id'] && $_POST['checktime_id'] !== 'undefined') {
                $g->setCheckTimeId($_POST['checktime_id']);
            }

            $usingField = $g->getUsingField();
            if ($this->formData['type'] == self::FORM_TYPE_MULTI && (!$_POST['content_id'] || !isset($_POST['content_id']))) {
                $usingField = [];
            }
            if (isset($usingField) && (in_array($field, $usingField) !== false || in_array($field.'-normal_type', $usingField) !== false || in_array(DataHelper::getFieldId($res['prop']), $usingField) !== false || in_array(DataHelper::getFieldId($res['prop'].'-normal_type'), $usingField) !== false)) {
                // 关闭的质疑不展示
                $res['is_logic_error'] = true;
                $res['logic_error_message'] = $res['normal_type_logic_error_message'] = [];
                if(in_array($field, $usingField) !== false || in_array(DataHelper::getFieldId($res['prop']), $usingField) !== false){
                    $res['logic_error_message'] = $g->getFieldError($field);
                }
                if(in_array($field.'-normal_type', $usingField) !== false || in_array(DataHelper::getFieldId($res['prop'].'-normal_type'), $usingField) !== false){
                    $res['normal_type_logic_error_message'] = $g->getFieldError($field.'-normal_type') ?: [];
                }
                $res['error_id'] = $g->errorId;

                return $res;
            }
        } elseif ($this->previewScenario === self::SCENARIO_PREVIEW_LOGIC_CHECK) {// 逻辑核查
                $g = new Pointer();
            //$_POST['error_id'] 是主表单的质疑ID 其他的表单需要查询最新的质疑ID去显示
            //根据条件查询一下 error_id
            $logic_query = Laminas::$serviceManager->itemPatientFormLogic->fetchOne([
                'where' => ['expression_hash' => $_POST['expression_id']]
            ]);
            if(!empty($logic_query)){
                //逻辑核查质疑单独处理一下
                $oldError_where = $error_infos = [];
                //逻辑核查公式质疑
                $generator = unserialize($logic_query['generator']);
                $allusings = $generator->allusings;
                $g->setErrorId(array($_POST['error_id']));
                if(!empty($allusings)){
                    foreach ($allusings as $using){
                        $new_using = explode('_',$using);
                        $oldError_where[PredicateSet::OP_OR][] = [
                            [
                                'checktime_id' => $new_using[0],
                                'form_id' => $new_using[1],
                                'prop' => $new_using[2],
                            ]
                        ];
                    }
                    $oldErrorDatas = Laminas::$serviceManager->itemPatientFormLogicErrorPointer->fetchAll([
                        'where'=> [
                            'is_del' => 0,
                            'error_type' => 0,
                            'item_id' => $_POST['item_id'],
                            'patient_id' => $_POST['patient_id'],
                            $oldError_where,
                        ],
                        'columns'=>['id','error_id','checktime_id','form_id','item_id','multi_id','patient_id'],
                        'order' => ['id desc']
                    ]);
                    if(!empty($oldErrorDatas)){
                        foreach ($oldErrorDatas as $oldErrorKey=>$oldErrorData){
                            $error_key = $oldErrorData['item_id'].'_'.$oldErrorData['checktime_id'].'_'.$oldErrorData['form_id'].'_'.$oldErrorData['patient_id'].'_'.$oldErrorData['multi_id'];
                            $error_keys[$oldErrorData['error_id']] = $error_key;
                            $error_infos[$error_key][] = $oldErrorData['error_id'];
                        }
                    }

                    $current_key = $_POST['item_id'].'_'.$_POST['checktime_id'].'_'.$_POST['id'].'_'.$_POST['patient_id'].'_'.$_POST['content_id'];

                    //根据传过来的error_id 查询对应的信息 主要为了区分开主表单的error_id 主表单要显示当前状态的质疑信息 其他涉及的表单只显示最新的质疑信息情况
                    $current_info =  isset($error_keys[$_POST['error_id']]) && !empty($error_keys[$_POST['error_id']]) ? $error_keys[$_POST['error_id']] : '';
                    if($current_key <> $current_info){
                        $error_ids = isset($error_infos[$current_key]) && !empty($error_infos[$current_key]) ? $error_infos[$current_key] : [];
                        $_POST['error_id'] = end($error_ids);   //非主表单的话  多条质疑信息只取最新的
                    }
                }
            }
                $g->setErrorId(array($_POST['error_id']));
                $g->setPatientId($pid);

                $usingField = $g->getUsingField();

                if (isset($usingField) && $usingField && (in_array($field, $usingField) !== false || in_array($field.'-normal_type', $usingField) !== false)) {
                    $res['is_logic_error'] = true;
                    $res['logic_error_message'] = $res['normal_type_logic_error_message'] = [];
                    if(in_array($field, $usingField) !== false){
                        $res['logic_error_message'] = $g->getFieldError($field);
                    }
                    if(in_array($field.'-normal_type', $usingField) !== false){
                        $res['normal_type_logic_error_message'] = $g->getFieldError($field.'-normal_type') ?: [];
                    }
                    $res['can_reply'] = $g->canReply;
                    $res['error_id'] = intval($_POST['error_id']);
                    $res['is_report_special'] = $res['is_report_special'] ?: (bool)(Laminas::$serviceManager->itemPatientFormLogicError->fetchOne(['where' => ['id' => $_POST['error_id']]])['is_report_special'] ?? 0);
                    // 质疑详情ocr模板设置

                    return $res;
                }
        } elseif ($this->previewScenario === self::SCENARIO_PREVIEW_USING_SCORE) { // 评分功能
            $isAdmin = $this->getIsUsingScoreAdmin();
            if ($isAdmin == false) {
                return;
            }

            $usingScoreUser = $this->getUsingScoreUser();
            $formData = $this->getContentData([
                'create_user_id' => $usingScoreUser,
                'form_id' => $this->formData['id'],
                'patient_id' => $this->getRequestParams('patient_id'),
                'checktime_id' => $this->getRequestParams('checktime_id')
            ]);

            $r = [];
            foreach ($formData as $v) {
                $val = $v[$res['prop']];
                $createUser = $v['create_user_name'];
                $dataVal = $val;
                if ($res['type'] == 'Radio') {
                    $children = ArrayHelper::index($this->versionData[$res['prop']]['children'], 'value');
                    $dataVal = ($children[$val]['name'] ?? '');
                    if (isset($children[$val]['is_score']) && $children[$val]['is_score'] == 1) {
                        $fixScore =  $children[$val]['score'];
                        $dataVal .= "[$fixScore(分)]";
                    }
                } else if ($res['type'] == 'Checkbox') {
                    if (is_string($val)) {
                        $ex = explode(',', $val);
                    } else {
                        $ex = $val;
                    }
                    if ($ex) {
                        $dataVal = [];
                    }
                    $children = ArrayHelper::index($this->versionData[$res['prop']]['children'], 'value');
                    foreach ($ex as $item) {
                        $s = ($children[$item]['name'] ?? '');
                        if (isset($children[$item]['is_score']) && $children[$item]['is_score'] == 1) {
                            $fixScore =  $children[$item]['score'];
                            $dataVal[] = ($s . "[$fixScore(分)]");
                        } else {
                            $dataVal[] = $s;
                        }
                    }

                    $dataVal = implode(',  ', $dataVal);
                }
                if ($dataVal) {
                    $r[] = "{$createUser}: {$dataVal}";
                }
            }

            $res['message'] = $r;
        }
    }

    public function getContentData(array $condition = [], $mode = 'preview'): ?array
    {
        if (!$this->contentData) {
            $query = Laminas::$serviceManager->patientFormContent->fetchAll([
                'where' => $condition
            ]);
            $res = [];
            foreach ($query as $item) {
                $data = StringHelper::jsonDecode($item['data']);
                $data['create_user_name'] = SDMHelper::app()->user->getRealName($item['create_user_id']);//(new UserHelper($item['create_user_id']))->getUserName();
                if ($mode == 'view') {
                    unset($data['id']);
                }
                if ($_POST['scenario'] == self::SCENARIO_PREVIEW_USING_SCORE) {
                    $res[] = $data;
                }
            }
            $this->contentData = $res;
        }

        return $this->contentData;
    }

    public function getUsingScoreUser(bool $isAdmin = false): array
    {
        $c = 2;
        if ($isAdmin) {
            $c = 1;
        }
        $itemId = $this->getRequestParams('item_id');

        if ($fid = (Laminas::$serviceManager->itemInfo->fetchOne(['where' => ['id' => $itemId]])['fid'] ?? 0)) {
            $itemId = $fid;
        }

        $query = Laminas::$serviceManager->adminMenu->fetchCol('id', ['is_score' => $c]);

        $id = Laminas::$serviceManager->realRolemodulerelation->fetchCol('role_id', ['module_id' => $query, 'status' => 0, 'item_id' => $itemId]);

        $s = array_unique(Laminas::$serviceManager->roleSignatoryRelation->fetchCol('signatory_user', [
            'role_id' => $id,
            'is_del' => 0,
            'status' => 0,
            'item_sign_id' => $this->getRequestParams('itemsig_id'),
            'item_id' => $itemId
        ]));

        $s = Laminas::$serviceManager->signatoryUser->isShowMaskingField(true)->fetchCol('user_tel', ['id' => $s]);

        return Laminas::$serviceManager->adminUser->fetchCol('id', ['mobile' => $s]);
    }

    public function getIsUsingScoreAdmin(): ?bool
    {
        if ($this->isUsingScoreAdmin === null) {
            if (in_array(Laminas::$serviceManager->identity->getId(), $this->getUsingScoreUser(true))) {
                $this->isUsingScoreAdmin = true;
            } else {
                $this->isUsingScoreAdmin = false;
            }
        }
        return $this->isUsingScoreAdmin;
    }

    private function getRegex($type): string
    {

        switch ($type) {
            case Enum::FORM_FIELD_TYPE_INTEGER:
                return "value=value.replace(/[^\d]/g,'')";
            case Enum::FORM_FIELD_TYPE_FLOAT_1:
                return "value=value.replace(/^\D*(\d*(?:\.\d{0,1})?).*$/g, '$1')";
            case Enum::FORM_FIELD_TYPE_FLOAT_2:
                return "value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')";
            case Enum::FORM_FIELD_TYPE_FLOAT_3:
                return "value=value.replace(/^\D*(\d*(?:\.\d{0,3})?).*$/g, '$1')";
        }

        return '';
    }

    /**
     * @param string $type
     * @return string
     * @throws Exception
     */
    private function _getType(string $type): string
    {
        switch ($type) {
            case Enum::FORM_FIELD_TYPE_INTEGER:
            case Enum::FORM_FIELD_TYPE_FLOAT_1:
            case Enum::FORM_FIELD_TYPE_FLOAT_2:
            case Enum::FORM_FIELD_TYPE_FLOAT_3:
            case Enum::FORM_FIELD_TYPE_TEXT:
                return 'Input';
            case Enum::FORM_FIELD_TYPE_DATE_UK:
                return 'Uk';
            case FormField::FORM_FIELD_TYPE_DATETIME_UK:
                return 'DateTimeUK';
            case FormField::FORM_FIELD_TYPE_DATETIME_SECOND_UK:
                return 'DateTimeSecondUK';
            case FormField::FORM_FIELD_TYPE_DATE_SECOND:
                return 'DateTimeSecond';
            case Enum::FORM_FIELD_TYPE_DATE:
                return 'Date';
            case Enum::FORM_FIELD_TYPE_DATETIME:
                return 'DateTime';
            case Enum::FORM_FIELD_TYPE_RADIO:
                return 'Radio';
            case Enum::FORM_FIELD_TYPE_CHECKBOX:
                return 'Checkbox';
            case Enum::FORM_FIELD_TYPE_UPLOAD_IMAGE:
            case FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE:
                return 'UploadImg';
            case Enum::FORM_FIELD_TYPE_UPLOAD_FILE:
                return 'UploadFile';
            case Enum::FORM_FIELD_TYPE_DROPDOWN:
                return 'Select';
            case Enum::FORM_FIELD_TYPE_EDITOR:
                return 'Editor';
            case FormField::FORM_FIELD_TYPE_TEXTAREA:
                return 'Textarea';
            case FormField::FORM_FIELD_TYPE_LABEL:
                return 'Text';
            case FormField::FORM_FIELD_TYPE_SPAN:
                return 'Span';
            case FormField::FORM_FIELD_TYPE_TIME_UK:
                return 'TimeUK';
            case FormField::FORM_FIELD_TYPE_TIME_SECOND_UK:
                return 'TimeSecondUK';
            case FormField::FORM_FIELD_TYPE_ITEM_FORM_SOURCE:
                return 'SelectTable';
            case FormField::FORM_FIELD_TYPE_REGION_OPTION:
                return 'Cascader';
            default:
                throw new Exception("错误的类型~");
        }
    }

    private function _getRelationForm(array $row)
    {
        $res = [];
        foreach ($row as $child) {
//            var_dump($child);
            foreach ($child['relation_information'] as $information) {
                if ($information) {
                    $res[$child['parent']][$child['value']][] = $information;
                }
            }
        }

        return $res;
    }

    private function _getDefault(array $row)
    {
        if (isset($row['children'])) {
            foreach ($row['children'] as $child) {
                // 0 是没默认值 1 是有默认值
                if (isset($child['is_check']) && $child['is_check'] == '1') {
                    // 多选默认值是数组
                    return $row['type'] == Enum::FORM_FIELD_TYPE_CHECKBOX ? [$child['value']] : $child['value'];
                }
            }
        }

        return null;
    }

    private function _getChild(array &$row)
    {
//        $request = Laminas::$app->getMvcEvent() !== null ? Laminas::$app->getMvcEvent()->getRequest() : null;
        $options = [];
        if (!isset($row['children'])) {
            if (in_array($row['var_name'], ['RANDOM_GROUP_CUSTOM', 'RANGC'])) { // 手写随机分组
                $row['children'] = Laminas::$serviceManager->itemRandom->fetchAll([
                    'columns' => ['random_name as name', 'id as value'],
                    'where' => ['is_del' => 0, 'item_id' => $this->getRequestParams('item_id'), 'type' => 2]
                ]) ?: [];

                foreach ($row['children'] as $k => $item) {
                    $relationFieldId = $item['value'];
                    $row['children'][$k] = ['name' => $item['name'], 'value' => $item['value']];
                    $row['children'][$k]['relation_information'][] = $relationFieldId;
                    $this->_attachField[$row['id']] = $row;
                    $this->_attachFieldVersion[$relationFieldId] = [
                        "id" => $relationFieldId,
                        "name" => $row['showfiled_name'],
                        "order" => "10",
                        "type" => "1",
                        "is_list" => "0",
                        "is_anchor" => "0",
                        "is_booked_time" => "0",
                        "placeholder" => "请输入".$row['showfiled_name'],
                        "tips" => "请输入".$row['showfiled_name'],
                        "form_type" => "TEXT",
                        "code" => $row['showfiled_name'],
                        'var_name' => 'RANDOM_GROUP_CUSTOM_CONTENT'
                    ];
                }
            } elseif (in_array($row['var_name'], ['RANDOM_GROUP_SYSTEM', 'RANGCA'])) { // 系统分配随机分组
                if ($this->getRequestParams('item_id') && $this->getRequestParams('itemsig_id') && $this->getRequestParams('patient_id')) {
                    $row['children'] = Laminas::$serviceManager->itemRandomdetails->getRandomdetailsNumberPop(
                        $this->getRequestParams('item_id'),
                        $this->getRequestParams('itemsig_id'),
                        $this->getRequestParams('patient_id'),
                    );
                }

                foreach ($row['children'] ?: [] as $k => $item) {
                    $relationFieldId = $item['id'];
                    $row['children'][$k] = ['name' => $item['group_name'], 'value' => $item['id']];
                    $row['children'][$k]['relation_information'][] = $relationFieldId;
                    $row['children'][$k]['var_name'] = '';
                    $row['children'][$k]['is_score'] = '';
                    $this->_attachField[$row['id']] = $row;
                    // 新增则不显示随机号/随机方案,编辑则disabled
                    if(Laminas::$serviceManager->patientFormContent->getOneFieldVal('id', [
                        'form_id' => $this->getRequestParams('id'),
                        'item_id' => $this->getRequestParams('item_id'),
                        'itemsig_id' => $this->getRequestParams('itemsig_id'),
                        'checktime_id' => $this->getRequestParams('checktime_id'),
                        'patient_id' => $this->getRequestParams('patient_id'),
                    ])) {
                        $row['disabled'] = true;
                        $this->_attachFieldVersion[$relationFieldId] = [
                            "id" => $relationFieldId,
                            "name" => $row['showfiled_name'],
                            "order" => "10",
                            "type" => "12",
                            "is_list" => "0",
                            "is_anchor" => "0",
                            "is_booked_time" => "0",
                            "placeholder" => "请输入".$row['showfiled_name'],
                            "tips" => "请输入".$row['showfiled_name'],
                            "form_type" => "TEXT",
                            "code" => $row['showfiled_name'],
                            'children' => [
                                [
                                    'name' => $this->getMedicalName($item),
                                    'value' => $item['rand_number']['id'],
                                    'is_score' => 0,
                                    'var_name' => ''
                                ]
                            ],
                            'var_name' => 'RANDOM_GROUP_SYSTEM_CONTENT',
                            'random' => $item,
                            'disabled' => true,
                        ];
                    }
                }
            } elseif ($row['var_name'] == DictionaryVarNameEnum::COLLECT_MEDICAL_TAKE_CMINDC) { // 用药原因【获取字典项设置信息】
                $row['children'] = Laminas::$serviceManager->collectMedicaltake->fetchAll([
                    'columns' => ['id', 'name', 'english'],
                    'order' => ['take_order'],
                    'where' => [
                        'is_del' => 0,
                        'take_type' => 6
                    ]
                ]);
                if ($this->previewScenario == self::SCENARIO_CM_LIST_VIEW) {
                    $row['children'][] = ['id' => '2', 'name' => '属于已有AE', 'english' => 'is_already_have_ae', 'is_cmindc' => true];
                    $row['children'][] = ['id' => '1', 'name' => '属于新增AE', 'english' => 'is_new_ae', 'is_cmindc' => true];
                }

                foreach ($row['children'] ?: [] as $k => $item) {
                    $row['children'][$k] = ['id' => $item['id'], 'name' => $item['name'], 'value' => $item['id'], 'var_name' => $item['english'], 'is_cmindc' => true];
                }
            }
        }

        $index = 0;
        foreach ($row['children'] ?? [] as $item) {
            // 必须要有label
            if (!$item['name']) {
                continue;
            }

            if (isset($item['is_score']) && $item['is_score'] == 1) {
                $options[$index] = [
                    'label' => $item['name'],
                    'value' => $item['value'],
                    'score' => floatval($item['score']), // 兼容非整数分值
                    'is_score' => true,
                    'id' => intval($item['id']),
                    'var_name' => $item['id']
                ];
            } elseif (isset($item['is_cmindc']) && $item['is_cmindc'] === true) {
                $options[$index] = ['label' => $item['name'], 'value' => $item['value'],  'is_score' => false, 'score' => 0, 'id' => intval($item['id']), 'var_name' => $item['var_name']];
            } else {
                $options[$index] = ['label' => $item['name'], 'value' => $item['value'],  'is_score' => false, 'score' => 0, 'id' => intval($item['id']), 'var_name' => $item['id']];
            }

            // 不检查需要提示一下
            // 【新系统】不检查时，提示：请填写备注说明。（注：只是提示而已，不做实际控制性功能，不填时表单也可正常提交）--美
            // https://e.gitee.com/yikeen_project/issues/table?issue=I6MYDV
            if (isset($item['var_name']) && $item['var_name'] == 'NC') {
                $options[$index]['is_dialog'] = true;
            }

            $index++;
        }

        return [$this->_getChildKey($row['type']), $options];
    }

    private function getMedicalName($item): string
    {

        $res = '';
        $show = false;

        // 如果没有后缀内容, 并且随机号内包含`/`
        if (strpos($item['rand_number']['randomdetails_name'], '/')){
            // 输出内容为 用字符串`/`切割后的第一个索引
            $randomCode = explode('/', $item['rand_number']['randomdetails_name'])[0];
        } else {
            // 输出内容为随机号
            $randomCode = $item['rand_number']['randomdetails_name'];
        }

        if ($item['rand_number']['itemBlindMethod'] == 1) {
            return $randomCode;
        } else {
            if ($item['rand_number']['itemBlindMethod'] == 0 && $item['rand_number']['medicationFlag'] == 1) {
                // 后缀内容: 如果药物分组名称不是空字符串 就展示(药物分组名称) 否则展示空值
                $res = $item['rand_number']['medicationName'] ? "({$item['rand_number']['medicationName']})" : '';
                $show = true;
            }
        }

        // 如果有后缀内容
        if ($show === true) {
            // 输出随机号 + 后缀内容
            $res = $item['rand_number']['randomdetails_name'] . $res;
        } else {
            $res = $item['rand_number']['randomdetails_name'];
        }

        return $res;
    }

    /**
     * @throws Exception
     */
    private function _getChildKey($type)
    {
        switch ($type) {
            case Enum::FORM_FIELD_TYPE_RADIO:
                return 'radios';
            case Enum::FORM_FIELD_TYPE_CHECKBOX:
                return 'checkboxs';
            case FormField::FORM_FIELD_TYPE_DROPDOWN:
                return 'options';
            case FormField::FORM_FIELD_TYPE_REGION_OPTION:
                return 'cascaderOptions';
            default:
                throw new Exception("错误的类型~");
        }
    }

    private function getAEResultString()
    {
        // 进度管理
        if (SDMHelper::app()->form->getIsCMINDCForm($this->formData['id']) === true) {
            $cmId = SDMHelper::app()->form->getCMINDCId($this->formData['id']);
            $isOther = $isAE = false;
            $appendData = [];
            $cmInfo = Laminas::$serviceManager->patientFormContentCm->fetchOne([
                'where' => ['content_id' => $this->getRequestParams('content_id')]
            ]);

            $status = $cmInfo['cmindc_status'] ?? false;

            if (!$status) {
                $status = '暂无';
            }

            if ($status == 1) {
                $isAE = true;
                $status = '属于新增AE';
            } elseif ($status == 2) {
                $isAE = true;
                $status = '属于已有AE';
            } elseif ($medicalTake = Laminas::$serviceManager->collectMedicaltake->fetchOne(['where' => ['id' => $status]])) {
                if ($medicalTake['english'] == 'CMINDC4') {
                    $isOther = true;
                }
                $status = $medicalTake['name'];
            }

            if ($isAE) {
                // 新增AE 是关联到数据条上的。
                // 属于已有AE 是关联到受试者上的。
                $condition = $cmInfo['cmindc_status'] == 1 ? [
                    'table' => 'itemCsaeRelation',
                    'condition' => [
                        'cm_content_id' => $this->getRequestParams('content_id'),
                        'is_del' => 0
                    ]
                ] : [
                    'table' => 'itemCsaeChecked',
                    'condition' => [
                        'cm_content_id' => $this->getRequestParams('content_id'),
                        'is_del' => 0
                    ]
                ];
                $AEContentId = ArrayHelper::getColumn(Laminas::$serviceManager->{$condition['table']}->fetchAll([
                    'where' => $condition['condition']
                ]), 'content_id');

                if ($AEContentId) {
                    $query = Laminas::$serviceManager->itemPatientAeContent->fetchAll([
                        'where' => ['id' => $AEContentId, 'is_del' => 0]
                    ]);
                    $itemId = SDMHelper::app()->form->getItemId($this->formData['id']);
                    $version = ArrayHelper::index(SDMHelper::app()->form->getVersionData(SDMHelper::app()->form->getAeForm($itemId)['id']), 'var_name');
                    $AENameFieldId = $version['AETERM']['id'] ?? '';
                    foreach ($query as $item) {
                        $data = StringHelper::jsonDecode($item['data']);
                        foreach ($data as $k => $v) {
                            if ($k == $AENameFieldId || stripos($k, $AENameFieldId) !== false) {
                                $appendData[] = "[$status] (不良事件名称: $v)";
                            }
                        }
                    }
                }
            } elseif ($isOther) {
                $appendData[] = "[$status] (备注: {$cmInfo['note']})";
            }

            return $appendData;
        }
    }

    public function pregLabel($pregFieldId)
    {
        $container = $this->LocalService()->itemFormField->fieldResultDataContainer;
        $children = ArrayHelper::index($this->versionData[$pregFieldId]['children'] ?? [], 'name');
        $defaultFieldId = SDMHelper::app()->form->field->getDefaultFieldId($pregFieldId);
        $defaultChecktimeFieldId = SDMHelper::app()->form->field->getDefaultChecktimeFieldId($pregFieldId);
        foreach ($container[$defaultFieldId] ?? [] as  $item) {
            if($pregFieldId == $this->versionData[$pregFieldId]['id'] && ($item['checktime_id'] == $defaultChecktimeFieldId || $defaultChecktimeFieldId == 0)){
                return $item['result'];
            }else{
                foreach ($children as $key => $child) {
                    if (stripos($key, $item['result']) !== false) {
                        return $child['value'];
                    }
                }
            }
        }
    }
}
