<?php

namespace Application\Service\DB\Project;


use Application\Common\Enum;
use Application\Service\DB\AbstractDb;
use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\Edcloghelper;
use Application\Service\Extension\Helper\StringHelper;
use interop\container\containerinterface;
use Laminas\Db\Sql\Predicate\IsNotNull;
use Laminas\Db\Sql\Predicate\Operator;

class Patientworkinfo extends AbstractDb
{
    public const ACT_SDV           = 1;    // SDV 操作
    public const ACT_REVIEW        = 2;    // review 操作
    public const ACT_LOCK          = 3;    // 锁定操作
    public const ACT_REMOVE_REVIEW = 4;    // 取消 review 操作
    public const ACT_UNLOCK        = 5;    // 解锁操作
    public const ACT_SIGN          = 6;    // 电子签名操作
    public const ACT_UNSIGN        = 7;    // 取消电子签名操作
    public const ACT_REMOVE_SDV = 14;    // 取消 SDV 操作

    public function __construct($dbAdapter, containerinterface $container)
    {
        $this->tableName = 'yikeen_project_patientworkinfo';
        parent::__construct($dbAdapter, $container);
    }

    public function save(array $saveData)
    {
        if (empty($saveData[$this->primaryKey])) {
            $redis = $this->LocalService()->redisExtend->getRedisInstance();

            $lockKey = sprintf('PatientworkInfo:%s:%s:%s:%s:%s:%s', $saveData['item_id'], $saveData['itemsig_id'], $saveData['checktime_id'], $saveData['patient_id'], $saveData['form_id'], $saveData['content_id']);
            $lockTTL = 60;  // 锁的有效时间 10 秒

            // 新增 （数据已经存在就不要再新增了）
            if ($redis->set('Insert:' . $lockKey, 'locked', [
                'nx',
                'ex' => $lockTTL,
            ])) {
                $insertId = parent::save($saveData);
                // 将新数据的id存入redis缓存中
                $redis->set($lockKey, $insertId, [
                    'nx',
                    'ex' => $lockTTL * 6,
                ]);
                return $insertId;
            }

            return $redis->get($lockKey);

        }

        return parent::save($saveData); // TODO: Change the autogenerated stub
    }

    public static function getActLogEvent(int $actType): string
    {
        switch ($actType) {
            case self::ACT_LOCK:
                return Enum::LOG_EVENT_LOCK;
            case self::ACT_REMOVE_REVIEW:
                return Enum::LOG_EVENT_UNREVIEW;
            case self::ACT_UNLOCK:
                return Enum::LOG_EVENT_UNLOCK;
            case self::ACT_SDV:
                return Enum::LOG_EVENT_SDV;
            case self::ACT_REVIEW:
                return Enum::LOG_EVENT_REVIEW;
            case self::ACT_SIGN:
                return Enum::LOG_EVENT_SIGN;
            case self::ACT_UNSIGN:
                return Enum::LOG_EVENT_UNSIGN;
            case self::ACT_REMOVE_SDV:
                return Enum::LOG_EVENT_UNSDV;
        }
    }

    public static function getActLogEventDesc(int $actType): string
    {
        if (! isset(Enum::LOG_EVENT[self::getActLogEvent($actType)])) {
            throw new InvalidArgumentException(sprintf("日志事件【%s】不存在！", self::getActLogEvent($actType)));
        }
        return Enum::LOG_EVENT[self::getActLogEvent($actType)];
    }

    /**
     * Notes: 更新受试者阶段工作进度明细信息
     * User: lltyy
     * DateTime: 2025/5/21 18:39
     *
     * @param array $params
     */
    public function multipleUpdateData(array $params) {
        $item_id = isset($params['item_id']) && !empty($params['item_id']) ? $params['item_id'] : 0;//项目ID
        $itemsig_id = isset($params['itemsig_id']) && !empty($params['itemsig_id']) ? $params['itemsig_id'] : 0;//项目中心ID
        $patient_id = isset($params['patient_id']) && !empty($params['patient_id']) ? $params['patient_id'] : 0;//患者ID
        $checktime_id = isset($params['checktime_id']) && !empty($params['checktime_id']) ? $params['checktime_id'] : 0;//项目检查点ID
        $formGroup = isset($params['formgroup_id']) && !empty($params['formgroup_id']) ? $params['formgroup_id'] : 0;//表单分组
        $form_id = isset($params['form_id']) && !empty($params['form_id']) ? $params['form_id'] : 0;//操作表单ID
        $content_arr = isset($params['content_id']) && !empty($params['content_id']) ? $params['content_id'] : [];//需要更新的进度content
        $batch_id = isset($params['batch_id']) && !empty($params['batch_id']) ? $params['batch_id'] : 0;//新增Content对应的projectPatientworkbatch批次ID
        $operate_type = isset($params['operate_type']) && !empty($params['operate_type']) ? $params['operate_type'] : 0;//操作类型 1、SDV 2、Review 3、锁定 4、取消Review 5、解锁 6 电子签名 7 取消电子签名 8 SDV质疑 9 Review质疑 10 新增Content 11 编辑Content 12 删除Content  13 恢复Content 14 取消SDV
        $user_id = isset($params['user_id']) && !empty($params['user_id']) ? $params['user_id'] : 0;//操作人ID
        $update_time = isset($params['time']) && !empty($params['time']) ? $params['time'] : time();//操作人时间
        if((empty($item_id) || empty($itemsig_id)) && !empty($patient_id)){
            $patientData = $this->LocalService()->patient->fetchOne([
                'where'=>'id = '.$patient_id,
                'columns'=>['item_id','itemsig_id']
            ]);
            $item_id = !empty($patientData) ? $patientData['item_id'] : 0;
            $itemsig_id = !empty($patientData) ? $patientData['itemsig_id'] : 0;
            unset($patientData);
        }

        $batch_arr = [];//获取工作进度批次信息
        if(!empty($item_id) && !empty($patient_id) && !empty($form_id) && !empty($content_arr)){
            $Journal = new Edcloghelper;
            //获取表单Group
            if(empty($formGroup)){
                $formGroup = $this->LocalService()->itemForm->getOneFieldVal('group_id',[
                    'id' => $form_id,
                ]);
            }
            //试验总结类、AE类、SAE类、贯穿全程类表单
            if($formGroup == FormGroup::TEST_SUMMARY){//试验总结类
                $checktime_id = $this->LocalService()->itemChecktime->getOneFieldVal('id',[
                    'is_del' => 9,
                    'item_id' => $item_id,
                ]);
            }
            if($formGroup == FormGroup::AE){//AE类
                $checktime_id = -1;
            }
            if($formGroup == FormGroup::SAE){//SAE类
                $checktime_id = -2;
            }
            if($formGroup == FormGroup::THROUGH_PROCESS){//贯穿全程类
                $checktime_id = 0;
            }

            //查询质疑
            $formQuestionArr = $formErrorDatas = [];
            if(in_array($operate_type,[8,9,10,11,12,13]) && !empty($content_arr)){
                //信息条件拼接
                $question_where = [
                    'patient_id' => $patient_id,
                    'form_id' => $form_id,
                ];
                if(!empty($checktime_id) && !in_array($formGroup,[FormGroup::TEST_SUMMARY,FormGroup::AE,FormGroup::SAE,FormGroup::THROUGH_PROCESS])){
                    $question_where['checktime_id'] = $checktime_id;
                }
                if(!in_array($formGroup,[FormGroup::CHECK_OCR])){//非检查项类只查询该content质疑信息
                    $question_where['multi_id'] = StringHelper::toArray($content_arr);
                }
                $questions = $this->LocalService()->itemPatientFormLogicErrorPointer->fetchAll([
                    'where'=>$question_where,
                    'columns'=>['multi_id','is_reply','error_id']
                ]);
                unset($question_where);
                if(!empty($questions)) {
                    if(!in_array($formGroup,[FormGroup::CHECK_OCR])) {
                        foreach ($questions as $question) {
                            $formQuestionArr[$question['multi_id']][] = $question;
                        }
                    }else{
                        $formQuestionArr = $questions;
                    }
                    //查询质疑批次信息
                    $formErrorDatas = $this->LocalService()->itemPatientFormLogicError->fetchAll([
                        'where' => [
                            'id' => StringHelper::toArray(array_values(array_column($questions, 'error_id'))),
                        ],
                        'columns' => ['id', 'role', 'is_closed', 'is_del','formcontent_id']
                    ]);
                    $formErrorDatas = !empty($formErrorDatas) ? ArrayHelper::index($formErrorDatas, 'id') : [];
                }
                unset($questions);
            }

            //获取表单内容信息
            $contentDatas = [];
            if(in_array($operate_type,[10,11,12,13])) {
                $content_where = [
                    'id' => StringHelper::toArray($content_arr),
                ];
                if(in_array($operate_type,[10,11])){
                    $content_where['is_del'] = 0;
                }
                if(in_array($operate_type,[12,13])){
                    $content_where['is_del'] = 1;
                }
                if ($formGroup == FormGroup::AE) {
                    $contentDatas = $this->LocalService()->itemPatientAeContent->fetchAll([
                        'where' => $content_where,
                        'columns' => ['id', 'is_complete']
                    ]);
                    $contentDatas = !empty($contentDatas) ? ArrayHelper::index($contentDatas, 'id') : [];
                } else {
                    $contentDatas = $this->LocalService()->patientFormContent->fetchAll([
                        'where' => $content_where,
                        'columns' => ['id', 'is_yc', 'is_lock', 'is_complete']
                    ]);
                    $contentDatas = !empty($contentDatas) ? ArrayHelper::index($contentDatas, 'id') : [];
                }
                unset($content_where);
            }

            //新增、编辑Content
            if(in_array($operate_type,[10,11]) && !empty($content_arr)){
                //获取Patientworkinfo表 已存储的Content
                $patient_workinfo_contents = $this->fetchAll([
                    'where'=>[
                        'is_del' => 0,
                        'patient_id' => $patient_id,
                        'form_id' => $form_id
                    ],
                    'columns'=>['id','item_id','itemsig_id','patient_id','form_id','checktime_id','content_id','is_signature']
                ]);
                $patient_workinfo_content = !empty($patient_workinfo_contents) ? array_values(array_column($patient_workinfo_contents,'content_id')) : [];
                $patient_workinfo_signature = !empty($patient_workinfo_contents) ? array_values(array_column($patient_workinfo_contents,'is_signature')) : [];
                $save_info_data = [
                    'batch_id'=>$batch_id,
                    'item_id'=>$item_id,
                    'itemsig_id'=>$itemsig_id,
                    'patient_id'=>$patient_id,
                    'checktime_id'=>$checktime_id,
                    'form_id'=>$form_id,
                    'formgroup_id'=>$formGroup,
                    'is_sdv'=>0,
                    'is_review'=>0,
                    'edc_lock'=>0,
                    'is_signature'=>0,
                    'create_user_id'=>$user_id,
                    'create_time'=>$update_time,
                ];
                $is_un_signature = 0;
                foreach($content_arr as $contentid){
                    if(!in_array($contentid,$patient_workinfo_content)){
                        $save_info_data['is_complete'] = isset($contentDatas[$contentid]) && isset($contentDatas[$contentid]['is_complete']) && !empty($contentDatas[$contentid]['is_complete']) ? $contentDatas[$contentid]['is_complete'] : 0;
                        $save_info_data['is_yc'] = isset($contentDatas[$contentid]) && isset($contentDatas[$contentid]['is_yc']) && !empty($contentDatas[$contentid]['is_yc']) ? $contentDatas[$contentid]['is_yc'] : 0;
                        $save_info_data['is_lock'] = isset($contentDatas[$contentid]) && isset($contentDatas[$contentid]['is_lock']) && !empty($contentDatas[$contentid]['is_lock']) ? $contentDatas[$contentid]['is_lock'] : 0;
                        $save_info_data['content_id'] = $contentid;
                        $save_info_data['sdv_question'] = 0;
                        $save_info_data['review_question'] = 0;
                        //质疑
                        $formQuestions = $formQuestionArr;
                        if(!in_array($formGroup,[FormGroup::CHECK_OCR])){
                            $formQuestions = isset($formQuestionArr[$contentid]) && !empty($formQuestionArr[$contentid]) ? $formQuestionArr[$contentid] : [];
                        }else{
                            if(!empty($formQuestions)){
                                foreach($formQuestions as $formQuestionKey1=>$formQuestionInfo){
                                    $formQuestion_content = isset($formErrorDatas[$formQuestionInfo['error_id']]) && isset($formErrorDatas[$formQuestionInfo['error_id']]['formcontent_id']) && !empty($formErrorDatas[$formQuestionInfo['error_id']]['formcontent_id']) ? $formErrorDatas[$formQuestionInfo['error_id']]['formcontent_id'] : 0;
                                    if($formQuestion_content != $contentid){
                                        unset($formQuestions[$formQuestionKey1]);
                                    }
                                    unset($formQuestion_content);
                                }
                            }
                            $formQuestions = !empty($formQuestions) ? array_values($formQuestions) : [];
                        }
                        if(!empty($formQuestions)){
                            $question_data_arr = [
                                1=>[//SDV质疑
                                    'reply'=>0, //已回复
                                    'no_reply'=>0,//未回复
                                    'count'=>0,//未回复和已回复总数
                                    'close'=>0,//已关闭
                                    'delete'=>0,//已删除
                                ],
                                2=>[//Review质疑
                                    'reply'=>0, //已回复
                                    'no_reply'=>0,//未回复
                                    'count'=>0,//未回复和已回复总数
                                    'close'=>0,//已关闭
                                    'delete'=>0,//已删除
                                ],
                            ];
                            foreach($formQuestions as $formQuestionKey => $formQuestion){
                                $formQuestionError = isset($formErrorDatas[$formQuestion['error_id']]) && !empty($formErrorDatas[$formQuestion['error_id']]) ? $formErrorDatas[$formQuestion['error_id']] : [];
                                if(!empty($formQuestionError)){
                                    //已删除数据
                                    if(!empty($formQuestionError['is_del'])){
                                        if($formQuestionError['role'] == 1){
                                            $question_data_arr[1]['delete']++;
                                        }
                                        if($formQuestionError['role'] == 2 || empty($formQuestionError['role']) || is_null($formQuestionError['role'])){
                                            $question_data_arr[2]['delete']++;
                                        }
                                    }

                                    //未删除已关闭数据
                                    if(empty($formQuestionError['is_del']) && $formQuestionError['is_closed'] == 1){
                                        if($formQuestionError['role'] == 1){
                                            $question_data_arr[1]['close']++;
                                        }
                                        if($formQuestionError['role'] == 2 || empty($formQuestionError['role']) || is_null($formQuestionError['role'])){
                                            $question_data_arr[2]['close']++;
                                        }
                                    }

                                    //未删除未关闭
                                    if(empty($formQuestionError['is_del']) && empty($formQuestionError['is_closed'])){
                                        if($formQuestionError['role'] == 1){
                                            $question_data_arr[1]['count']++;
                                            if($formQuestion['is_reply'] == 1){//已回复
                                                $question_data_arr[1]['reply']++;
                                            }else{//未回复
                                                $question_data_arr[1]['no_reply']++;
                                            }
                                        }
                                        if($formQuestionError['role'] == 2 || empty($formQuestionError['role']) || is_null($formQuestionError['role'])){
                                            $question_data_arr[2]['count']++;
                                            if($formQuestion['is_reply'] == 1){//已回复
                                                $question_data_arr[2]['reply']++;
                                            }else{//未回复
                                                $question_data_arr[2]['no_reply']++;
                                            }
                                        }
                                    }
                                }
                                unset($formQuestionError);
                                unset($formQuestions[$formQuestionKey]);
                            }

                            //质疑状态
                            foreach($question_data_arr as $question_key=>$question_data){
                                $question_status = 0;
                                if(!empty($question_data['count']) || !empty($question_data['close']) || !empty($question_data['delete'])){
                                    //未回复数有值，则表示部分回复
                                    if(!empty($question_data['no_reply'])){
                                        $question_status = 2;
                                    }

                                    //如果未回复无值 且 已回复有值 且 总数与已回复一致，则表示已全部回复
                                    if(empty($question_data['no_reply']) && !empty($question_data['reply']) && $question_data['count'] == $question_data['reply']){
                                        $question_status = 1;
                                    }

                                    //如果未回复与已回复总数无值 且 已关闭有值，则表示已全部关闭
                                    if(empty($question_data['count']) && !empty($question_data['close'])){
                                        $question_status = 3;
                                    }

                                    ///如果无未回复与已回复总数 且 已关闭无值 且 已删除有值，则表示已全部删除
                                    if(empty($question_data['count']) && empty($question_data['close']) && !empty($question_data['delete'])){
                                        $question_status = 4;
                                    }
                                }
                                if($question_key == 1){//SDV质疑
                                    $save_info_data['sdv_question'] = $question_status;
                                }else{//Review质疑
                                    $save_info_data['review_question'] = $question_status;
                                }
                                unset($question_status);
                                unset($question_data_arr[$question_key]);
                            }
                            unset($question_data_arr);
                        }
                        unset($formQuestions);
                        $this->isSetInfo(false)->save($save_info_data);
                        if($operate_type == 10 && in_array(1,$patient_workinfo_signature)){
                            $is_un_signature = 1;
                        }
                    }
                }
                $batch_arr[] = $batch_id;
                unset($save_info_data);
                if($is_un_signature == 1 && !empty($patient_workinfo_contents)){
                    foreach($patient_workinfo_contents as $patient_workinfo_content_key=>$patient_workinfo_content_info){
                        //取消电子签名 content 的日志信息
                        if($patient_workinfo_content_info['is_signature'] == 1){
                            $this->isSetInfo(false)->update(['is_signature'=>0,'update_user_id'=>$user_id, 'update_time'=>$update_time],['id'=>$patient_workinfo_content_info['id']]);
                            //日志存储
                            $_POST = [
                                'item_id'=>$patient_workinfo_content_info['item_id'],
                                'itemsig_id'=>$patient_workinfo_content_info['itemsig_id'],
                                'patient_id'=>$patient_workinfo_content_info['patient_id'],
                                'form_id'=>$patient_workinfo_content_info['form_id'],
                                'checktime_id'=>$patient_workinfo_content_info['checktime_id'],
                                'id'=>$patient_workinfo_content_info['content_id']
                            ];
                            $logupdateFieldData = [
                                'item_id'=>$patient_workinfo_content_info['item_id'],
                                'itemsig_id'=>$patient_workinfo_content_info['itemsig_id'],
                                'patient_id'=>$patient_workinfo_content_info['patient_id'],
                                'form_id'=>$patient_workinfo_content_info['form_id'],
                                'checktime_id'=>$patient_workinfo_content_info['checktime_id'],
                                'is_signature'=>0,
                                'create_user_id'=>0,
                                'create_time'=>$update_time
                            ];

                            $_POST['type'] = self::ACT_UNSIGN;
                            $Journal->setContentId($patient_workinfo_content_info['content_id'])->setEvent(self::getActLogEvent(self::ACT_UNSIGN))->setPostData($_POST)->flush($logupdateFieldData);
                            unset($logupdateFieldData);
                            unset($_POST);
                        }
                        unset($patient_workinfo_contents[$patient_workinfo_content_key]);
                    }
                }
                unset($patient_workinfo_contents);
            }

            if(in_array($operate_type,[8,9,11,12,13])){
                if(!empty($content_arr)){
                    $info_where = [
                        'patient_id' => $patient_id,
                        'form_id' => $form_id,
                        'content_id' => StringHelper::toArray($content_arr),
                    ];
                    if(in_array($operate_type,[8,9,11,12])){
                        $info_where['is_del'] = 0;
                    }
                    if(in_array($operate_type,[13])){
                        $info_where['is_del'] = 1;
                    }
                    $infos = $this->fetchAll([
                        'where'=>$info_where,
                        'columns'=>['id','content_id','batch_id','item_id','itemsig_id','patient_id','checktime_id','form_id','content_id','is_sdv','is_review','edc_lock','is_signature']
                    ]);
                    unset($info_where);
                    if(!empty($infos)){
                        $batch_arr = array_values(array_unique(array_column($infos,'batch_id')));
                        $updateDataNewContentArr = [];
                        if($operate_type == 11){
                            //有数据更新的Content
                            $updateDataNewContentArr = $this->LocalService()->patientFormContentUpdated->fetchCol('content_id',[
                                'is_del' => 0,
                                'patient_id' => $patient_id,
                                'form_id' => $form_id,
                                'content_id' => StringHelper::toArray($content_arr),
                                new Operator('fields',Operator::OP_NE,'[]'),
                                new Operator('fields',Operator::OP_NE,''),
                                new IsNotNull('fields')
                            ]);
                            $updateDataNewContentArr = !empty($updateDataNewContentArr) ? array_values($updateDataNewContentArr) : [];

                            //获取检查项标星显示
                            $checkUpdateDataNewContentArr = $this->LocalService()->itemIdentificationresultchange->fetchCol('patientformcontent_id',[
                                'is_del' => 0,
                                'patient_id' => $patient_id,
                                'form_id' => $form_id,
                                'patientformcontent_id' => StringHelper::toArray($content_arr),
                                new Operator('update_fileds',Operator::OP_NE,''),
                                new IsNotNull('update_fileds')
                            ]);
                            if(!empty($checkUpdateDataNewContentArr)){
                                foreach($checkUpdateDataNewContentArr as $checkUpdateDataNewContent){
                                    if(!in_array($checkUpdateDataNewContent,$updateDataNewContentArr)){
                                        $updateDataNewContentArr[] = $checkUpdateDataNewContent;
                                    }
                                }
                            }
                            unset($checkUpdateDataNewContentArr);
                        }
                        foreach($infos as $infoKey=>$info){
                            if((in_array($operate_type,[11,12,13]) && isset($contentDatas[$info['content_id']]) && !empty($contentDatas[$info['content_id']])) || !in_array($operate_type,[11,12,13])){
                                $updateFieldData = [
                                    'update_user_id'=>$user_id,
                                    'update_time'=>$update_time,
                                    'sdv_question'=>0,
                                    'review_question'=>0
                                ];
                                $is_edit_sdv_review = 0;
                                if(in_array($operate_type,[11,12,13])) {
                                    if($operate_type == 11 && in_array($info['content_id'],$updateDataNewContentArr)){
                                        $is_edit_sdv_review = 1;
                                    }
                                    if(in_array($operate_type,[12,13])){
                                        $is_edit_sdv_review = 1;
                                    }
                                    $updateFieldData['is_yc'] = isset($contentDatas[$info['content_id']]['is_yc']) && !empty($contentDatas[$info['content_id']]['is_yc']) ? $contentDatas[$info['content_id']]['is_yc'] : -1;
                                    $updateFieldData['is_lock'] = isset($contentDatas[$info['content_id']]['is_lock']) && !empty($contentDatas[$info['content_id']]['is_lock']) ? $contentDatas[$info['content_id']]['is_lock'] : 0;
                                    $updateFieldData['is_complete'] = isset($contentDatas[$info['content_id']]['is_complete']) && !empty($contentDatas[$info['content_id']]['is_complete']) ? $contentDatas[$info['content_id']]['is_complete'] : 0;
                                    if (in_array($operate_type, [12])) {
                                        $updateFieldData['is_del'] = 1;
                                    }
                                    if (in_array($operate_type, [13])) {
                                        $updateFieldData['is_del'] = 0;
                                    }
                                }
                                if($is_edit_sdv_review == 1){
                                    $updateFieldData['is_sdv'] = in_array($info['is_sdv'],[1,2]) ? 2 : $info['is_sdv'];
                                    $updateFieldData['is_review'] = in_array($info['is_review'],[1,2]) ? 2 : $info['is_review'];
                                    $updateFieldData['edc_lock'] = 0;
                                    $updateFieldData['is_signature'] = 0;
                                }
                                //质疑
                                $formQuestions = $formQuestionArr;
                                if(!in_array($formGroup,[FormGroup::CHECK_OCR])){
                                    $formQuestions = isset($formQuestionArr[$info['content_id']]) && !empty($formQuestionArr[$info['content_id']]) ? $formQuestionArr[$info['content_id']] : [];
                                }else{
                                    if(!empty($formQuestions)) {
                                        foreach ($formQuestions as $formQuestionKey2 => $formQuestionInfo1) {
                                            $formQuestion_content1 = isset($formErrorDatas[$formQuestionInfo1['error_id']]) && isset($formErrorDatas[$formQuestionInfo1['error_id']]['formcontent_id']) && !empty($formErrorDatas[$formQuestionInfo1['error_id']]['formcontent_id']) ? $formErrorDatas[$formQuestionInfo1['error_id']]['formcontent_id'] : 0;
                                            if ($formQuestion_content1 != $info['content_id']) {
                                                unset($formQuestions[$formQuestionKey2]);
                                            }
                                            unset($formQuestion_content1);
                                        }
                                    }
                                    $formQuestions = !empty($formQuestions) ? array_values($formQuestions) : [];
                                }
                                if(!empty($formQuestions)){
                                    $question_data_arr = [
                                        1=>[//SDV质疑
                                            'reply'=>0, //已回复
                                            'no_reply'=>0,//未回复
                                            'count'=>0,//未回复和已回复总数
                                            'close'=>0,//已关闭
                                            'delete'=>0,//已删除
                                        ],
                                        2=>[//Review质疑
                                            'reply'=>0, //已回复
                                            'no_reply'=>0,//未回复
                                            'count'=>0,//未回复和已回复总数
                                            'close'=>0,//已关闭
                                            'delete'=>0,//已删除
                                        ],
                                    ];
                                    foreach($formQuestions as $formQuestionKey => $formQuestion){
                                        $formQuestionError = isset($formErrorDatas[$formQuestion['error_id']]) && !empty($formErrorDatas[$formQuestion['error_id']]) ? $formErrorDatas[$formQuestion['error_id']] : [];
                                        if(!empty($formQuestionError)){
                                            //已删除数据
                                            if(!empty($formQuestionError['is_del'])){
                                                if($formQuestionError['role'] == 1){
                                                    $question_data_arr[1]['delete']++;
                                                }
                                                if($formQuestionError['role'] == 2 || empty($formQuestionError['role']) || is_null($formQuestionError['role'])){
                                                    $question_data_arr[2]['delete']++;
                                                }
                                            }

                                            //未删除已关闭数据
                                            if(empty($formQuestionError['is_del']) && $formQuestionError['is_closed'] == 1){
                                                if($formQuestionError['role'] == 1){
                                                    $question_data_arr[1]['close']++;
                                                }
                                                if($formQuestionError['role'] == 2 || empty($formQuestionError['role']) || is_null($formQuestionError['role'])){
                                                    $question_data_arr[2]['close']++;
                                                }
                                            }

                                            //未删除未关闭
                                            if(empty($formQuestionError['is_del']) && empty($formQuestionError['is_closed'])){
                                                if($formQuestionError['role'] == 1){
                                                    $question_data_arr[1]['count']++;
                                                    if($formQuestion['is_reply'] == 1){//已回复
                                                        $question_data_arr[1]['reply']++;
                                                    }else{//未回复
                                                        $question_data_arr[1]['no_reply']++;
                                                    }
                                                }
                                                if($formQuestionError['role'] == 2 || empty($formQuestionError['role']) || is_null($formQuestionError['role'])){
                                                    $question_data_arr[2]['count']++;
                                                    if($formQuestion['is_reply'] == 1){//已回复
                                                        $question_data_arr[2]['reply']++;
                                                    }else{//未回复
                                                        $question_data_arr[2]['no_reply']++;
                                                    }
                                                }
                                            }
                                        }
                                        unset($formQuestionError);
                                        unset($formQuestions[$formQuestionKey]);
                                    }

                                    //质疑状态
                                    foreach($question_data_arr as $question_key=>$question_data){
                                        $question_status = 0;
                                        if(!empty($question_data['count']) || !empty($question_data['close']) || !empty($question_data['delete'])){
                                            //未回复数有值，则表示部分回复
                                            if(!empty($question_data['no_reply'])){
                                                $question_status = 2;
                                            }

                                            //如果未回复无值 且 已回复有值 且 总数与已回复一致，则表示已全部回复
                                            if(empty($question_data['no_reply']) && !empty($question_data['reply']) && $question_data['count'] == $question_data['reply']){
                                                $question_status = 1;
                                            }

                                            //如果未回复与已回复总数无值 且 已关闭有值，则表示已全部关闭
                                            if(empty($question_data['count']) && !empty($question_data['close'])){
                                                $question_status = 3;
                                            }

                                            ///如果无未回复与已回复总数 且 已关闭无值 且 已删除有值，则表示已全部删除
                                            if(empty($question_data['count']) && empty($question_data['close']) && !empty($question_data['delete'])){
                                                $question_status = 4;
                                            }
                                        }
                                        if($question_key == 1){//SDV质疑
                                            $updateFieldData['sdv_question'] = $question_status;
                                        }else{//Review质疑
                                            $updateFieldData['review_question'] = $question_status;
                                        }
                                        unset($question_status);
                                        unset($question_data_arr[$question_key]);
                                    }
                                    unset($question_data_arr);
                                }
                                unset($formQuestions);
                                //更新信息
                                $this->isSetInfo(false)->update($updateFieldData,'id = '.$info['id']);

                                //增加质疑、编辑Content、删除Content 增加取消SDV、取消Review、解锁、取消签名日志
                                //if(in_array($operate_type,[8,9,11,12])){
                                if($is_edit_sdv_review == 1){
                                    //日志存储
                                    $_POST = [
                                        'item_id'=>$info['item_id'],
                                        'itemsig_id'=>$info['itemsig_id'],
                                        'patient_id'=>$info['patient_id'],
                                        'form_id'=>$info['form_id'],
                                        'checktime_id'=>$info['checktime_id'],
                                        'id'=>$info['content_id']
                                    ];
                                    $updateFieldData = array_diff_Key($updateFieldData, array_flip([
                                        'update_user_id','update_time'
                                    ]));
                                    $updateFieldData['item_id'] = $info['item_id'];
                                    $updateFieldData['itemsig_id'] = $info['itemsig_id'];
                                    $updateFieldData['patient_id'] = $info['patient_id'];
                                    $updateFieldData['form_id'] = $info['form_id'];
                                    $updateFieldData['checktime_id'] = $info['checktime_id'];
                                    $updateFieldData['create_user_id'] = 0;
                                    $updateFieldData['create_time'] = $update_time;
                                    //取消SDV content 的日志信息
                                    if($info['is_sdv'] == 1){
                                        $_POST['type'] = self::ACT_REMOVE_SDV;
                                        $Journal->setContentId($info['content_id'])->setEvent(self::getActLogEvent(self::ACT_REMOVE_SDV))->setPostData($_POST)->flush($updateFieldData);
                                    }
                                    //取消Review content 的日志信息
                                    if($info['is_review'] == 1){
                                        $_POST['type'] = self::ACT_REMOVE_REVIEW;
                                        $Journal->setContentId($info['content_id'])->setEvent(self::getActLogEvent(self::ACT_REMOVE_REVIEW))->setPostData($_POST)->flush($updateFieldData);
                                    }
                                    //解锁 content 的日志信息
                                    if(in_array($info['edc_lock'],[1,2])){
                                        $_POST['type'] = self::ACT_UNLOCK;
                                        $Journal->setContentId($info['content_id'])->setEvent(self::getActLogEvent(self::ACT_UNLOCK))->setPostData($_POST)->flush($updateFieldData);
                                    }
                                    //取消电子签名 content 的日志信息
                                    if($info['is_signature'] == 1){
                                        $_POST['type'] = self::ACT_UNSIGN;
                                        $Journal->setContentId($info['content_id'])->setEvent(self::getActLogEvent(self::ACT_UNSIGN))->setPostData($_POST)->flush($updateFieldData);
                                    }
                                    unset($_POST);
                                }
                                unset($is_edit_sdv_review);
                                unset($updateFieldData);
                            }else{
                                //更新信息
                                $this->isSetInfo(false)->update(['is_del'=>1,'update_user_id'=>$user_id,'update_time'=>$update_time],'id = '.$info['id']);
                            }
                            unset($infos[$infoKey]);
                        }
                    }
                    unset($infos);
                }
            }
            unset($formQuestionArr);
            unset($formErrorDatas);
            if(empty($batch_arr)){
                //试验总结类、AE类、SAE类、贯穿全程类表单
                if($formGroup == FormGroup::TEST_SUMMARY){//试验总结类
                    $checktime_id = $this->LocalService()->itemChecktime->getOneFieldVal('id',[
                        'is_del' => 9,
                        'item_id' => $item_id,
                    ]);
                }
                if($formGroup == FormGroup::AE){//AE类
                    $checktime_id = -1;
                }
                if($formGroup == FormGroup::SAE){//SAE类
                    $checktime_id = -2;
                }
                if($formGroup == FormGroup::THROUGH_PROCESS){//贯穿全程类
                    $checktime_id = 0;
                }
                $batch_arr = $this->LocalService()->projectPatientworkbatch->fetchCol('id',[
                    'is_del' => 0,
                    'patient_id' => $patient_id,
                    'form_id' => $form_id,
                    'checktime_id' => $checktime_id,
                ]);
                $batch_arr = !empty($batch_arr) ? array_values($batch_arr) : [];
            }

            unset($contentDatas);
            unset($Journal);
        }
        //释放空间
        unset($item_id);
        unset($itemsig_id);
        unset($patient_id);
        unset($checktime_id);
        unset($formGroup);
        unset($form_id);
        unset($content_arr);
        unset($batch_id);
        unset($operate_type);
        unset($user_id);
        unset($update_time);

        return $batch_arr;
    }

}