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

use Application\Service\DB\Dictionary\FormField;
use Application\Service\Extension\Helper\StringHelper;
use Interop\Container\ContainerInterface;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\DB\Dictionary\FormGroup;
use Laminas\Db\Sql\Predicate\Expression;
use Laminas\Db\Sql\Predicate\Operator;

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

    /**
     * Notes: 更新患者阶段工作信息【化验单、常规类识别】
     * User: lltyy
     * DateTime: 2025/2/10 15:28
     *
     * @param array $params
     */
    public function updatePatientworkData(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
        $form_id = isset($params['form_id']) && !empty($params['form_id']) ? $params['form_id'] : 0;//操作表单ID
        $content_id = isset($params['content_id']) && !empty($params['content_id']) ? $params['content_id'] : 0;//操作表单内容ID
        $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) && !empty($patientData['item_id']) ? $patientData['item_id'] : 0;
            $itemsig_id = !empty($patientData) && !empty($patientData['itemsig_id']) ? $patientData['itemsig_id'] : 0;
            unset($patientData);
        }
        if(!empty($item_id) && !empty($itemsig_id) && !empty($patient_id) && !empty($checktime_id) && !empty($form_id)){
            //获取表单信息
            $formInfo = $this->LocalService()->itemForm->fetchOne([
                'where' => [
                    'id' => $form_id,
                ],
                'columns' => ['group_id', 'gco_pool','info_collect_type']
            ]);
            //判断表单是否为 检查类、常规类识别表单
            if(!empty($formInfo) && in_array($formInfo['group_id'],[FormGroup::CHECK_OCR,FormGroup::NORMAL_OCR])){
                //区分表单类型
                $info_type = 0;
                if($formInfo['group_id'] == FormGroup::NORMAL_OCR){
                    $info_type = 1;
                }
                $form_ids = $form_id;
                //常规类识别表单 【同组表单】
                if($info_type == 1){
                    //获取该表单对应的同组表单
                    if($formInfo['gco_pool'] != ''){
                        //获取医嘱类型
                        $form_id_arr = $this->LocalService()->itemForm->fetchCol('id',[
                            'is_del' => 0,
                            'item_id' => $item_id,
                            'group_id' => $formInfo['group_id'],
                            'gco_pool' => $formInfo['gco_pool'],
                        ]);
                        if(!empty($form_id_arr)){
                            //获取检查点下同组常规类识别表单
                            $check_form_arr = [];
                            //判断该检查点是否为计划外检查点
                            $patientchecktime_id = $this->LocalService()->itemChecktime->getOneFieldVal('patientchecktime_id',[
                                'item_id' => $item_id,
                                'id' => $checktime_id,
                            ]);
                            $patientchecktime_id = !empty($patientchecktime_id) ? $patientchecktime_id : 0;

                            if(!empty($patientchecktime_id)){
                                $check_form_arr = $this->LocalService()->itemPatientcheckcontent->fetchCol('form_id', [
                                    'is_del' => 0,
                                    'patient_id' => $patient_id,
                                    'patientchecktime_id' => $patientchecktime_id,
                                    'form_id' => StringHelper::toArray(array_values($form_id_arr)),
                                ]);
                            }else{
                                $check_form_arr = $this->LocalService()->itemCheckcontent->fetchCol('form_id', [
                                    'is_del' => 0,
                                    'check_id' => $checktime_id,
                                    'form_id' => StringHelper::toArray(array_values($form_id_arr)),
                                ]);
                            }
                            $check_form_arr = !empty($check_form_arr) ? array_values(array_unique(array_values($check_form_arr))) :[];
                            if(!empty($check_form_arr)){
                                $field_count = $this->LocalService()->itemFormField->getCount([
                                    'is_del' => 0,
                                    'form_id' => StringHelper::toArray($check_form_arr),
                                    new Operator('type', Operator::OP_NE, FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE)
                                ]);
                                if(!empty($field_count)){
                                    $form_ids = implode(',',$check_form_arr);
                                }else{
                                    $form_ids = '';
                                }
                            }else{
                                $form_ids = '';
                            }
                            unset($check_form_arr);
                            unset($patientchecktime_id);
                        }else{
                            $form_ids = '';
                        }
                        unset($form_id_arr);
                        unset($info_collect_type);
                    }else{
                        $form_ids = '';
                    }
                }
                //更新表单信息
                if(!empty($form_ids)){
                    $old_where = [];
                    foreach(explode(',',$form_ids) as $form_id_info){
                        $old_where['or'][] = new Expression('FIND_IN_SET(?, form_ids)', $form_id_info);
                    }
                    //判断该表单下是否存在数据
                    $old_info_where = $old_where;
                    $old_info_where['is_del'] = 0;
                    $old_info_where['info_type'] = $info_type;
                    $old_info_where['patient_id'] = $patient_id;
                    $old_info_where['checktime_id'] = $checktime_id;
                    if($info_type == 0){
                        $old_info_where['formcontent_id'] = $content_id;
                    }
                    $old_info = $this->fetchOne(['where'=> $old_info_where]);
                    unset($old_info_where);
                    $save_data = [
                        'info_type'=>$info_type,
                        'item_id'=>$item_id,
                        'itemsig_id'=>$itemsig_id,
                        'patient_id'=>$patient_id,
                        'checktime_id'=>$checktime_id,
                        'form_ids'=>$form_ids
                    ];
                    if($info_type == 0){
                        $save_data['formcontent_id'] = $content_id;
                    }
                    if(empty($old_info)){
                        $save_data['create_user_id'] = $user_id;
                        $save_data['create_time'] = $update_time;
                    }else{
                        $save_data['id'] = $old_info['id'];
                        $save_data['update_user_id'] = $user_id;
                        $save_data['update_time'] = $update_time;
                    }
                    if($info_type == 0){//化验单
                        //获取化验单附件及手动填写数据
                        $all_annexs = $this->LocalService()->itemPatientworkannex->fetchAll([
                            'where'=> [
                                'is_del' => 0,
                                'item_id' => $item_id,
                                'patient_id' => $patient_id,
                                'checktime_id' => $checktime_id,
                                'form_id' => $form_id,
                                'formcontent_id' => $content_id,
                                new Operator('annex_type', Operator::OP_NE, 2)
                            ],
                            'columns'=>['create_time','create_user_id','annex_type','ocr_state','change_type','lock_state','is_unlock','unlock_id','is_lock_operate','form_id','checktime_id','patient_id','patient_form_id'],
                            'order'=>['id']
                        ]);
                        if(!empty($all_annexs)){
                            $save_data['ocr_state'] = $all_annexs[0]['ocr_state'];
                            $save_data['lock_state'] = $all_annexs[0]['lock_state'];
                            $save_data['upload_user'] = $all_annexs[count($all_annexs)-1]['create_user_id'];
                            $save_data['upload_time'] = $all_annexs[count($all_annexs)-1]['create_time'];
                            if(empty($old_info) && empty($save_data['create_user_id'])){
                                $save_data['create_user_id'] = $all_annexs[0]['create_user_id'];
                                $save_data['create_time'] = $all_annexs[0]['create_time'];
                            }
                            if(!empty($old_info) && empty($save_data['update_user_id'])){
                                $save_data['id'] = $old_info['id'];
                                $save_data['update_user_id'] = $all_annexs[count($all_annexs)-1]['create_user_id'];
                                $save_data['update_time'] = $all_annexs[count($all_annexs)-1]['create_time'];
                            }
                            //补单【0 否 1 补单】
                            $save_data['is_new'] = 0;
                            foreach($all_annexs as $all_annex){
                                if($all_annex['annex_type'] == 4 and $all_annex['change_type'] == 0){
                                    $save_data['is_new'] = 1;
                                }
                            }
                            //作废【0 全部 1 作废】
                            $save_data['is_annul'] = 0;
                            if(!empty($save_data['lock_state'])){
                                $annulChange = $this->LocalService()->itemIdentificationresultchange->fetchCol('is_annul','is_del = 0 and is_annul = 1 and patient_form_id = '.$all_annexs[0]['patient_form_id'].' and checktime_id = '.$all_annexs[0]['checktime_id'].' and patientformcontent_id = '.$content_id);
                                $annulChange = !empty($annulChange) ? array_values($annulChange) : [];
                                if(!empty($annulChange) && in_array(1,$annulChange)){
                                    $save_data['is_annul'] = 1;
                                }
                                unset($annulChange);
                            }

                            //申请解锁、解锁未更新、解锁已更新状态
                            $save_data['is_unlock'] = $save_data['is_lock_operate'] = $save_data['is_unlock_update'] = 0;
                            if(!empty($all_annexs[0]['is_unlock'])){//申请解锁
                                $save_data['is_unlock'] = 1;
                                $save_data['is_lock_operate'] = 0;
                                $save_data['is_unlock_update'] = 1;
                            }else{
                                if(empty($save_data['lock_state'])){
                                    if($all_annexs[0]['unlock_id'] != 0 && empty($all_annexs[0]['is_lock_operate'])){//解锁未更新
                                        $save_data['is_unlock'] = 1;
                                        $save_data['is_lock_operate'] = 0;
                                        $save_data['is_unlock_update'] = 2;
                                    }else{
                                        //解锁已更新
                                        if($all_annexs[0]['is_lock_operate'] == 1){
                                            $save_data['is_unlock'] = 1;
                                            $save_data['is_lock_operate'] = 1;
                                            $save_data['is_unlock_update'] = 3;
                                        }
                                    }
                                }
                            }

                            //查质疑信息 按时间展示查化验单质疑信息
                            $questions = $this->LocalService()->itemQuestion->getQuestionInfo(['item_id'=>$item_id,'itemsig_id'=>$itemsig_id,'patient_id'=>$patient_id,'form_id'=>$form_id,'content_id'=>$content_id,'checktime_id'=>$checktime_id,'type'=> 0]);
                            $isShowStar = false;//是否存在未回复信息
                            //SDM图片质疑
                            $save_data['sdm_question'] = 0;
                            $itemQuestionFormStatusData =isset($questions[$form_id][$checktime_id][$patient_id]['itemQuestionForminfo']) && !empty($questions[$form_id][$checktime_id][$patient_id]['itemQuestionForminfo']) ? $questions[$form_id][$checktime_id][$patient_id]['itemQuestionForminfo'] : [];
                            if(!empty($itemQuestionFormStatusData)){
                                // 多条质疑沟通, 有未关闭的就是质疑中
                                $save_data['sdm_question'] = 1;
                                $isShowStar = true;
                                // 是否有未沟通完成的
                                $unComplete = false;
                                foreach ($itemQuestionFormStatusData as $itemQuestionFormStatusInfo) {
                                    if ($itemQuestionFormStatusInfo['question_status'] != '沟通完成') {
                                        $unComplete = true;
                                    }
                                }
                                if ($unComplete == false) {
                                    $save_data['sdm_question'] = 2;
                                    $isShowStar = false;
                                }
                                unset($unComplete);
                                //排除掉沟通完成的 剩下的如果有未回复的 就标绿星
                                if($isShowStar){
                                    $isShowStar = in_array('待确认',ArrayHelper::getColumn($itemQuestionFormStatusData, 'question_status')) ? false : true;
                                }
                            }
                            unset($itemQuestionFormStatusData);
                            //EDC逻辑核查质疑
                            $save_data['edc_question'] = 0;
                            $allFormLogicError =isset($questions[$form_id][$checktime_id][$patient_id]['edcQuestionData']) && !empty($questions[$form_id][$checktime_id][$patient_id]['edcQuestionData']) ? $questions[$form_id][$checktime_id][$patient_id]['edcQuestionData'] : [];
                            if(!empty($allFormLogicError)){
                                $isShowStar = true;
                                $save_data['edc_question'] = 1;
                                // 是否有未关闭的
                                $unComplete = false;
                                $replay_edcquestion_arr = [];//获取查询回复数据的质疑ID
                                foreach ($allFormLogicError as $item) {
                                    if ($item['edcquestion_status'] != '已关闭') {
                                        $unComplete = true;
                                        $replay_edcquestion_arr[] = $item['id'];
                                    }
                                }
                                if ($unComplete == false) {
                                    $save_data['edc_question'] = 2;
                                    $isShowStar = false;
                                }
                                unset($unComplete);
                                //排除掉已关闭的质疑 剩下的如果有未回复的 就标绿星
                                if($isShowStar){
                                    //查询每笔质疑最后操作的记录
                                    $reply_where = [
                                        'is_del' => 0,
                                        [
                                            'or' => [
                                                'platform' => 1,
                                                [
                                                    'platform' => 2,
                                                    [
                                                        'or' => [
                                                            'is_reply' => 1,
                                                            'is_auditor' => 1,
                                                        ]
                                                    ]
                                                ]
                                            ]
                                        ]
                                    ];
                                    if(!empty($replay_edcquestion_arr)){
                                        $reply_where['error_id'] = StringHelper::toArray($replay_edcquestion_arr);
                                    }else{
                                        $reply_where = [
                                            'id' => 0,
                                        ];
                                    }
                                    $errorQuerys = $this->LocalService()->itemPatientFormLogicErrorQuery->fetchAll([
                                        'where'=>$reply_where,
                                        'columns'=>['id','error_id','platform','is_reply','is_auditor'],
                                        'order'=>['id desc']
                                    ]);
                                    unset($reply_where);
                                    if(!empty($errorQuerys)){
                                        $errorQueryArr = [];
                                        foreach($errorQuerys as $errorQueryKey=>$errorQuery){
                                            if(!isset($errorQueryArr[$errorQuery['error_id']])){
                                                $errorQueryArr[$errorQuery['error_id']] = $errorQuery['platform'].'_'.$errorQuery['is_reply'].'_'.$errorQuery['is_auditor'];
                                            }
                                            unset($errorQuerys[$errorQueryKey]);
                                        }
                                        $is_no_replay = 0;
                                        foreach($errorQueryArr as $errorQueryInfo){
                                            if($errorQueryInfo != '2_1_1' && $errorQueryInfo != '2_0_1'){
                                                $is_no_replay = 1;
                                            }
                                        }
                                        if($is_no_replay == 0){
                                            $isShowStar = false;
                                        }
                                        unset($is_no_replay);
                                        unset($errorQueryArr);
                                    }
                                    unset($errorQuerys);
                                }
                                unset($replay_edcquestion_arr);
                            }
                            unset($allFormLogicError);
                            unset($questions);
                            $save_data['noreplay_question'] = $isShowStar ? 1 : 0;
                            unset($isShowStar);

                            //按时间展示排序【6申请解锁/解锁未更新->5作废->4质疑->3解锁已更新->2补图->1未锁定】
                            $save_data['info_order'] = 0;
                            if($save_data['is_annul'] == 1){//作废
                                $save_data['info_order'] = 5;
                            }else{
                                if($save_data['sdm_question'] == 1 || $save_data['edc_question'] == 1){//质疑
                                    $save_data['info_order'] = 4;
                                }else{
                                    if($save_data['is_new'] == 1){//补图
                                        $save_data['info_order'] = 2;
                                    }else{
                                        if(in_array($save_data['is_unlock_update'],[1,2])){//申请解锁、解锁未更新
                                            $save_data['info_order'] = 6;
                                        }else{
                                            //解锁已更新
                                            if($save_data['is_unlock_update'] == 3){
                                                $save_data['info_order'] = 3;
                                            }else{
                                                if(empty($save_data['lock_state'])){//未锁定
                                                    $save_data['info_order'] = 1;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }else{
                            $save_data = [];
                            //无图删除中间表数据
                            if(!empty($old_info)){
                                $this->update(['is_del'=>1],[
                                    'id' => $old_info['id'],
                                ]);
                            }
                        }
                        unset($all_annexs);
                    }else{//常规类识别
                        $is_lock = $this->LocalService()->patientFormContent->getOneFieldVal('is_lock',[
                            'is_del' => 0,
                            'item_id' => $item_id,
                            'patient_id' => $patient_id,
                            'checktime_id' => $checktime_id,
                            'form_id' => StringHelper::toArray($form_ids),
                        ]);
                        $all_imgs = $this->LocalService()->patientFormContentImg->fetchAll([
                            'where'=> [
                                'is_del' => 0,
                                'item_id' => $item_id,
                                'patient_id' => $patient_id,
                                'checktime_id' => $checktime_id,
                                'form_id' => StringHelper::toArray($form_ids),
                                'gco_pool' => $formInfo['gco_pool'],
                                new Operator('info_collect_type', Operator::OP_NE, 3)
                            ],'columns'=>['create_time','create_user_id','is_lock'],
                            'order'=>['id']
                        ]);
                        if(!empty($all_imgs)){
                            $save_data['is_new'] = 0;
                            $save_data['is_annul'] = 0;
                            $save_data['ocr_state'] = 1;
                            $save_data['lock_state'] = !empty($is_lock) || !empty($all_imgs[0]['is_lock']) ? 1 : 0;
                            $save_data['upload_user'] = $all_imgs[count($all_imgs)-1]['create_user_id'];
                            $save_data['upload_time'] = $all_imgs[count($all_imgs)-1]['create_time'];
                            if(empty($old_info) && empty($save_data['create_user_id'])){
                                $save_data['create_user_id'] = $all_imgs[0]['create_user_id'];
                                $save_data['create_time'] = $all_imgs[0]['create_time'];
                            }
                            if(!empty($old_info) && empty($save_data['update_user_id'])){
                                $save_data['id'] = $old_info['id'];
                                $save_data['update_user_id'] = $all_imgs[count($all_imgs)-1]['create_user_id'];
                                $save_data['update_time'] = $all_imgs[count($all_imgs)-1]['create_time'];
                            }

                            //申请解锁、解锁未更新、解锁已更新
                            $save_data['is_unlock'] = $save_data['is_lock_operate'] = $save_data['is_unlock_update'] = 0;
                            $isWaitingUnlock = $this->LocalService()->redisExtend->getRedisInstance()->hget("UNLOCK_SHARE_FORM:{$item_id}", "{$patient_id}:{$checktime_id}:{$formInfo['gco_pool']}");
                            if ($isWaitingUnlock) {
                                $save_data['is_unlock'] = 1;
                                $save_data['is_lock_operate'] = 0;
                                $save_data['is_unlock_update'] = 1;
                            }
                            unset($isWaitingUnlock);
                            if (empty($save_data['lock_state'])) {
                                $status = $this->LocalService()->redisExtend->getRedisInstance()->hGet("SHARE_FORM_IS_UNLOCK_NOT_UPDATED:{$item_id}", "{$patient_id}:{$checktime_id}:{$formInfo['gco_pool']}") ? 2 : 0;
                                if (!$status) {
                                    $status = $this->LocalService()->redisExtend->getRedisInstance()->hGet("SHARE_FORM_IS_UNLOCK_IS_UPDATED:{$item_id}", "{$patient_id}:{$checktime_id}:{$formInfo['gco_pool']}") ? 3 : 0;
                                }
                                if($status == 2){
                                    $save_data['is_unlock'] = 1;
                                    $save_data['is_lock_operate'] = 0;
                                    $save_data['is_unlock_update'] = 2;
                                }
                                if($status == 3){
                                    $save_data['is_unlock'] = 1;
                                    $save_data['is_lock_operate'] = 1;
                                    $save_data['is_unlock_update'] = 3;
                                }
                                unset($status);
                            }
                            unset($isWaitingUnlock);
                            //质疑
                            $formIdArr = explode(',',$form_ids);
                            $questions = $this->LocalService()->itemQuestion->getQuestionInfo(['patient_id'=>[$patient_id],'checktime_id'=>[$checktime_id],'form_id'=>$formIdArr,'type'=> 0,'info_type'=>1]);
                            $isShowStar = false;// 是否展示绿星
                            $itemQuestionFormStatusData = $allFormLogicError = [];
                            foreach($formIdArr as $formId){
                                //SDM质疑
                                $form_sdm_questions = isset($questions[$formId][$checktime_id][$patient_id]['itemQuestionForminfo']) && !empty($questions[$formId][$checktime_id][$patient_id]['itemQuestionForminfo']) ? $questions[$formId][$checktime_id][$patient_id]['itemQuestionForminfo'] : [];
                                if(!empty($form_sdm_questions)){
                                    $itemQuestionFormStatusData = !empty($itemQuestionFormStatusData) ? array_merge($itemQuestionFormStatusData,$form_sdm_questions) : $form_sdm_questions;
                                }
                                unset($form_sdm_questions);
                                //EDC质疑
                                $form_edc_questions = isset($questions[$formId][$checktime_id][$patient_id]['edcQuestionData']) && !empty($questions[$formId][$checktime_id][$patient_id]['edcQuestionData']) ? $questions[$formId][$checktime_id][$patient_id]['edcQuestionData'] : [];
                                if(!empty($form_edc_questions)){
                                    $allFormLogicError = !empty($allFormLogicError) ? array_merge($allFormLogicError,$form_edc_questions) : $form_edc_questions;
                                }
                                unset($form_edc_questions);
                            }
                            unset($questions);
                            //SDM图片质疑
                            $save_data['sdm_question'] = 0;
                            if(!empty($itemQuestionFormStatusData)){
                                // 多条质疑沟通, 有未关闭的就是质疑中
                                $save_data['sdm_question'] = 1;
                                // 是否有未沟通完成的
                                $unComplete = false;
                                $isShowStar = true;
                                foreach ($itemQuestionFormStatusData as $itemQuestionForm) {
                                    if ($itemQuestionForm['question_status'] != '沟通完成') {
                                        $unComplete = true;
                                    }
                                }
                                if ($unComplete == false) {
                                    $save_data['sdm_question'] = 2;
                                    $isShowStar = false;
                                }
                                //排除掉沟通完成的 剩下的如果有未回复的 就标绿星
                                if($isShowStar){
                                    $isShowStar = in_array('待确认',ArrayHelper::getColumn($itemQuestionFormStatusData, 'question_status')) ? false : true;
                                }
                            }
                            unset($itemQuestionFormStatusData);

                            //EDC逻辑核查质疑
                            $save_data['edc_question'] = 0;
                            if(!empty($allFormLogicError)){
                                $save_data['edc_question'] = 1;
                                // 是否有未沟通完成的
                                $unComplete = false;
                                $isShowStar = true;
                                $normal_replay_edcquestion_arr = [];
                                foreach ($allFormLogicError as $allFormLogicErrorInfo) {
                                    if ($allFormLogicErrorInfo['is_closed'] != 1) {
                                        $unComplete = true;
                                        $normal_replay_edcquestion_arr[] = $allFormLogicErrorInfo;
                                    }
                                }
                                if ($unComplete == false) {
                                    $save_data['edc_question'] = 2;
                                    $isShowStar = false;
                                }

                                //排除掉关闭的 剩下的如果有未回复的 就标绿星
                                if($isShowStar){
                                    $isShowStar = !empty($normal_replay_edcquestion_arr) && in_array(0,ArrayHelper::getColumn($normal_replay_edcquestion_arr, 'is_reply')) ? true : false;
                                }
                                unset($normal_replay_edcquestion_arr);
                            }
                            unset($allFormLogicErrors);
                            $save_data['noreplay_question'] = $isShowStar ? 1 : 0;
                            unset($isShowStar);

                            //常规识别【6申请解锁/解锁未更新->5作废->4质疑->3解锁已更新->2补图->1未锁定】
                            $save_data['info_order'] = 0;
                            if($save_data['is_annul'] == 1){//作废
                                $save_data['info_order'] = 5;
                            }else{
                                if($save_data['sdm_question'] == 1 || $save_data['edc_question'] == 1){//质疑
                                    $save_data['info_order'] = 4;
                                }else{
                                    if($save_data['is_new'] == 1){//补图
                                        $save_data['info_order'] = 2;
                                    }else{
                                        if(in_array($save_data['is_unlock_update'],[1,2])){//申请解锁、解锁未更新
                                            $save_data['info_order'] = 6;
                                        }else{
                                            //解锁已更新
                                            if($save_data['is_unlock_update'] == 3){
                                                $save_data['info_order'] = 3;
                                            }else{
                                                if(empty($save_data['lock_state'])){//未锁定
                                                    $save_data['info_order'] = 1;
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                        }else{
                            $save_data = [];
                            //无图删除中间表数据
                            if(!empty($old_info)){
                                $this->update(['is_del'=>1],'id = '.$old_info['id']);
                            }
                        }
                        unset($is_lock);
                        unset($all_imgs);
                    }
                    if(!empty($save_data)){
                        $this->isSetInfo(false)->save($save_data);

                        //判断数据是否重复
                        $repeat_where = [
                            'is_del' => 0,
                            'info_type' => $info_type,
                            'patient_id' => $patient_id,
                            'checktime_id' => $checktime_id,
                            $old_where,
                        ];
                        if($info_type == 0){
                            $repeat_where['formcontent_id'] = $content_id;
                        }
                        $repeat_datas = $this->fetchAll([
                            'where'=>$repeat_where,
                            'columns'=>['id'],
                            'order'=>['id']
                        ]);
                        unset($repeat_where);
                        if(count($repeat_datas) > 1){
                            $delete_repeat_arr = [];
                            foreach($repeat_datas as $repeat_key=>$repeat_data){
                                if($repeat_key > 0){
                                    $delete_repeat_arr[] = $repeat_data['id'];
                                }
                                unset($repeat_datas[$repeat_key]);
                            }
                            $this->update(['is_del'=>1],[
                                'is_del' => 0,
                                'id' => StringHelper::toArray($delete_repeat_arr)
                            ]);
                            unset($delete_repeat_arr);
                        }
                        unset($repeat_datas);
                    }
                    unset($save_data);
                    unset($old_info);
                }

                unset($info_type);
                unset($form_ids);
            }
            unset($formInfo);
        }

        //释放空间
        unset($item_id);
        unset($itemsig_id);
        unset($patient_id);
        unset($checktime_id);
        unset($form_id);
        unset($content_id);
        unset($user_id);
    }

    /**
     * Notes:更新历史患者阶段工作信息【化验单、常规类识别】
     * User: lltyy
     * DateTime: 2025/2/14 15:13
     *
     */
    public function scanData(){
        //获取患者填写的检查点表单信息
        $where = 'is_del = 0 and item_id > 0 and patient_id > 0 and checktime_id > 0 and form_id > 0';
        //获取检查类、常规类识别类表单
        $formWhere = 'is_del = 0 and group_id in ('.FormGroup::CHECK_OCR.','.FormGroup::NORMAL_OCR.')';
        //$formWhere = 'is_del = 0 and group_id in ('.FormGroup::CHECK_OCR.')';
        $form_arr = $this->LocalService()->itemForm->fetchCol('id',$formWhere);
        if(!empty($form_arr)){
            $where .= ' and form_id in ('.implode(',',array_values($form_arr)).')';
        }else{
            $where = 'id < 0';
        }
        unset($form_arr);
        $bool = true;
        $page = 0;
        $limit = 1000;
        $last_id = 0;
        while ($bool) {
            $page++;
            echo "PAGE {$page}：" . PHP_EOL;
            $last_id = $this->mateData($where.' and id > '.$last_id,$limit,0);
            if(!$last_id) $bool = false;
        }
        unset($checkimgArr);
        unset($haveImgCheckArr);
    }

    /**
     * Notes: 执行更新历史患者阶段工作信息【化验单、常规类识别】
     * User: lltyy
     * DateTime: 2025/2/14 15:14
     *
     * @param $where
     * @param int $limit
     * @param int $offset
     * @return int
     */
    public function mateData($where,$limit=0,$offset=0){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','item_id','itemsig_id','patient_id','checktime_id','form_id'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->LocalService()->patientForm->fetchAll($cond);
        $last_id = 0;
        if(!empty($datas)){
            foreach($datas as $dataKey=>$data){
                $last_id = $data['id'];
                $this->updatePatientworkData([
                    'item_id'=>$data['item_id'],
                    'itemsig_id'=>$data['itemsig_id'],
                    'patient_id'=>$data['patient_id'],
                    'checktime_id'=>$data['checktime_id'],
                    'form_id'=>$data['form_id']
                ]);
                unset($datas[$dataKey]);
            }
        }

        //释放空间
        unset($datas);
        unset($cond);
        unset($where);

        return $last_id;

    }

    /**
     * Notes:更新历史患者阶段工作信息【常规类识别】
     * User: lltyy
     * DateTime: 2025/2/14 15:13
     *
     */
    public function scanNormalData(){
        //获取患者填写的检查点表单信息
        $where = 'is_del = 0 and item_id > 0 and patient_id > 0 and checktime_id > 0 and form_id > 0';
        //获取检查类、常规类识别类表单
        $formWhere = 'is_del = 0 and group_id in ('.FormGroup::NORMAL_OCR.')';
        $form_arr = $this->LocalService()->itemForm->fetchCol('id',$formWhere);
        if(!empty($form_arr)){
            $where .= ' and form_id in ('.implode(',',array_values($form_arr)).')';
            //获取共享表单字段
            $formFieldArr = $this->LocalService()->itemFormField->fetchCol('id','is_del = 0 and type = '.FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE.' and form_id in ('.implode(',',array_values($form_arr)).')');
            if(!empty($formFieldArr)){
                $where .= ' and field_id in ('.implode(',',array_values($formFieldArr)).')';
            }else{
                $where = 'id < 0';
            }
        }else{
            $where = 'id < 0';
        }
        unset($form_arr);
        $bool = true;
        $page = 0;
        $limit = 1000;
        $last_id = 0;
        while ($bool) {
            $page++;
            echo "PAGE {$page}：" . PHP_EOL;
            $last_id = $this->mateNormalData($where.' and id > '.$last_id,$limit,0);
            if(!$last_id) $bool = false;
        }
        unset($checkimgArr);
        unset($haveImgCheckArr);
    }

    /**
     * Notes: 执行更新历史患者阶段工作信息【常规类识别】
     * User: lltyy
     * DateTime: 2025/2/14 15:14
     *
     * @param $where
     * @param int $limit
     * @param int $offset
     * @return int
     */
    public function mateNormalData($where,$limit=0,$offset=0){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','item_id','itemsig_id','patient_id','checktime_id','form_id'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->LocalService()->patientFormContentImg->fetchAll($cond);
        $last_id = 0;
        if(!empty($datas)){
            foreach($datas as $dataKey=>$data){
                $last_id = $data['id'];
                $this->updatePatientworkData([
                    'item_id'=>$data['item_id'],
                    'itemsig_id'=>$data['itemsig_id'],
                    'patient_id'=>$data['patient_id'],
                    'checktime_id'=>$data['checktime_id'],
                    'form_id'=>$data['form_id']
                ]);
                unset($datas[$dataKey]);
            }
        }

        //释放空间
        unset($datas);
        unset($cond);
        unset($where);

        return $last_id;

    }


    /**
     * Notes:更新历史患者阶段无图片工作信息
     * User: lltyy
     * DateTime: 2025/2/14 15:13
     *
     */
    public function scanDeleteData(){
        //获取中间表信息
        $where = 'is_del = 0';
        $bool = true;
        $page = 0;
        $limit = 1000;
        $last_id = 0;
        while ($bool) {
            $page++;
            echo "PAGE {$page}：" . PHP_EOL;
            $last_id = $this->mateDeleteData($where.' and id > '.$last_id,$limit,0);
            if(!$last_id) $bool = false;
        }
        unset($checkimgArr);
        unset($haveImgCheckArr);
    }

    /**
     * Notes: 执行更更新历史患者阶段无图片工作信息
     * User: lltyy
     * DateTime: 2025/2/14 15:14
     *
     * @param $where
     * @param int $limit
     * @param int $offset
     * @return int
     */
    public function mateDeleteData($where,$limit=0,$offset=0){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','item_id','itemsig_id','patient_id','checktime_id','form_ids'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->fetchAll($cond);
        $last_id = 0;
        if(!empty($datas)){
            foreach($datas as $dataKey=>$data){
                $last_id = $data['id'];
                $form_id_arr = explode(',',$data['form_ids']);
                $this->updatePatientworkData([
                    'item_id'=>$data['item_id'],
                    'itemsig_id'=>$data['itemsig_id'],
                    'patient_id'=>$data['patient_id'],
                    'checktime_id'=>$data['checktime_id'],
                    'form_id'=>$form_id_arr[0]
                ]);
                unset($datas[$dataKey]);
            }
        }

        //释放空间
        unset($datas);
        unset($cond);
        unset($where);

        return $last_id;

    }

    /**
     * Notes:更新化验单已锁定未回复信息
     * User: lltyy
     * DateTime: 2025/2/14 15:13
     *
     */
    public function scanCheckData(){
        //获取已锁定有未回复信息的化验单表单信息
        $where = [
            'is_del'=>0,
            'info_type'=>0,
            'lock_state'=>1,
            'noreplay_question'=>1,
        ];
        $bool = true;
        $page = 0;
        $limit = 1000;
        $last_id = 0;
        while ($bool) {
            $page++;
            echo "PAGE {$page}：" . PHP_EOL;
            $mateWhere = $where;
            $mateWhere[] = new Operator('id',Operator::OP_GT,$last_id);
            $last_id = $this->mateCheckData($mateWhere,$limit,0);
            if(!$last_id) $bool = false;
        }
        unset($checkimgArr);
        unset($haveImgCheckArr);
    }

    /**
     * Notes: 执行更新化验单已锁定未回复信息
     * User: lltyy
     * DateTime: 2025/2/14 15:14
     *
     * @param $where
     * @param int $limit
     * @param int $offset
     * @return int
     */
    public function mateCheckData($where,$limit=0,$offset=0){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','item_id','itemsig_id','patient_id','checktime_id','form_ids','create_user_id','update_user_id','update_time','create_time'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->fetchAll($cond);
        $last_id = 0;
        if(!empty($datas)){
            foreach($datas as $dataKey=>$data){
                $last_id = $data['id'];
                $this->updatePatientworkData([
                    'item_id'=>$data['item_id'],
                    'itemsig_id'=>$data['itemsig_id'],
                    'patient_id'=>$data['patient_id'],
                    'checktime_id'=>$data['checktime_id'],
                    'form_id'=>$data['form_ids'],
                    'user_id'=>!empty($data['update_user_id']) ? $data['update_user_id'] : $data['create_user_id'],
                    'time'=>!empty($data['update_time']) ? $data['update_time'] : $data['create_time']
                ]);
                unset($datas[$dataKey]);
            }
        }

        //释放空间
        unset($datas);
        unset($cond);
        unset($where);

        return $last_id;

    }

}