<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/5/6 10:57
 * @Description：
 *
 */

namespace Application\Service\DB\Item;

use Application\Service\DB\Dictionary\Form;
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 Interop\Container\ContainerInterface;
use Application\Service\Extension\Helper\Edcloghelper;
use Application\Service\Extension\Helper\RouterHelper;
use Laminas\Db\Sql\Predicate\Like;
use Laminas\Db\Sql\Predicate\NotIn;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Stdlib\ArrayUtils;

class Confirm extends \Application\Service\DB\AbstractDb
{
    public function __construct($dbAdapter, ContainerInterface $container)
    {
        $this->tableName = 'yikeen_item_confirm';
        parent::__construct($dbAdapter, $container);
    }

    /**
     * Notes :提出质疑、更新数据 关闭审核
     * @param $item_id
     * @param $patient_id
     * @param $checktime_id 没有检查点ID 代表AE或者是SAE
     * @param $form_id
     * @param int $is_multi 是否为一对多表单  0否 1是
     * @param string $content_id 一对多表单IDS【逗号拼接的字符串】
     * @param int $is_more_operate 是否为批量操作【0 否 1 是】
     * @return bool
     * Author:唐伯虎不虎
     * Date:2023/11/16 14:33
     */
    public function closeconfirm($item_id,$patient_id,$checktime_id,$form_id,$is_multi=0,$content_id=0,$is_more_operate=0)
    {
        $Journal = new Edcloghelper;
        $Router = new RouterHelper;
        $paramNames = $Router->getmethodparams(__CLASS__, __FUNCTION__);

        $Requestparams = array_combine($paramNames,func_get_args());

        $itemsig_id = $this->LocalService()->patient->getOneFieldVal('itemsig_id',[
            'id' => $patient_id,
        ]);

        $formgroup = $this->LocalService()->itemForm->getOneFieldVal('group_id',[
            'id' => $form_id,
        ]);//表单类型
        $operate_content_arr = !empty($content_id) ? explode(',',$content_id) : [];
        if(is_array($checktime_id)){
            $checktime_id = implode(',',array_values(array_unique($checktime_id)));
        }
        if($formgroup == 4) {
            $where = [];
            //贯穿全程表单不在检查点显示 查询 字符串
            $except_checktime = $this->LocalService()->itemForm->getOneFieldVal('except_checktime', [
                'id' => $form_id,
            ]);

            if (!empty($except_checktime)) $where[] = new NotIn('check_id', $except_checktime);

            $checkid = $this->LocalService()->itemCheckcontent->fetchCol('check_id', ArrayUtils::merge([
                'is_del' => 0,
                'form_id' => $form_id,
            ], $where));
            $checkid = implode(',',$checkid ?: []);

            if(empty($checkid)) return true;
        }

        //项目 受试者、检查点、表单
        if (empty($item_id) || empty($patient_id)  || empty($form_id))  return false;

        $confirmWhere['where'] = [
            'item_id' => $item_id,
            'patient_id' => $patient_id,
            'form_id' => $form_id,
            'is_del' => 0,
        ];
        if($formgroup !=4 && !empty($checktime_id)) $confirmWhere['where']['checktime_id'] = explode(',', $checktime_id);
        if($formgroup ==4) $confirmWhere['where']['checktime_id'] = explode(',', $checkid);
        if($is_more_operate == 1){//批量取消Review
            $confirmWhere['where']['confirm_type'] = 2;
        }
        $confirmWhere['columns'] = ['id','checktime_id','form_id','patient_id','item_id','confirm_type','content_ids','is_all','child'];
        $result = $this->fetchAll($confirmWhere);

        if(!empty($result)){
            foreach($result as $key=>$value){
                $recordLog= false;
                $Event = $value['confirm_type'] == 1 ? 'Un-SDV' : 'Un-Review';//array_combine
                if($is_more_operate == 1){
                    $Event = $value['confirm_type'] == 1 ? 'MoreUn-SDV' : 'MoreUn-Review';//array_combine
                }
                if($is_multi == 1){
                    //查询当前一对多表单数量
                    $formnumber = $this->_getmanyformcount($item_id,$form_id,$checktime_id,$patient_id,$formgroup,0);
                    $formnumber = !empty($formnumber) ? array_values($formnumber) : [];

                    //一对多 取消单个审核
                    $content_idsArr = json_decode($value['content_ids'],true);
                    if(!empty($operate_content_arr)){
                        foreach($operate_content_arr as $operate_content){
                            if(in_array($operate_content,$content_idsArr))$recordLog = true;
                        }
                    }
                    if(!empty($content_idsArr)){
                        foreach($content_idsArr as $k=>$v){
                            //数据修正，避免历史数据或者单独删除数据造成数据不准确的问题
                            if(!in_array($k,$formnumber))unset($content_idsArr[$k]);
                            if(in_array($k,$operate_content_arr)) unset($content_idsArr[$k]);
                        }
                    }
                    $value['child'] = count($content_idsArr);//数据修正，避免历史数据或者单独删除数据造成数据不准确的问题

                    $is_all = 0;

                    //当前数据被删除完了
                    if(($value['child']) == 0 &&  count($formnumber) == 0){
                        $this->update(['is_del'=>1],['id'=>$value['id']]);
                        continue;
                    }

                    //一对多表单 删除其中一条 更正数据review状态
                    if(($value['child']) == count($formnumber)) $is_all = 1;

                    $this->update(['is_all'=>$is_all,'child'=>$value['child'],'content_ids'=>json_encode($content_idsArr)],['id'=>$value['id']]);
                    if($recordLog == true){
                        if(!empty($operate_content_arr)){
                            foreach($operate_content_arr as $operate_content1){
                                if(!empty($operate_content1) && $formgroup == 5) {
                                    $branch = Laminas::$serviceManager->itemPatientAeContent->getOneFieldVal('branch', [
                                        'id' => $operate_content1
                                    ]);
                                    $branch_ae = Laminas::$serviceManager->itemPatientAeContent->getOneFieldVal('id', [
                                        'branch' => $branch,
                                    ]);
                                    $operate_content1 = !empty($branch_ae) ? $branch_ae : $operate_content1;
                                    unset($branch);
                                    unset($branch_ae);
                                }
                                $Journal->setContentId($operate_content1)->setEvent($Event)->setPostData($Requestparams)->flush($value+['itemsig_id'=>$itemsig_id]);
                            }
                        }

                    }
                }else{
                    $this->update(['is_del'=>1],['id'=>$value['id']]);
                    if(!empty($operate_content_arr)){
                        if($formgroup == 5){
                            $branch = Laminas::$serviceManager->itemPatientAeContent->getOneFieldVal('branch',[
                                'id' => $operate_content_arr[0],
                            ]);
                            $branch_ae = Laminas::$serviceManager->itemPatientAeContent->getOneFieldVal('id',[
                                'branch' => $branch,
                            ]);
                            $operate_content_arr[0] = !empty($branch_ae) ? $branch_ae : $operate_content_arr[0];
                            unset($branch);
                            unset($branch_ae);
                        }
                        $Journal->setContentId($operate_content_arr[0])->setEvent($Event)->setPostData($Requestparams)->flush($value+['itemsig_id'=>$itemsig_id]);
                    }
                }
            }
        }
        //取消锁定
        $lockWhere['where'] = [
            'item_id' => $item_id,
            'patient_id' => $patient_id,
            'form_id' => $form_id,
            'is_del' => 0,
        ];
        if($formgroup !=4) $lockWhere['where']['checktime_id'] = StringHelper::toArray($checktime_id);
        if($formgroup ==4) $lockWhere['where']['checktime_id'] = StringHelper::toArray($checkid);
        $lockWhere['columns'] = ['id','item_id','checktime_id','form_id','patient_id','content_ids'];
        $lockData = $this->LocalService()->itemLock->fetchAll($lockWhere);
        $lockrecordLog= false;
        if(!empty($lockData)){
            $lockEvent = $is_more_operate == 1 ? 'MoreUn-Lock' : 'Un-Lock';
            foreach($lockData as $lockK=>$lockV){
                if($is_multi == 1){
                    //查询当前一对多表单数量
                    $formnumber = $this->_getmanyformcount($item_id,$form_id,$checktime_id,$patient_id,$formgroup,0);
                    $formnumber = !empty($formnumber) ? array_values($formnumber) : [];
                    //一对多 取消单个审核
                    $content_idsArr = json_decode($lockV['content_ids'],true);
                    if(!empty($operate_content_arr)){
                        foreach($operate_content_arr as $operate_content2){
                            if(in_array($operate_content2,$content_idsArr)) $lockrecordLog = true;
                        }
                    }
                    if(!empty($content_idsArr)){
                        foreach($content_idsArr as $k=>$v){
                            //数据修正，避免历史数据或者单独删除数据造成数据不准确的问题
                            if(!in_array($k,$formnumber))unset($content_idsArr[$k]);
                            if(in_array($k,$operate_content_arr)) unset($content_idsArr[$k]);
                        }
                    }
                    $value['child'] = count($content_idsArr);//数据修正，避免历史数据或者单独删除数据造成数据不准确的问题
                    $is_all = 0;
                    //当前数据被删除完了
                    if(($value['child']) == 0 &&  count($formnumber) == 0){
                        $this->LocalService()->itemLock->update(['is_del'=>1],['id'=>$lockV['id']]);
                        continue;
                    }
                    //一对多表单 删除其中一条 更正数据review状态
                    if(($value['child']) == count($formnumber)) $is_all = 1;

                    $this->LocalService()->itemLock->update(['is_all'=>$is_all,'child'=>$value['child'],'content_ids'=>json_encode($content_idsArr)],['id'=>$lockV['id']]);
                    if($lockrecordLog == true){
                        if(!empty($operate_content_arr)) {
                            foreach ($operate_content_arr as $operate_content3) {
                                if (!empty($operate_content3) && $formgroup == 5) {
                                    $branch = Laminas::$serviceManager->itemPatientAeContent->getOneFieldVal('branch',[
                                        'id' => $operate_content3
                                    ]);
                                    $branch_ae = Laminas::$serviceManager->itemPatientAeContent->getOneFieldVal('id',[
                                        'branch' => $branch,
                                    ]);
                                    $operate_content3 = !empty($branch_ae) ? $branch_ae : $operate_content3;
                                    unset($branch);
                                    unset($branch_ae);
                                }
                                $Journal->setContentId($operate_content3)->setEvent($lockEvent)->setPostData($Requestparams)->flush($value+['itemsig_id'=>$itemsig_id]);
                            }
                        }
                    }
                }else{
                    $this->LocalService()->itemLock->update(['is_del'=>1],['id'=>$lockV['id']]);
                    if(!empty($operate_content_arr)){
                        if($formgroup == 5){
                            $branch = Laminas::$serviceManager->itemPatientAeContent->getOneFieldVal('branch',[
                                'id' => $operate_content_arr[0],
                            ]);
                            $branch_ae = Laminas::$serviceManager->itemPatientAeContent->getOneFieldVal('id',[
                                'branch' => $branch,
                            ]);
                            $operate_content_arr[0] = !empty($branch_ae) ? $branch_ae : $operate_content_arr[0];
                            unset($branch);
                            unset($branch_ae);
                        }
                        $Journal->setContentId($operate_content_arr[0])->setEvent($lockEvent)->setPostData($Requestparams)->flush($value+['itemsig_id'=>$itemsig_id]);
                    }
                }
            }
        }
        unset($operate_content_arr);

        //取消签名数据
        $delSignaturedetail = [
            'item_id'=>$item_id,
            'patient_id'=>$patient_id,
            'form_id'=>$form_id,
            'checktime_id'=>$checktime_id,
            'is_more_operate'=>$is_more_operate
        ];
        if($formgroup == 4){
            $delSignaturedetail['checktime_id'] = $checkid;
        }
        $this->LocalService()->itemSignaturedetail->delPatientFormSignature($delSignaturedetail);

        return true;
    }

    //每次数据同步需要更新 数据已修改，解除SDV和Review
    public function changedatacloseconfirm($item_id)
    {
        //查询大项目ID
        $fid = $this->LocalService()->itemInfo->getOneFieldVal('fid',[
            'is_del' => 0,
            'id' => $item_id,
        ]);

        $sendWhere['where'] = [
            'item_id' => $item_id,
            'table_id' => 78,
        ];
        $sendWhere['columns'] = ['id','create_time'];
        $sendWhere['order'] = "id desc";
        $sendWhere['limit'] = 2;
        $prevsendData = $this->LocalService()->adminSend->fetchAll($sendWhere);

        $contentupdateWhere['where'] = [
            'item_id' => $item_id,
        ];
        if(count($prevsendData) < 2 ){
            $contentupdateWhere['where'] = [
                'is_del' => 0,
            ];
        }else{
            $contentupdateWhere['where'][] = new Operator('create_time', Operator::OP_GT, $prevsendData[1]['create_time']);
        }

        $contentupdateWhere['columns'] = ['id','item_id','checktime_id','form_id','patient_id','content_id','is_multi'];
        $contentupdateData = $this->LocalService()->itemConfirm->fetchAll($contentupdateWhere);
        foreach($contentupdateData as $k=>$v){
            $this->closeconfirm($item_id,$v['patient_id'],$v['checktime_id'],$v['form_id'],$v['is_multi'],$v['content_id']);
        }
        return true;
    }

    //一对多删除表单更新Review 锁定状态
    public function ChangeFormStatus($item_id,$patient_id,$checktime_id,$form_id,$content_id=0)
    {
        $formgroup = $this->LocalService()->itemForm->getOneFieldVal('group_id',[
            'id' => $form_id,
        ]);

        if($formgroup == 4) {
            $where = '';
            //贯穿全程表单不在检查点显示 查询 字符串
            $except_checktime = $this->LocalService()->itemForm->getOneFieldVal('except_checktime',[
                'id' => $form_id,
            ]);
            if(!empty($except_checktime)) $except_checktime[] = new NotIn('check_id', StringHelper::toArray($except_checktime));
            $checkid = $this->LocalService()->itemCheckcontent->fetchCol('check_id', ArrayUtils::merge($where, [
                'is_del' => 0,
                'form_id' => $form_id,
            ]));
        }

        //项目 受试者、表单
        if (empty($item_id) || empty($patient_id)  || empty($form_id))  return false;
        $confirmWhere['where'] = [
            'item_id' => $item_id,
            'patient_id' => $patient_id,
            'form_id' => $form_id,
            'is_del' => 0,
        ];
        if($formgroup !=4 && !empty($checktime_id)) $confirmWhere['where']['checktime_id'] = StringHelper::toArray($checktime_id);
        if($formgroup ==4) $confirmWhere['where']['checktime_id'] = $checkid;;
        $confirmWhere['columns'] = ['id','checktime_id','patient_id','item_id','confirm_type','content_ids','is_all','child'];
        $result = $this->fetchAll($confirmWhere);

        foreach($result as $k=>$v){
            $formnumber = $this->_getmanyformcount($item_id,$form_id,$checktime_id,$patient_id,$formgroup,0);
            //一对多 取消单个审核

            $content_idsArr = json_decode($v['content_ids'],true);
            $status = 0;


            foreach($content_idsArr['id'] as $key=>$value){
                //数据修正，避免历史数据或者单独删除数据造成数据不准确的问题
                if(!in_array($v,$formnumber))unset($content_idsArr['id'][$key]);

                if($v == $content_id) unset($content_idsArr['id'][$key]);
            }
            $value['child'] = count($content_idsArr['id']);//数据修正，避免历史数据或者单独删除数据造成数据不准确的问题

            $is_all = 0;

            //一对多表单 删除其中一条 更正数据review状态
            if(($value['child']) == count($formnumber)) $is_all = 1;

            $this->update(['is_all'=>$is_all,'child'=>$value['child'],'content_ids'=>json_encode($content_idsArr)],['id'=>$value['id']]);


        }

    }

    public function getupdatedatastatus($item_id,$checktime_id,$patient_id)
    {
        $fid = $this->LocalService()->itemInfo->getOneFieldVal('fid',[
            'is_del' => 0,
            'id' => $item_id,
        ]);

        $sendWhere['where'] = [
            'item_id' => $fid,
            'table_id' => 78,
        ];
        $sendWhere['columns'] = ['id','create_time'];
        $sendWhere['order'] = "id desc";
        $sendWhere['limit'] = 2;
        $prevsendData = $this->LocalService()->adminSend->fetchAll($sendWhere);

        $contentupdateWhere['where'] = [
            'item_id' => $item_id,
            'checktime_id' => $checktime_id,
            'patient_id' => $patient_id,
        ];
        if(count($prevsendData) < 2 ){
            $contentupdateWhere['where']['is_del'] = 0;
        }else{
            $contentupdateWhere['where'][] = new Operator('create_time', Operator::OP_GT, $prevsendData[1]['create_time']);
        }

        $contentupdateData = $this->LocalService()->patientFormContentUpdated->fetchCol('form_id',$contentupdateWhere['where']);
        return $contentupdateData;
    }

    //获取一对多表单条数
    public function _getmanyformcount($item_id,$form_id,$checktime_id,$patient_id,$formgroup,$formtype)
    {
        $patientformwhereArr = [
            'is_del' => 0,
            'item_id' => $item_id,
            'patient_id' => $patient_id,
            'form_id' => $form_id,
        ];
        if($formgroup != 4 && !empty($checktime_id))$patientformwhereArr['checktime_id'] = $checktime_id;
        if($formgroup == 5){
            $patientformcontent = $this->LocalService()->itemPatientAeContent->fetchCol('id', [
                'is_del' => 0,
                'patient_id' => $patient_id,
            ]);
        }else{
            $patientformcontent = $this->LocalService()->patientFormContent->fetchCol('id', $patientformwhereArr);
        }
        return $patientformcontent;
    }

    //获取质疑
    public function _geterror($checktime_id,$patient_id,$form_id = 0)
    {
        $logicPointerWhere['where'] = [
            'is_del' => 0,
            'patient_id' => $patient_id,
        ];
        if(!empty($form_id)) $logicPointerWhere['where']['form_id'] = $form_id;
        if(!empty($checktime_id)) $logicPointerWhere['where']['checktime_id'] = $checktime_id;

        $logicPointerWhere['columns'] = ['form_id','logic_expression_id','is_del','is_reply','error_id'];
        $loginerrorPointerDatas = $this->LocalService()->itemPatientFormLogicErrorPointer->fetchAll($logicPointerWhere);
        $logicForm = [];
        foreach($loginerrorPointerDatas as $PointerK => $PointerV){
            if(!empty($PointerV['logic_expression_id'])){
                $arr['is_reply'] = $PointerV['is_reply'];
                $arr['error_type'] = 0;
                $arr['error_id'] = $PointerV['error_id'];
            }else{
                $arr['is_reply'] = $PointerV['is_reply'];
                $arr['error_type'] = 1;
                $arr['error_id'] = $PointerV['error_id'];
            }
            $logicForm[$PointerV['form_id']][] = $arr;
        }
        return $logicForm;
    }

    /**
     * Notes :获取更新数据的type
     * @param $operate_type 操作者角色  CAR/DM
     * @param $group group == 1  SDV/Review  正常   gourp ==2 1对多
     * @param $AoS 1 新增  2 删除
     * Author:唐伯虎不虎
     * Date:2023/10/19 15:56
     */
    public function _getchangdataType($operate_type,$group,$AoS)
    {
        //$group
        switch($group){
            case 1:
                if($operate_type == 2 && $AoS == 1){
                    return  3;
                }elseif($operate_type == 2 && $AoS == 2){
                    return 4;
                }elseif($operate_type == 1 && $AoS == 1){
                    return  7;
                }elseif($operate_type == 1 && $AoS == 2){
                    return  8;
                }
                break;
            case 2:
                if($operate_type == 2 && $AoS == 1){
                    return  9;
                }elseif($operate_type == 2 && $AoS == 2){
                    return 10;
                }elseif($operate_type == 1 && $AoS == 1){
                    return  11;
                }elseif($operate_type == 1 && $AoS == 2){
                    return  12;
                }
                break;
        }
    }


    /**
     * Notes: 表单操作SDV和Review 删除修改状态（红星）
     * DateTime: 2025/5/16 8:17
     *
     * @param $patient_id
     * @param $checktime_id
     * @param $form_id
     * @param $type
     * @param string $id 【逗号拼接的字符串】
     * @return bool
     */
    public function delformupdatestatus($patient_id,$checktime_id,$form_id,$type,$id = 0) :void
    {

        $type = ($type >1) ? 1: 2;
        //查询当前表单是否是一对多
        $typetype = $this->LocalService()->itemForm->getOneFieldVal('type',[
            'id' => $form_id,
        ]);//获取项目名称
        $formgroup = $this->LocalService()->itemForm->getOneFieldVal('group_id',[
            'id' => $form_id,
        ]);//获取项目名称

        if($formgroup == 4)$checktime_id = implode(',',$checktime_id);
        $where = [
            'checktime_id' => StringHelper::toArray($checktime_id),
            'patient_id' => $patient_id,
            'form_id' => $form_id,
            'is_del' => 0,
            'confirm_type' => $type,
        ];
        if($typetype == 1){
            $is_data = $this->fetchOne(['where'=>$where,'columns'=>['id','content_ids']]);
            $contentArr = json_decode($is_data['content_ids'],true);
            $id_arr = explode(',',$id);
            if(!empty($id_arr)){
                foreach($id_arr as $id_info){
                    if(in_array($id_info,$contentArr)){
                        $update_where = [
                            'form_id' => $form_id,
                            'patient_id' => $patient_id,
                            'content_id' => $id_info,
                        ];
                        if(!empty($checktime_id)){
                            $update_where['checktime_id'] = StringHelper::toArray($checktime_id);
                        }
                        $this->LocalService()->patientFormContentUpdated->update(['is_del'=>1],$update_where);
                    }
                }
            }
        }else{
            $where['is_all'] = 1;
            $is_data = $this->fetchOne(['where'=>$where,'columns'=>['id','content_ids']]);
            if($is_data){
                $this->LocalService()->patientFormContentUpdated->update(['is_del'=>1],['form_id'=>$form_id,'checktime_id'=>$checktime_id,'patient_id'=>$patient_id]);
                $this->LocalService()->itemIdentificationresultchange->update(['update_fileds'=>''],['form_id'=>$form_id,'checktime_id'=>$checktime_id,'patient_id'=>$patient_id]);
            }
        }


    }

    public function changeAeErrorId($ae_id,$changeAe_id,$patient_id,$form_id,$newData,$oldData)
    {
        if($ae_id != $changeAe_id){
            $errorData = $this->LocalService()->itemPatientFormLogicError->fetchCol('id',[
                'patient_id' => $patient_id,
                'checktime_id' => 0,
                'is_report' => 0,
                'multi_id' => $ae_id,
                'form_id' => $form_id,
            ]);
            if($errorData){
                $this->LocalService()->itemPatientFormLogicError->update(
                    [
                        'multi_id'=>$changeAe_id
                    ],
                    [
                        'id'=>$errorData,
                        'patient_id'=>$patient_id,
                        'checktime_id'=>0,
                        'is_report'=>0,
                        'multi_id'=>$ae_id,
                        'form_id'=>$form_id
                    ]
                );

                $errorData = $this->LocalService()->itemPatientFormLogicErrorPointer->update(['multi_id'=>$changeAe_id],['error_id'=>$errorData]);
            }
        }
        $newData = $newData;
        $oldData = json_decode($oldData,true);
        $updatedFields = [];
        $item_id = $newData['item_id'];
        foreach ($newData as $k => $data) {
            if (DataHelper::isField($k)) {
                // 有数据修改再解锁
                if (is_array($data)) {
                    sort($data);
                }

                if (is_array($oldData[$k])) {
                    sort($oldData[$k]);
                }
                if (!isset($oldData[$k]) || $data != $oldData[$k]) {
                    $updatedFields[$k] = $oldData[$k];
                }
            }
        }

        //*******************************
        $callable = function ($id, $autoReply = false, $pointer = null)  use($item_id){
            // 被关联的质疑自动关闭的时候要加一个自动回复
            if ($autoReply === true) {
                Laminas::$serviceManager->itemPatientFormLogicErrorQuery->save([
                    'content' => '上级菜单数据更新!',
                    'error_id' => $id,
                    'platform' => 1,
                    'is_reply' => 1,
                    'pointer_id' => $pointer,
                    'item_id' => $item_id,
                    'create_user_id' => 0 // 系统
                ]);
            }

            // 删除质疑
            Laminas::$serviceManager->itemPatientFormLogicError->update(['is_closed' => 1], ['id' => $id]);
            //Laminas::$serviceManager->itemPatientFormLogicErrorQuery->update(['is_del' => 1], ['error_id' => $id]);
            Laminas::$serviceManager->itemPatientFormLogicErrorLog->update(['is_closed' => 1], ['error_id' => $id]);
            //Laminas::$serviceManager->itemPatientFormLogicErrorPointer->update(['is_del' => 1], ['error_id' => $id]);
        };
        if ($updatedFields) {
            foreach ($updatedFields as $field => $v) {
                $childError = Laminas::$serviceManager->itemPatientFormLogicErrorPointer->fetchAll([
                    'where' => [
                        'patient_id' => $patient_id,
                        'checktime_id' => 0,
                        'form_id' => $form_id,
                        new Like('prop', "%{$field}%"),
                        new Operator('prop', Operator::OP_NE, $field),
                        'is_del' => 0
                    ]
                ]) ?: [];

                foreach ($childError as $error) {
                    $callable($error['error_id'], true, $error['id']);
                }
            }
        }
        //*******************************


        //判断是否操作过SDV或者REVIEW
        $sdv_review_where = [
            'is_del' => 0,
            'patient_id' => $patient_id,
            'form_id' => $form_id,
            'content_id' => $ae_id,
            [
                'or' => [
                    'is_sdv' => 1,
                    'is_review' => 1,
                ]
            ]
        ];
        $sdv_review_count = Laminas::$serviceManager->projectPatientworkinfo->getCount($sdv_review_where);
        unset($sdv_review_where);
        if (empty($sdv_review_count)) {
            return;
        }

        $has = Laminas::$serviceManager->patientFormContentUpdated->fetchOne([
            'where' => [
                'content_id' => $ae_id,
                'form_id' => $form_id
            ]
        ]);
        if($has){
            $update_fields = !empty($updatedFields) ? json_encode($updatedFields) : NULL;
            Laminas::$serviceManager->patientFormContentUpdated->update(['is_del'=>0,'fields' => $update_fields, 'content_id'=>$changeAe_id], ['id'=>$has['id']]);
        }else{
            if(!empty($updatedFields)){
                Laminas::$serviceManager->patientFormContentUpdated->insert([
                    'item_id' => $newData['item_id'],
                    'checktime_id' => 0,
                    'form_id' => $form_id,
                    'patient_id' => $patient_id,
                    'fields' => json_encode($updatedFields),
                    'content_id' => $changeAe_id,
                    'is_multi' => 1
                ]);
            }
        }

        return true;
    }
}