<?php

namespace Application\Controller\item\patient;


use Application\Common\EventEnumV2;
use Application\Common\StatusCode;
use Application\Form\item\patient\ImportForm;
use Application\Form\item\patient\PatientFormModel;
use Application\Mvc\Controller\BasicController;
use Application\Service\DB\Db;
use Application\Service\DB\Dictionary\Form;
use Application\Service\DB\Dictionary\FormField;
use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\DB\Item\PatientFormContent;
use Application\Service\DB\Item\PatientFormContentImg;
use Application\Service\DB\Item\PatientFormUnlock;
use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\DataHelper;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Params\Params;
use Application\Service\Extension\Params\ParamSet;
use Application\Service\Extension\Store\Store;
use Application\Service\Extension\Uploader\adapter\Oss;
use Application\Service\Logs;
use Exception;
use Laminas\Db\Sql\Where;
use Laminas\View\Model\JsonModel;

class FormController extends BasicController
{

    private function addLog($eventId)
    {
        if (!is_int($eventId)) {
            $eventId = $this->validator->attributes['id'];
            $remark = '编辑受试者表单内容';
            $operate = Logs::OPERATE_EDIT;
        } else {
            $operate = Logs::OPERATE_CREATE;
            $remark = '添加受试者表单内容';
        }

        $formId = $this->params()->fromPost('form_id');
        $this->LocalService()->log->setSaveEventForm('PatientForm')->setFormId($formId)->saveFileLog(
            $eventId,
            $this->LocalService()->itemFormVersion->getField(['form_id' => $formId], true),
            $this->validator->attributes,
            $operate,
            $remark,
            $this->validator->attributes['item_id']
        );
    }

    /**
     * 添加/编辑受试者数据
     * @actionUrl /patient/form/create
     * @analysis REQUEST_TIMES,RESPONSE_TIME[max=500]
     * @return JsonModel
     * @throws Exception
     */
    public function createAction(): JsonModel
    {
        $id = $this->params()->fromPost('id');
        if($id === 'undefined') {
            $id = 0;
            $this->validator->attributes['id'] = $id;
        }
        $this->validator->attach(
            [['patient_id', 'form_id', 'item_id', 'checktime_id', 'itemsig_id'], 'required'],
            [['patient_id', 'form_id', 'item_id', 'checktime_id', 'itemsig_id'], 'integer'],
            [[Form::ATTACH_SDTX], 'default', 'value' => '[]']
        );

        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }
        $reason = $this->params()->fromPost('reason');
        if(!empty($reason)){
            $reason_res = [];
            $reason_datas = json_decode($reason,true);
            foreach ($reason_datas as $reason_data){
                $reason_res[] = [
                    'filed_id'=>$reason_data['filed_id'],
                    'modify_reason'=>$reason_data['modify_reason'],
                ];
            }
            unset($reason_datas);
            $reason = json_encode($reason_res,true);
        }
        $this->validator->attributes['note'] = $reason;
        unset($this->validator->attributes['reason']);
        $model = new PatientFormModel($this->validator);

        $postData = DataHelper::handleFormData($this->validator->attributes, $this->params()->fromPost('form_id'));

        if (SDMHelper::app()->setAttributes(['form_id' => $this->params()->fromPost('form_id')])->form->getIsUsingScore() == 1) {
            throw new InvalidArgumentException('评分类表单不允许操作。');
        }

        if ($this->validator->attributes['id']) {
            $model->editForm($postData);
            // 异步处理工作信息
            $this->LocalService()->swTaskClient->send([
                'svName' => 'projectPatientwork',
                'methodName' => 'updatePatientworkData',
                'params' => [
                    'item_id' => $this->validator->attributes['item_id'],
                    'itemsig_id' => $this->validator->attributes['itemsig_id'],
                    'patient_id' => $this->validator->attributes['patient_id'],
                    'checktime_id' => $this->validator->attributes['checktime_id'],
                    'form_id' => $this->validator->attributes['form_id'],
                    'user_id' => $this->LocalService()->identity->getId(),
                    'content_id' => $this->validator->attributes['id']
                ]
            ]);
        } else {
            $insertId = $model->createForm($postData);

            // 异步处理工作信息
            $this->LocalService()->swTaskClient->send([
                'svName' => 'projectPatientwork',
                'methodName' => 'updatePatientworkData',
                'params' => [
                    'item_id' => $this->validator->attributes['item_id'],
                    'itemsig_id' => $this->validator->attributes['itemsig_id'],
                    'patient_id' => $this->validator->attributes['patient_id'],
                    'checktime_id' => $this->validator->attributes['checktime_id'],
                    'form_id' => $this->validator->attributes['form_id'],
                    'user_id' => $this->LocalService()->identity->getId(),
                    'content_id' => $insertId
                ]
            ]);
            return $this->RenderApiJson()->Success([
                'id' => $insertId
            ]);
        }

        return $this->RenderApiJson()->Success();
    }

    /**
     * 通过表单质疑修改表单数据
     * @actionUrl /patient/form/cover-by-question-reply
     * @analysis REQUEST_TIMES,RESPONSE_TIME[max=500]
     * @return JsonModel
     * @throws Exception
     */
    public function coverByQuestionReplyAction(): JsonModel
    {

        $model = new PatientFormModel($this->validator);

        $postData = DataHelper::handleFormData($this->validator->attributes, $this->params()->fromPost('form_id'));
        $model->setEvent(EventEnumV2::getVal(EventEnumV2::EVENT_FORM_CONTENT_EDIT_BY_LOGIC_REPLY))->editForm($postData);

        //锁定后自动添加异常值判断数据
        $postData['patientformcontent_id'] = $postData['id'];

        $changeResultWhere = [
            'is_del' => 0,
            'patient_id' => $this->params()->fromPost('patient_id', 0),
            'checktime_id' => $this->params()->fromPost('checktime_id', 0),
            'form_id' => $this->params()->fromPost('form_id', 0),
        ];
        if(!empty($postData['patientformcontent_id'])){
            $changeResultWhere['patientformcontent_id'] = $postData['patientformcontent_id'];
        }
        $changResultDatas = Laminas::$serviceManager->itemIdentificationresultchange->fetchAll([
            'where'=>$changeResultWhere,
            'columns'=>['id','is_normal_type','patientformcontent_id','item_checkname_id','result']
        ]);
        unset($changeResultWhere);
        if(empty($changResultDatas)){
            $send_formcs_data = [
                'item_id'=>$this->params()->fromPost('item_id'),
                'itemsig_id'=>$this->params()->fromPost('itemsig_id'),
                'patient_id'=>$this->params()->fromPost('patient_id'),
                'checktime_id'=>$this->params()->fromPost('checktime_id'),
                'patientchecktime_id'=>0,
                'form_data'=>[$postData['form_id'] => [
                    'content_data' => $postData]
                ]
            ];

            Laminas::$serviceManager->itemIdentificationresultchange->saveFormCs($send_formcs_data);
        }

        if(isset($postData['childData']) && !empty($postData['childData'])){
            $this->LocalService()->itemIdentificationresultchange->changeNormalType($postData);
        }

        //异步处理访视进度情况信息
        
        $form_content_arr = !empty($postData['patientformcontent_id']) ? [$postData['patientformcontent_id']] : [];
        Laminas::$serviceManager->swTaskClient->send([
            'svName' => 'projectPatientworkbatch',
            'methodName' => 'multipleUpdateData',
            'params' => [
                'item_id' => $this->params()->fromPost('item_id'),
                'itemsig_id' => $this->params()->fromPost('itemsig_id'),
                'patient_id' => $this->params()->fromPost('patient_id'),
                'checktime_id' => $this->params()->fromPost('checktime_id'),
                'form_id' => $this->params()->fromPost('form_id'),
                'operate_type'=>11,
                'content_id'=>!empty($form_content_arr) ? $form_content_arr : [],
                'user_id' => Laminas::$serviceManager->identity->getId()
            ]
        ]);
        unset($form_content_arr);
        return $this->RenderApiJson()->Success();
    }


    /**
     * 回显表单数据
     * @actionUrl  /patient/form/view
     * @analysis REQUEST_TIMES,RESPONSE_TIME[max=200]
     * @return JsonModel
     * @throws Exception
     */
    public function viewAction(): JsonModel
    {
        $this->validator->attach(
            [['patient_id', 'form_id', 'checktime_id'], 'required']
        );
        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        $model = new PatientFormModel($this->validator);

        $data = $model->setDataHaveDel(true)->view();

        if ($data) {
            $aeResults = Laminas::$serviceManager->itemCsae->fetchCheckFieldAeData([
                'item_id'=>$this->validator->attributes['item_id'],
                'itemsig_id'=>[$this->validator->attributes['itemsig_id']],
                'patient_id'=>[$this->validator->attributes['patient_id']],
                'form_id'=>[$this->validator->attributes['form_id']],
                'type'=>1
            ]);
            if(SDMHelper::app()->form->getType($this->validator->attributes['form_id']) == Form::FORM_TYPE_SINGLE){
                $data['childData'] = isset($data['childData']) && !empty($data['childData']) ? json_decode($data['childData'],true) : [];
                if(!empty($data['childData'])){
                    $aeResultArr = isset($aeResults[$data['id']]) && !empty($aeResults[$data['id']]) ? $aeResults[$data['id']] : [];

                    /************有质疑可以编辑异常值判断***********/
                    $childerrorDatas = [];
                    if($data['id']){
                        $childerror = $this->LocalService()->itemPatientFormLogicErrorPointer->fetchAll([
                            'where'=>"multi_id = ".$data['id'],
                            'columns'=>['error_id','prop']
                        ]);
                        $childerrorDatas = ArrayHelper::index($childerror,'prop');
                    }

                    /************有质疑可以编辑异常值判断***********/

                    foreach($data['childData'] as $data_judge_key=>$data_judge){
                        $data_judge_field = isset($data_judge['field_id']) && !empty($data_judge['field_id']) ? $data_judge['field_id'] : 0;
                        if(empty($data_judge_field) && strpos($data_judge_key, "-") === false){
                            $data_judge_field = $data_judge_key;
                        }
                        $data['childData'][$data_judge_key]['field_id'] = $data_judge_field;
                        $data['childData'][$data_judge_key]['normal_type'] = !empty($data_judge['normal_type']) ? $data_judge['normal_type'] : '';
                        $data['childData'][$data_judge_key]['parentProp'] = $data_judge_key;
                        $data['childData'][$data_judge_key]['aeResultList'] = [];
                        if($data_judge['normal_type'] == 2){
                            $data['childData'][$data_judge_key]['aeResultList'] = isset($aeResultArr[$data_judge_field]) && isset($aeResultArr[$data_judge_field]['show_ae']) && !empty($aeResultArr[$data_judge_field]['show_ae']) ? $aeResultArr[$data_judge_field]['show_ae'] : [];
                        }

                        if(!empty($childerrorDatas) && (isset($childerrorDatas[$data_judge_key]) || isset($childerrorDatas[$data_judge_key.'-normal_type']))){
                            if($model->scenario === 'progressManage'){
                                $data['childData'][$data_judge_key]['disabled'] = true;
                            }else{
                                $index_id = isset($childerrorDatas[$data_judge_key.'-normal_type']['error_id']) ? $childerrorDatas[$data_judge_key.'-normal_type']['error_id'] : 0;
                                $errorResult = $this->LocalService()->itemPatientFormLogicError->getOneFieldVal('id',"is_closed = 0 and id =".$index_id);
                                $data['childData'][$data_judge_key]['disabled'] = $errorResult  ? false : true;
                            }

                        }else{
                            if($model->scenario === 'progressManage'){
                                $data['childData'][$data_judge_key]['disabled'] = true;
                            }else{
                                $contentLockState = 0;
                                if(!empty($data['id'])){
                                    $contentLockState = $this->LocalService()->patientFormContent->getOneFieldVal('is_lock',"id = ".$data['id']);
                                }
                                $data['childData'][$data_judge_key]['disabled'] = !empty($contentLockState) ? true : false;
                            }

                        }
                        unset($data_judge_field);

                    }
                    unset($aeResultArr);
                }
            }else{
                //获取该表单锁定状态
                $contentLockState = $this->LocalService()->patientFormContent->getOneFieldVal('is_lock',"is_del = 0 and patient_id = ".$this->validator->attributes['patient_id'].' and checktime_id = '.$this->validator->attributes['checktime_id'].' and form_id = '.$this->validator->attributes['form_id']);
                foreach($data as &$dataInfo){
                    //获取 patientFormContent 表的ID
                    $patient_formcontent_id = 0;
                    if(!empty($contentLockState)){
                        if(isset($dataInfo['id']) && !empty(isset($dataInfo['id']))){
                            $patient_formcontent_id = $dataInfo['id'];
                        }
                    }else{
                        if(isset($dataInfo['content_id']) && !empty($dataInfo['content_id'])){
                            $patient_formcontent_id = $dataInfo['content_id'];
                        }
                    }
                    $aeResultArr = isset($aeResults[$patient_formcontent_id]) && !empty($aeResults[$patient_formcontent_id]) ? $aeResults[$patient_formcontent_id] : [];
                    $dataInfo['patientformcontent_id'] = $patient_formcontent_id;
                    //===========判断是否存在未关闭的质疑===============
                    $formerrorCount = 0;
                    if(!empty($patient_formcontent_id)){
                        $formerrorCount = $this->LocalService()->itemPatientFormLogicError->getCount([
                            'is_del' => 0,
                            'is_closed' => 0,
                            'is_report_special' => 1,
                            'multi_id' => $patient_formcontent_id,
                        ]);
                    }
                    $dataInfo['is_have_error'] = 0;
                    if(!empty($formerrorCount)){
                        $dataInfo['is_have_error'] = 1;
                    }
                    unset($formerrorCount);

                    $dataInfo['childData'] = isset($dataInfo['childData']) && !empty($dataInfo['childData']) ? json_decode($dataInfo['childData'],true) : [];
                    if(!empty($dataInfo['childData'])){
                        //===========有质疑可以编辑异常值判断===============
                        $childerrorDatas = [];
                        if(!empty($patient_formcontent_id)){
                            $childerror = $this->LocalService()->itemPatientFormLogicErrorPointer->fetchAll([
                                'where'=>"multi_id = ".$patient_formcontent_id,
                                'columns'=>['error_id','prop']
                            ]);
                            $childerrorDatas = ArrayHelper::index($childerror,'prop');
                        }
                        //===========*有质疑可以编辑异常值判断===============

                        foreach($dataInfo['childData'] as $data_judge_key=>$data_judge){
                            $data_judge_field = isset($data_judge['field_id']) && !empty($data_judge['field_id']) ? $data_judge['field_id'] : 0;

                            if(empty($data_judge_field) && strpos($data_judge_key, "-") === false){
                                $data_judge_field = $data_judge_key;
                            }
                            $dataInfo['childData'][$data_judge_key]['field_id'] = $data_judge_field;
                            $dataInfo['childData'][$data_judge_key]['normal_type'] = !empty($data_judge['normal_type']) ? $data_judge['normal_type'] : '';
                            $dataInfo['childData'][$data_judge_key]['parentProp'] = $data_judge_key;
                            $dataInfo['childData'][$data_judge_key]['aeResultList'] = [];
                            $dataInfo['childData'][$data_judge_key]['disabled'] = false;
                            if($data_judge['normal_type'] == 2){
                                $dataInfo['childData'][$data_judge_key]['aeResultList'] = isset($aeResultArr[$data_judge_field]) && isset($aeResultArr[$data_judge_field]['show_ae']) && !empty($aeResultArr[$data_judge_field]['show_ae']) ? $aeResultArr[$data_judge_field]['show_ae'] : [];
                            }

                            if(!empty($childerrorDatas) && (isset($childerrorDatas[$data_judge_key]) || isset($childerrorDatas[$data_judge_key.'-normal_type']))){
                                if($model->scenario === 'progressManage'){
                                    $dataInfo['childData'][$data_judge_key]['disabled'] = true;
                                }else{
                                    $index_id = isset($childerrorDatas[$data_judge_key.'-normal_type']['error_id']) ? $childerrorDatas[$data_judge_key.'-normal_type']['error_id'] : 0;
                                    $errorResult = $this->LocalService()->itemPatientFormLogicError->getOneFieldVal('id',"is_closed = 0 and id =".$index_id);
                                    $dataInfo['childData'][$data_judge_key]['disabled'] = $errorResult  ? false : true;
                                }

                            }else{
                                if($model->scenario === 'progressManage'){
                                    $dataInfo['childData'][$data_judge_key]['disabled'] = true;
                                }else{
                                    $dataInfo['childData'][$data_judge_key]['disabled'] = !empty($contentLockState) ? true : false;
                                }

                            }
                            unset($data_judge_field);
                        }
                        unset($aeResultArr);
                    }
                    unset($patient_formcontent_id);
                }
                unset($contentLockState);
            }
            unset($aeResults);
        }

        return $this->RenderApiJson()->Success($data, 'OK', [
            'total' => $model->getFormMultiTotalCount(),
            'annexData' => $model->getAnnexData(),
            'report_type' => call_user_func(function () use ($model) {
                $categoryId = $model->getItemFormData()['checklist_id'] ?? false;
                return $model->getReportType($categoryId);
            })
        ]);
    }

    public function importAction(): JsonModel
    {
        set_time_limit(0);
        $model = new ImportForm();
        $model->import($_FILES['file']);
        if ($fail = $model->getErrorMessage()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, implode('<br>', $fail));
        }
        return $this->RenderApiJson()->Success();
    }

    public function importCheckFormAction(): JsonModel
    {
        set_time_limit(0);

//        if(!empty($_POST['item_id']) || !empty($_POST['itemsig_id'])) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '参数有误');

        $model = new ImportForm($_POST['item_id']);
//        $model->importCheckForm($_FILES['file'],$_POST['item_id'],$_POST['itemsig_id']);
        $model->importCheckForm($_FILES['file'],$_POST['item_id'],403);
        if ($fail = $model->getErrorMessage()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, implode('<br>', $fail));
        }
        return $this->RenderApiJson()->Success();
    }

    //错误数据列表
    public function getImportErrorDataAction()
    {
        $model = new ImportForm($_POST['item_id']);
        $page = $_POST['page'] ? : 1;
        list($data,$count) = $model->getErrorDatas($_POST['item_id'],$page);

        $FormFiledData[] = ['label'=>"中心名称",'prop'=>'itemsig_name'];
        $FormFiledData[] = ['label'=>"受试者编号",'prop'=>'patient_number'];
        $FormFiledData[] = ['label'=>"检查点",'prop'=>'checktime_name'];
        $FormFiledData[] = ['label'=>"表单",'prop'=>'form_name'];
        return $this->RenderApiJson()->Success(['data'=>$data,'total'=>$count,'FormFiledData'=>$FormFiledData]);
    }

    //错误数据详情
    public function getImportErrorInfoAction()
    {
        $model = new ImportForm($_POST['item_id']);
        list($data,$header) = $model->geterrorInfo($_POST['item_id'],$_POST['line']);
        $errorHeader['label'] = '错误信息';
        $errorHeader['prop'] = 'error_info';
        return $this->RenderApiJson()->Success(['data'=>$data,'header'=>$header,'line'=>$_POST['line'],'errorHeader'=>$errorHeader]);
    }

    //删除详情
    public function delErrorInfoAction()
    {
        $model = new ImportForm($_POST['item_id']);
        $model->delErrorInfo($_POST['item_id'],$_POST['line']);
        return $this->RenderApiJson()->Success();
    }

    //数据二次提交
    public function importDataSaveAction()
    {
        $model = new ImportForm($_POST['item_id']);

        $model->importDataSave($_POST['item_id'],json_decode($_POST['data'],true),$_POST['line']);

        return $this->RenderApiJson()->Success();
    }

    //数据录入
    public function importDataExecuteAction()
    {
        $keys = Laminas::$serviceManager->redisExtend->getRedisInstance(6)->keys('task:improtExecute:*');

        if(!empty($keys)){
            $pos = strrpos($keys[0], ":");
            $item_id = $pos !== false ? substr($keys[0], $pos + 1) : $keys[0];
            //查看此项目是否有对应的待处理KEY
            $process =  Laminas::$serviceManager->redisExtend->getRedisInstance(6)->hKeys('task:importProcess:'.$item_id);
            //没有待处理的数据，可以执行了
            if(empty($process)){
                $cacheDatas = Laminas::$serviceManager->redisExtend->getRedisInstance(6)->hKeys($keys[0]);
                if(!empty($cacheDatas)){
                    $model = new ImportForm($item_id);
                    $model->importDataExecute($item_id,$cacheDatas[0]);
                }
            }
        }
        return $this->RenderApiJson()->Success();
    }


    //删除redis和文件混存
    public function delCacheAction()
    {
        $item_id = $_POST['item_id'];

        Laminas::$serviceManager->redisExtend->getRedisInstance(6)->del('task:improtExecute:'.$item_id);
        Laminas::$serviceManager->redisExtend->getRedisInstance(6)->del('task:importProcess:'.$item_id);

        $file = APP_PATH.'/data/import'.$item_id.'txt';

        if (file_exists($file)) {
            unlink($file);
        }

        return $this->RenderApiJson()->Success();
    }


    /**
     * 删除一对多表单
     * @actionUrl /patient/form/del
     * @return JsonModel
     * @throws Exception
     */
    public function delAction()
    {
        $this->validator->attach(
            [['id'], 'required'],
            [['id'], 'exist', 'targetClass' => $this->LocalService()->patientFormContent, 'targetAttribute' => ['id']]
        );
        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        $content = Laminas::$serviceManager->patientFormContent->fetchOne([
            'where' => ['id' => $this->validator->attributes['id']]
        ]);
        $this->validator->setAttributes($content);
        $model = new PatientFormModel($this->validator);
        $model->delete();

        return $this->RenderApiJson()->Success();
    }

    /**
     * @note 一对多表单删除数据恢复（单条恢复）
     * @throws Exception
     * @return JsonModel
     */
    public function recoveryAction(): JsonModel
    {
        $this->validator->attach(
            [['id'], 'required'],
            [['id'], 'exist', 'targetClass' => $this->LocalService()->patientFormContent, 'targetAttribute' => ['id']]
        );

        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        (new PatientFormModel($this->validator))->recoveryDelContent();

        return $this->RenderApiJson()->Success();
    }

    /**
     * 重置表单填写内容
     * @actionUrl /patient/form/flush
     * @return JsonModel
     * @throws Exception
     */
    public function flushAction(): JsonModel
    {
        $this->validator->attach(
            [['id', 'item_id'], 'required'],
        );
        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        $model = new PatientFormModel($this->validator);
        $model->flushContent();
        return $this->RenderApiJson()->Success();
    }

    /**
     * @note 识别类表单申请解锁（解锁的类型：图片调整但不解锁识别/图片调整并解锁识别/清空解锁）
     * @return JsonModel
     */
    public function applyunlockAction() : JsonModel
    {
        //受试者访视期表单填写内容ID【yikeen_item_patient_form_content】
        $patientFormContentId = $this->params()->fromPost('patientformcontent_id', 0);
        $patientFormContentId = empty($patientFormContentId) ? 0 : $patientFormContentId;
        if(empty($patientFormContentId)){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR,'参数有误！');
        }

        //受试者访视期表单填写内容信息
        $content = $this->LocalService()->patientFormContent->fetchOne([
            'where'=>['is_del'=>0,'id'=>$patientFormContentId]
        ]);
        if(empty($content)){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR,'信息已不存在！');
        }
        $content_datas = json_decode($content['data'],true);
        $item_id = isset($content_datas['item_id']) && !empty($content_datas['item_id']) ? $content_datas['item_id'] : $content['item_id'];
        $patient_id = isset($content_datas['patient_id']) && !empty($content_datas['patient_id']) ? $content_datas['patient_id'] : $content['patient_id'];
        $checktime_id = isset($content_datas['checktime_id']) && !empty($content_datas['checktime_id']) ? $content_datas['checktime_id'] : $content['checktime_id'];
        $form_id = isset($content_datas['form_id']) && !empty($content_datas['form_id']) ? $content_datas['form_id'] : $content['form_id'];

        //获取表单Group类型
        $formData = $this->LocalService()->itemForm->fetchOne([
            'where'=>['is_del'=>0,'id'=>$form_id],
            'columns'=>['group_id','gco_pool']
        ]);
        $formGcoPool = !empty($formData) ? $formData['gco_pool'] : '';
        $formGroupId = !empty($formData) ? $formData['group_id'] : 0;
        unset($formData);
        if(!in_array($formGroupId,[FormGroup::CHECK_OCR,FormGroup::NORMAL_OCR])){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR,'非识别类表单尚未开放申请解锁功能！');
        }


        $img_field_prop = '';//获取上传识别图片Prop
        $unlock_img = [];//获取上传识别图片信息

        //常规类识别表单共享图片字段 以及 共享图片信息
        if($formGroupId == FormGroup::NORMAL_OCR){
            $img_field_prop = $this->LocalService()->itemFormField->getOneFieldVal('id',['is_del'=>0,'form_id'=>$form_id,'type'=>FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE]);
            if(!empty($img_field_prop)){
                //获取共享表单
                $sharePoolForm[$form_id] = $form_id;
                if($formGcoPool != ''){
                    $sharePoolForm = $this->LocalService()->itemForm->fetchCol('id',['is_del'=>0,'item_id'=>$item_id,'gco_pool'=>$formGcoPool]);
                }
                if(!empty($sharePoolForm)){
                    //获取共享表单下设置的共享图片字段
                    $sharePoolFormField = $this->LocalService()->itemFormField->fetchCol('id',['is_del'=>0,'form_id'=>array_values($sharePoolForm),'type'=>FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE]);
                    if(!empty($sharePoolFormField)){
                        $unlock_img = $this->LocalService()->patientFormContentImg->fetchAll([
                            'where'=>['is_del'=>0,'patient_id'=>$patient_id,'checktime_id'=>$checktime_id,'form_id'=>array_values($sharePoolForm),'field_id'=>array_values($sharePoolFormField)],
                            'columns'=>['name'=>'img_name','url'=>'img_src'],
                            'order' => ['id ASC']
                        ]);
                        if(!empty($unlock_img)){
                            foreach($unlock_img as &$unlock_img_info){
                                $unlock_img_info['url'] = Oss::getUploadDomain().$unlock_img_info['url'];
                            }
                        }
                    }
                    unset($sharePoolFormField);
                }
                unset($sharePoolForm);
            }
        }
        unset($formGcoPool);

        //化验单类表单识别图片字段 以及 识别图片信息
        if($formGroupId == FormGroup::CHECK_OCR){
            //获取化验单上传图片字段
            $img_field_id = $this->LocalService()->itemFormField->getOneFieldVal('id',['is_del'=>0,'form_id'=>$form_id,'var_name'=>'CHECKIMG']);
            if(!empty($img_field_id) && !empty($content_datas)){
                //获取化验单上传图片Prop
                foreach($content_datas as $content_data_key=>$content_data){
                    if(!DataHelper::isField($content_data_key)) {
                        continue;
                    }
                    if(DataHelper::getFieldId($content_data_key) == $img_field_id) {
                        $img_field_prop = $content_data_key;
                    }
                }
                $unlock_img = !empty($img_field_prop) && isset($content_datas[$img_field_prop]) && !empty($content_datas[$img_field_prop]) ? json_decode($content_datas[$img_field_prop],true) : [];
            }
            unset($img_field_id);
        }
        unset($formGroupId);
        if(empty($img_field_prop)){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR,'尚未设置识别图片类型字段！');
        }

        //返回数据信息
        $datas = [
            'item_id'=>$item_id,
            'itemsig_id'=>isset($content_datas['itemsig_id']) && !empty($content_datas['itemsig_id']) ? $content_datas['itemsig_id'] : $content['itemsig_id'],
            'patient_id'=>$patient_id,
            'checktime_id'=>$checktime_id,
            'form_id'=>$form_id,
            'content_id'=>$patientFormContentId,
            'img_field_prop'=>$img_field_prop,
            'unlock_img'=>!empty($unlock_img) ? $unlock_img : []
        ];
        unset($img_field_prop);
        unset($content_datas);
        unset($content);
        unset($item_id);
        unset($patient_id);
        unset($checktime_id);
        unset($form_id);
        unset($unlock_img);

        //表结构信息
        $FormFileData = $this->Introduce('ItemPatientformunlock');
        return $this->RenderApiJson()->success($datas,'',['FormFileData' => array_values($FormFileData)]);
    }

    /**
     * @note 保存识别类表单申请解锁
     * @return JsonModel
     */
    public function saveApplyunlockAction() : JsonModel
    {
        $content_id = $_POST['content_id'] ?: 0;//受试者访视期表单填写内容ID【yikeen_item_patient_form_content】
        $unlock_type = $_POST['unlock_type'] ?: 0;//申请解锁类型
        $unlock_note = $_POST['unlock_note'] ? trim($_POST['unlock_note']) : '';//申请解锁原因
        $img_field_prop = $_POST['img_field_prop'] ?: '';//上传识别图片Prop
        $unlock_img = $_POST['unlock_img'] ? json_decode($_POST['unlock_img'],true) : [];//识别图片
        if(empty($content_id) ) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '参数不正确！');
        if(empty($unlock_type)){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '申请解锁类型不能为空！');
        }
        if($unlock_note == ''){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '申请解锁原因不能为空！');
        }
        if($unlock_type == '2' && empty($unlock_img)){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '识别图片不能为空！');
        }

        //受试者访视期表单填写内容信息
        $content = $this->LocalService()->patientFormContent->fetchOne([
            'where'=>['is_del'=>0,'id'=>$content_id]
        ]);
        if(empty($content)){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR,'申请解锁信息已不存在！');
        }
        unset($content);
        //保存数据赋值
        $this->validator->attributes['note'] = sprintf("%s%s", $unlock_note, $unlock_type ? "【". PatientFormUnlock::APPLY_UNLOCK_TYPE_MAP_TXT[$unlock_type] . "】" : '');

        //释放空间
        unset($unlock_note);
        unset($unlock_type);
        unset($img_field_prop);
        unset($unlock_img);

        //保存申请解锁信息
        $model = new PatientFormModel($this->validator);
        $model->setPostValues($this->validator->attributes);
        $model->unlock();

        //异步处理申请解锁工作信息
        $this->LocalService()->swTaskClient->send([
            'svName' => 'projectPatientwork',
            'methodName' => 'updatePatientworkData',
            'params' => [
                'item_id' => $this->validator->attributes['item_id'],
                'itemsig_id' => $this->validator->attributes['itemsig_id'],
                'patient_id' => $this->validator->attributes['patient_id'],
                'checktime_id' => $this->validator->attributes['checktime_id'],
                'form_id' => $this->validator->attributes['form_id'],
                'user_id' => $this->LocalService()->identity->getId(),
                'content_id' => $content_id,
            ]
        ]);
        unset($content_id);

        return $this->RenderApiJson()->Success();
    }

    /**
     * @note 确认申请解锁【图片调整但不解锁识别】
     * @return JsonModel
     */
    public function confirmApplyunlockAction() : JsonModel
    {
        $content_id = $this->params()->fromPost('content_id', 0);   // 申请解锁的id

        if(empty($content_id) ) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '参数不正确！');
        
        //更新图片调整及申请解锁状态信息
        $this->LocalService()->patientFormUnlock->confirmApplyunlock($content_id);

        return $this->RenderApiJson()->Success();
    }

    /**
     * 化验单锁定
     * 常规识别也用的这个
     * @actionUrl /patient/form/unlock
     * @return JsonModel
     * @throws Exception
     */
    public function unlockAction(): JsonModel
    {
        $this->validator->attach(
            [['content_id'], 'integer'],
            [['content_id'], 'exist', 'targetClass' => $this->LocalService()->patientFormContent, 'targetAttribute' => ['id'], 'message' => '参数有误呢。'],

            [['note'], 'default', 'value' => '未填写'],
            [['note'], 'string', 'max' => 255],
        );

        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        $model = new PatientFormModel($this->validator);
        $model->setPostValues($this->validator->attributes);
        $model->unlock();

        //异步处理申请解锁工作信息
        $this->LocalService()->swTaskClient->send([
            'svName' => 'projectPatientwork',
            'methodName' => 'updatePatientworkData',
            'params' => [
                'item_id' => $this->validator->attributes['item_id'],
                'itemsig_id' => $this->validator->attributes['itemsig_id'],
                'patient_id' => $this->validator->attributes['patient_id'],
                'checktime_id' => $this->validator->attributes['checktime_id'],
                'form_id' => $this->validator->attributes['form_id'],
                'user_id' => $this->LocalService()->identity->getId(),
                'content_id' => $this->validator->attributes['content_id'],
            ]
        ]);

        return $this->RenderApiJson()->Success();
    }

    /**
     * 填写分值表单
     * @return JsonModel
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function scoreFormCreateAction(): JsonModel
    {
        $contentId = $this->params()->fromPost('id', false);
        $postData = DataHelper::handleFormData($this->validator->attributes, $this->params()->fromPost('form_id'));

        $model = new PatientFormModel($this->validator);
        $model->setScenario($model::SCENARIO_USING_SCORE);
        if (!$contentId) {
            $this->addLog($model->createForm($postData));
        } else {
            $model->editForm($postData);
            $this->addLog(null);
        }

        return $this->RenderApiJson()->Success();
    }

    /**
     * 临时保存表单
     * @url xxx.com/patient/form/tempStorage
     */
    public function tempStorageAction(): JsonModel
    {
        $this->validator->setAttributesLabels([
            'form_id' => '表单ID',
            'patient_id' => '受试者ID',
            'checktime_id' => '检查点ID',
        ]);
        $this->validator->attach(
            [['form_id', 'patient_id', 'checktime_id'], 'required']
        );
        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }
        $model = new PatientFormModel();
        $model->setPostValues($this->LocalService()->request->getPost()->toArray());
        $model->tempStorage();

        return $this->RenderApiJson()->Success();
    }

    /**
     * 锁定识别类表单
     * @actionUrl /patient/form/lockShareForm
     * @analysis REQUEST_TIMES,RESPONSE_TIME[max=200]
     * @return JsonModel
     * @throws Exception
     */
    public function lockShareFormAction(): JsonModel
    {
        $this->validator->setAttributesLabels([
            'patient_id' => '受试者ID',
            'checktime_id' => '检查点ID',
            'form_id' => '表单ID',
        ]);

        $this->validator->attach(
            [['patient_id', 'checktime_id', 'form_id'], 'required']
        );

        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        $model = new PatientFormModel();
        $model->setPostValues($this->LocalService()->request->getPost()->toArray());
        $model->lockShareForm();

        // 异步处理工作信息
        $itemsig_id = $this->LocalService()->patient->getOneFieldVal('itemsig_id',[
            'id' => $this->validator->attributes['patient_id'],
        ]);
        $this->LocalService()->swTaskClient->send([
            'svName' => 'projectPatientwork',
            'methodName' => 'updatePatientworkData',
            'params' => [
                'item_id' => $this->validator->attributes['item_id'],
                'itemsig_id' => $itemsig_id,
                'patient_id' => $this->validator->attributes['patient_id'],
                'checktime_id' => $this->validator->attributes['checktime_id'],
                'form_id' => $this->validator->attributes['form_id'],
                'user_id' => $this->LocalService()->identity->getId()
            ]
        ]);

        return $this->RenderApiJson()->Success();
    }

    /**
     * 解锁识别类表单
     * @actionurl /patient/form/unlockShareForm
     * @return JsonModel
     * @throws Exception
     */
    public function unlockShareFormAction(): JsonModel
    {
        $this->validator->setAttributesLabels([
            'patient_id' => '受试者ID',
            'checktime_id' => '检查点ID',
            'form_id' => '表单ID',
            'item_id' => '项目ID',
        ]);

        $this->validator->attach(
            [['patient_id', 'checktime_id', 'form_id', 'item_id'], 'required']
        );

        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        $model = new PatientFormModel();
        $model->setPostValues($this->LocalService()->request->getPost()->toArray());
        $model->unlockShareForm();

        // 异步处理工作信息
        $itemsig_id = $this->LocalService()->patient->getOneFieldVal('itemsig_id',[
            'id' => $this->validator->attributes['patient_id'],
        ]);
        $this->LocalService()->swTaskClient->send([
            'svName' => 'projectPatientwork',
            'methodName' => 'updatePatientworkData',
            'params' => [
                'item_id' => $this->validator->attributes['item_id'],
                'itemsig_id' => $itemsig_id,
                'patient_id' => $this->validator->attributes['patient_id'],
                'checktime_id' => $this->validator->attributes['checktime_id'],
                'form_id' => $this->validator->attributes['form_id'],
                'user_id' => $this->LocalService()->identity->getId()
            ]
        ]);


        return $this->RenderApiJson()->Success();
    }

    /**
     * 删除一对多识别类表单数据
     * @actionurl /patient/form/deleteShareFormMulti
     * @return JsonModel
     * @throws Exception
     */
    public function deleteShareFormMultiAction()
    {
        $this->validator->attach(
            [['id', 'patient_id', 'checktime_id', 'form_id'], 'required']
        );

        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        $model = new PatientFormModel();
        $model->setPostValues($this->LocalService()->request->getPost()->toArray());
        $model->deleteShareFormMulti($this->validator->attributes['id']);

        return $this->RenderApiJson()->Success();
    }

    /**
     * 一对多共享图片上传
     * @actionUrl /patient/form/uploadMultiShareFormImage
     * @return JsonModel
     * @throws Exception
     */
    public function uploadMultiShareFormImageAction(): JsonModel
    {
        $this->validator->attach(
            [['form_id', 'patient_id', 'checktime_id', 'item_id', 'itemsig_id', 'share_img'], 'required']
        );

        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }
        $patientChecktimeWhere = new Where();
        $patientChecktimeWhere->equalTo('checktime_id',$this->validator->attributes['checktime_id'])
            ->equalTo('is_del',0)
            ->equalTo('patient_id',$this->validator->attributes['patient_id'])
            ->isNotNull('anchor_date');
        //验证是否有窗口期
        $isHaveAnchor = Laminas::$serviceManager->itemPatientchecktime->getOneFieldVal('id',$patientChecktimeWhere);
        if(empty($isHaveAnchor)){
            // 查一下检查点日期
            $checkTime = Laminas::$serviceManager->itemChecktime->memoryCache()->fetchOne([
                'order' => ['check_order DESC'],
                'where' => ['id' => $this->validator->attributes['checktime_id']]
            ]) ?: false;

            $field = $checkTime['field_id'];
            // 字段数据
            $field = Laminas::$serviceManager->itemFormField->memoryCache()->fetchOne(['where' => ['id' => $field]]);

            // 字段所属表单名称
            $form = Laminas::$serviceManager->itemForm->memoryCache()->fetchOne(['where' => ['id' => $field['form_id']]]);

            $allCheckId = Laminas::$serviceManager->itemCheckcontent->memoryCache()->fetchAll([
                'columns' => ['check_id'],
                'where' => ['form_id' => $form['id'], 'is_del' => 0]
            ]);

            $topCheckTime = Laminas::$serviceManager->itemChecktime->memoryCache()->fetchOne([
                'order' => ['check_order ASC'],
                'where' => ['id' => ArrayHelper::getColumn($allCheckId, 'check_id')]
            ]) ?: false;

            // 阶段名称
            $stageName = Laminas::$serviceManager->itemResearchstage->memoryCache()->fetchOne(['where' => ['id' => $topCheckTime['stage_id']]])['stage_name'] ?? '';

            throw new InvalidArgumentException("{$stageName} / {$topCheckTime['check_name']} - {$form['name']} / {$field['name']} 未填写, 请补充！");

        }


        if (SDMHelper::app()->form->getIsShareFormLock($this->validator->attributes['form_id'], $this->validator->attributes['patient_id'], $this->validator->attributes['checktime_id'])) {
            throw new InvalidArgumentException('当前数据已被锁定。');
        }

        Db::beginTransaction();

        $images = StringHelper::jsonDecode($this->validator->attributes['share_img'], true);

        $shareForms = ArrayHelper::getColumn(SDMHelper::app()->form->getGcoGroupForm($this->validator->attributes['form_id']), 'id');

        Laminas::$serviceManager->patientFormContentImg->update(['is_del' => 1], ['itemsig_id' => $this->validator->attributes['itemsig_id'], 'item_id' => $this->validator->attributes['item_id'], 'form_id' => $shareForms, 'patient_id' => $this->validator->attributes['patient_id'], 'checktime_id' => $this->validator->attributes['checktime_id']]);

        $isHaveImg = Laminas::$serviceManager->patientFormContentImg->fetchOne(['where'=>[
            'itemsig_id' => $this->validator->attributes['itemsig_id'],
            'item_id' => $this->validator->attributes['item_id'],
            'form_id' => $shareForms,
            'patient_id' => $this->validator->attributes['patient_id'],
            'checktime_id' => $this->validator->attributes['checktime_id']
        ],'columns'=>['id']]);

        foreach ($images as $image) {
            if (!$image['url']) {
                throw new InvalidArgumentException('图片格式不对。');
            }

            $image['url'] = DataHelper::handleImageSrc($image['url']);
            $shareFieldId = Laminas::$serviceManager->itemFormField->fetchOne(['where' => ['form_id' => $this->validator->attributes['form_id'], 'type' => FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE]])['id'];


            if ($has = Laminas::$serviceManager->patientFormContentImg->fetchOne(['where' => ['img_src' => $image['url']]])) {
                Laminas::$serviceManager->patientFormContentImg->update(['is_del' => 0], ['id' => $has['id']]);
            } else {
                $save_annex = [
                    'item_id' => $this->validator->attributes['item_id'],
                    'itemsig_id' => $this->validator->attributes['itemsig_id'],
                    'patient_id' => $this->validator->attributes['patient_id'],
                    'form_id' => $this->validator->attributes['form_id'],
                    'checktime_id' => $this->validator->attributes['checktime_id'],
                    'img_src' => $image['url'],
                    'img_name' => $image['name'] ?? '',
                    'img_type' => PatientFormContentImg::IMG_TYPE_NORMAL,
                    'content_id' => 0, // 一对多这种的没有id,
                    'field_id' => $shareFieldId,
                    'gco_pool' => SDMHelper::app()->form->getGcoPool($this->validator->attributes['form_id']),
                    'info_collect_type' => SDMHelper::app()->form->getInfoCollectType($this->validator->attributes['form_id']),
                    'is_form_ocr' => 1
                ];
                if(isset($image['collect_annex_id']) && !empty($image['collect_annex_id'])){
                    $save_annex['collect_annex_id'] = $image['collect_annex_id'];
                }
                Laminas::$serviceManager->patientFormContentImg->insert($save_annex);
                unset($save_annex);
            }
        }

        $forms = SDMHelper::app()->form->getGcoGroupForm($this->validator->attributes['form_id']);
        $model = new PatientFormModel();
        $model->setPostValues($this->validator->attributes);
        foreach ($forms as $form) {
            if (SDMHelper::app()->form->getIdentificationEdit($this->validator->attributes['form_id']) == 0) {
                $model->_updateRelationStatus($form['id'], 0);
            }
        }

        $eventKey = !empty($isHaveImg) ? EventEnumV2::EVENT_MULTI_SHARE_FORM_UPDATE_IMAGE :EventEnumV2::EVENT_MULTI_SHARE_FORM_UPLOAD_IMAGE;

        $model->logger->setEvent(EventEnumV2::getVal($eventKey))->setPostOriginData($this->validator->attributes)->setPostData($this->validator->attributes)->flush($this->validator->attributes);

        Db::commit();

        // 异步处理工作信息
        Laminas::$serviceManager->swTaskClient->send([
            'svName' => 'projectPatientwork',
            'methodName' => 'updatePatientworkData',
            'params' => [
                'item_id' => $this->validator->attributes['item_id'],
                'itemsig_id' => $this->validator->attributes['itemsig_id'],
                'patient_id' => $this->validator->attributes['patient_id'],
                'checktime_id' => $this->validator->attributes['checktime_id'],
                'form_id' => $this->validator->attributes['form_id'],
                'user_id' => Laminas::$serviceManager->identity->getId()
            ]
        ]);

        return $this->RenderApiJson()->Success();
    }

    public function compareAction()
    {
        $is_ae = $this->params()->fromPost('is_ae');   //区分是否是AE数据判断入口
        $id = $this->params()->fromPost('id');
        $item_id = $this->params()->fromPost('item_id');
        $form_id = $this->params()->fromPost('form_id');
        $checktime_id = $this->params()->fromPost('checktime_id');
        $patient_id = $this->params()->fromPost('patient_id');
        $sdtx = $this->params()->fromPost('sdtx');
        if (!$id) {
            throw new InvalidArgumentException('参数不对。');
        }

        if (!$item_id) {
            throw new InvalidArgumentException('缺少项目ID参数！');
        }

        if (!$form_id) {
            throw new InvalidArgumentException('缺少表单ID参数！');
        }

        if($is_ae){
            $originData = StringHelper::jsonDecode(Laminas::$serviceManager->itemPatientAeContent->fetchOne(['where' => ['id' => $id]])['data'], true);
        }else{
            $originData = StringHelper::jsonDecode(Laminas::$serviceManager->patientFormContent->fetchOne(['where' => ['id' => $id]])['data'], true);
        }

        //判断表单是否为共享类表单
        $formData = $this->LocalService()->itemForm->fetchOne(['where'=>[
            'id' => $form_id,
        ],['group_id','gco_pool']]);
        $form_group = !empty($formData) ? $formData['group_id'] : 0;
        $gco_pool = !empty($formData) ? $formData['gco_pool'] : 0;
        if(!empty($gco_pool)){
            $gco_where = [
                'is_del' => 0,
                'item_id' => $item_id,
                'group_id' => $form_group,
                'gco_pool' => $gco_pool,
            ];
            $gco_formid = $this->LocalService()->itemForm->fetchCol('id',$gco_where);
            //查询共享图片信息
            $img_where = [
                'is_del' => 0,
                'item_id' => $item_id,
                'checktime_id' => $checktime_id,
                'patient_id' => $patient_id,
                'gco_pool' => $gco_pool,
                'form_id' => StringHelper::toArray($gco_formid),
            ];
            $img_infos = $this->LocalService()->patientFormContentImg->fetchAll([
                'where'=>$img_where,
                'columns'=>['img_name as name','img_src as url']
            ]);
        }

        $diffParams = ArrayHelper::newdiff($originData,Params::app()->getValuesToArray());
        $list = [];
        //查询字段类型 如果是图片 需要截取显示
        $filedtype_arr = $this->LocalService()->itemFormField->fetchCol('type',[
            'is_del' => 0,
            'item_id' => $item_id,
        ]);
        $filedname_arr = $this->LocalService()->itemFormField->fetchCol('name',[
            'is_del' => 0,
            'item_id' => $item_id,
        ]);

        foreach ($diffParams as $key => $paramSet) {
            if (!DataHelper::isField($key)) {
                continue;
            }
            $filed_id = $key;
            if(strpos($key,'-')){
                $filed_ids = explode('-',$key);
                $filed_id = $filed_ids[0];
            }
            $filed_type           = isset($filedtype_arr[$filed_id]) && !empty($filedtype_arr[$filed_id]) ? $filedtype_arr[$filed_id] : '';

            $origin = SDMHelper::app()->form->field->getValueLabel($originData[$key], $key);
            $current =  SDMHelper::app()->form->field->getValueLabel(Params::app()->{$key}, $key);

            /*$origin = !empty($origin) ? $origin : '';
            $current = !empty($current) ? $current : '';*/

            if(in_array($filed_type,[FormField::FORM_FIELD_TYPE_UPLOAD_FILE,FormField::FORM_FIELD_TYPE_UPLOAD_IMAGE,FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE])){
                $origin_url = $current_url = '';
                //图片 需截取显示
                $old_value  = json_decode($origin, true) ? json_decode($origin, true) : $origin;
                //如果是共享图片的情况需要额外处理
                if($filed_type == FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE && empty($old_value)){
                    $old_value  = $img_infos;
                }
                if(!empty($old_value)){
                    foreach ($old_value as $oldvalue){
                        if(isset($oldvalue['name']) && !empty($oldvalue['name'])){
                            $file_url = $oldvalue['name'];
                        }else{
                            $old_file_url = $oldvalue['url'];
                            $file_url = substr($old_file_url, strrpos($old_file_url, '_') + 1);
                        }
                        $origin_url.=$file_url.',';
                    }
                    $origin = trim($origin_url,',');
                }
                $new_value  = json_decode($current, true) ? json_decode($current, true) : $current;
                if(!empty($new_value)){
                    foreach ($new_value as $nevalue){
                        //$new_file_url = $nevalue['url'];
                        if(isset($nevalue['name']) && !empty($nevalue['name'])){
                            $n_file_url = $nevalue['name'];
                        }else{
                            $new_file_url = $nevalue['url'];
                            $n_file_url = substr($new_file_url, strrpos($new_file_url, '_') + 1);
                        }
                        $current_url.=$n_file_url.',';
                    }
                    $current = trim($current_url,',');
                }
            }

            //解析后的值一致 排除
            if($origin === $current){ continue;}

            /*//都为空 不管什么形式的为空 跳过
            if(empty($origin) && empty($current)) continue;*/

            if(strpos($key,'-')){
                //拼接正确显示的label
                $key_arr = explode('-',$key);
                $key_name1 = SDMHelper::app()->form->field->getFieldString($key_arr[0]);
                $len = count($key_arr);
                if($key_arr[1] && $key_arr[2]){
                    $key_son_ids = $this->LocalService()->itemFormField->fetchCol('id',[
                        'is_del' => 0,
                        'parent' => $key_arr[1]
                    ]);
                    //查询选项值的id
                    $key_value_id = $this->LocalService()->itemFormFieldRadio->getOneFieldVal('field_id',[
                        'field_id' => StringHelper::toArray($key_son_ids),
                        'value' => $key_arr[$len -1],
                    ]);
                    $key_value_name = isset($filedname_arr[$key_value_id]) && !empty($filedname_arr[$key_value_id]) ? $filedname_arr[$key_value_id] : '';
                }
                $label = $key_value_name ? $key_name1.'('.$key_value_name.')': $key_name1;
            }else{
                $label = SDMHelper::app()->form->field->getFieldString($key);
            }

            $list[] = [
                'filed_id' => $key,
                'label' => $label,
                'origin' => $origin,
                'current' => $current,
                'modify_reason' => '',
            ];
        }

        unset($gco_formid);
        unset($formData);
        unset($img_infos);

        if($sdtx !== "[]" && !empty($sdtx)){
            $originsdtxData = $originData['sdtx'];
            $old_originsdtxData = json_decode($originsdtxData,true);
            $old_sdtx_infos = array_combine(array_column($old_originsdtxData['content'],'id'),$old_originsdtxData['content']);
            $sdtx_infos = json_decode($sdtx,true);
            $new_sdtx_infos = array_combine(array_column($sdtx_infos['content'],'id'),$sdtx_infos['content']);

            if($sdtx_infos['check_date'] != $old_originsdtxData['check_date']){
                $list[] = [
                    'filed_id' => '0_检查日期',
                    'label' => '检查日期',
                    'origin' => $sdtx_infos['check_date'],
                    'current' => $old_originsdtxData['check_date'],
                    'modify_reason' => '',
                ];
            }

            foreach ($new_sdtx_infos as $key=>$new_sdtx_info){
                $old_result  = isset($old_sdtx_infos[$new_sdtx_info['id']]['result']) && !empty($old_sdtx_infos[$new_sdtx_info['id']]['result']) ? $old_sdtx_infos[$new_sdtx_info['id']]['result'] : '';
                if(empty($old_result) && !empty($old_originsdtxData['note'])){
                    $old_result = $old_originsdtxData['note'];
                }
                $old_unit    = isset($old_sdtx_infos[$new_sdtx_info['id']]['unit']) ? $old_sdtx_infos[$new_sdtx_info['id']]['unit'] : '';
                $old_max_val = isset($old_sdtx_infos[$new_sdtx_info['id']]['max_val'])  ? $old_sdtx_infos[$new_sdtx_info['id']]['max_val'] : '';
                $old_min_val = isset($old_sdtx_infos[$new_sdtx_info['id']]['min_val']) ? $old_sdtx_infos[$new_sdtx_info['id']]['min_val'] : '';

                if(empty($new_sdtx_info['result']) && !empty($sdtx_infos['note'])){
                    $new_sdtx_info['result']  = $sdtx_infos['note'];
                }

                if($new_sdtx_info['result'] != $old_result){
                    $list[] = [
                        'filed_id' => $new_sdtx_info['id'].'_结果',
                        'label' => $new_sdtx_info['check_item'].'(结果)',
                        'origin' => $old_result,
                        'current' => $new_sdtx_info['result'],
                        'modify_reason' => '',
                    ];
                }

                if($new_sdtx_info['unit'] != $old_unit){
                    $list[] = [
                        'filed_id' => $new_sdtx_info['id'].'_单位',
                        'label' => $new_sdtx_info['check_item'].'(单位)',
                        'origin' => $old_unit,
                        'current' => $new_sdtx_info['unit'],
                        'modify_reason' => '',
                    ];
                }

                if($new_sdtx_info['max_val'] != $old_max_val){
                    $list[] = [
                        'filed_id' => $new_sdtx_info['id'].'_最大值',
                        'label' => $new_sdtx_info['check_item'].'(最大值)',
                        'origin' => $old_max_val,
                        'current' => $new_sdtx_info['max_val'],
                        'modify_reason' => '',
                    ];
                }

                if($new_sdtx_info['min_val'] != $old_min_val){
                    $list[] = [
                        'filed_id' => $new_sdtx_info['id'].'_最小值',
                        'label' => $new_sdtx_info['check_item'].'(最小值)',
                        'origin' => $old_min_val,
                        'current' => $new_sdtx_info['min_val'],
                        'modify_reason' => '',
                    ];
                }
            }
            unset($change_datas);
            unset($new_sdtx_infos);
            unset($sdtx_infos);
        }

        unset($originData);
        unset($diffParams);

        return $this->RenderApiJson()->Success([
            'header' => [
                ['label' => '字段/指标名称', 'prop' => 'label', 'type' => 'Text'],
                ['label' => '录入值', 'prop' => 'current', 'type' => 'Text'],
                ['label' => '历史值', 'prop' => 'origin', 'type' => 'Text'],
                ['label' => '修改原因', 'prop' => 'modify_reason', 'type' => 'Textarea','rules' => [
                    ['required' => true, 'message' => '请填写修改原因', 'trigger' => 'blur']
                ]],
            ],
            'list' => $list ?? [],
            'hidden_list' => [],
        ]);
    }

    private function formatText($text): array
    {
        $data = explode('-', $text);
        array_shift($data);
        $length = count($data);
        $result = [];
        for ($i = 0; $i < $length / 2; $i++) {
            $first = array_shift($data);
            $last = array_pop($data);
            $result[] = [$first, $last];
        }
        return $result;
    }
}
