<?php

namespace Application\Service\DB\Item;

use Application\Form\item\patient\ImportForm;
use Application\Service\DB\Dictionary\Form;
use Application\Service\Extension\Helper\DataHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\DB\Dictionary\FormGroup;
use Application\Form\item\patient\PatientFormModel;
use Application\Service\Extension\Laminas;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Stdlib\ArrayUtils;

class PatientFormContent extends \Application\Service\DB\AbstractDb
{
    public function __construct($dbAdapter, ContainerInterface $container)
    {
        if (!$this->tableName) {
            $this->tableName = 'yikeen_item_patient_form_content';
        }

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

    /**
     * 表单锁定
     * @param $id
     */
    public function lock($id)
    {
        $this->update(['is_lock' => 1], ['id' => $id]);
    }

    /**
     * 表单解锁
     * @param $id
     */
    public function unlock($id)
    {
        $this->update(['is_lock' => 0], ['id' => $id]);
    }

    /**
     * 把部分未检查改成已开具
     * 拆分检查项, 有的未检查其实有化验单, 所以需要处理一下。
     */
    public function handleIsYc(int $itemId, int $itemSigId)
    {
        $query = Laminas::$serviceManager->patientFormContent->fetchAll([
            'where' => [
                'item_id' => $itemId,
                'itemsig_id' => $itemSigId,
                'is_yc' => 0
            ]
        ]);

        foreach ($query as $item) {
            $hasAnnex = Laminas::$serviceManager->itemPatientworkannex->fetchAll([
                'where' => ['patient_id' => $item['patient_id'], 'form_id' => $item['form_id'], 'checktime_id' => $item['checktime_id']]
            ]);

            if ($hasAnnex) {
                $versionData = Laminas::$serviceManager->itemFormVersion->getField(['form_id' => $item['form_id']], true);
                $originData = StringHelper::jsonDecode($item['data']);
                $generateField = Laminas::$serviceManager->itemForm->getPreviewConfig($item['form_id'], true);
                foreach ($originData as $field => &$data) {
                    if (isset($versionData[$field])) {
                        if ($versionData[$field]['var_name'] === 'ISCHECK') {
                            $checkImgFieldId = $generateField['config'][$field][2][0]['prop'] ?? false;
                            if (!$checkImgFieldId) {
                                die('ERROR');
                            }

                            // 不检查修改成已开具
                            $data = '2';
                            foreach ($hasAnnex as $annex) {
                                // 不检查修改成已开具
                                $originData[$checkImgFieldId][] = [
                                    'name' => pathinfo($annex['annex_path'])['basename'],
                                    'url' => 'https://www.5-mc.cn/common/showPic?path=' . $annex['annex_path'],
                                ];
                            }
                        }
                    }
                }
                echo "项目id -> {$item['item_id']} ; 受试者 -> {$item['patient_id']}; 检查点 -> {$item['checktime_id']}; 表单 -> {$item['form_id']}" . PHP_EOL;
                Laminas::$serviceManager->patientFormContent->update(['is_yc' => 1, 'data' => json_encode($originData)], ['id' => $item['id']]);
            }
        }
    }

    /**
     * 把删除的原图恢复
     *
     */
    public function restorePicBack($itemPatientworkannexIdS='8871,8241,8280,8431',$type=0){
        if(empty($itemPatientworkannexIdS)){
            return 1;
        }
        $itemPatientworkannexWhere['where'] = [
            'id' => explode(',', $itemPatientworkannexIdS),
        ];
        $itemPatientworkannexWhere['columns'] = ['id','patient_id','form_id','item_id','itemsig_id','checktime_id','annex_title','annex_path'];
        $itemPatientworkannexData = Laminas::$serviceManager->itemPatientworkannex->fetchAll($itemPatientworkannexWhere);
        if(empty($itemPatientworkannexData)){
            return 1;
        }
        $arr = [];
        foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>$itemPatientworkannexDataValue) {
            $patientFormContentWhere = [
                'is_del' => 0,
                'patient_id' => $itemPatientworkannexDataValue['patient_id'],
                'form_id' => $itemPatientworkannexDataValue['form_id'],
                'item_id' => $itemPatientworkannexDataValue['item_id'],
                'itemsig_id' => $itemPatientworkannexDataValue['itemsig_id'],
                'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
            ];
            $patientFormContentDataField = Laminas::$serviceManager->patientFormContent->getOneFieldVal('data',$patientFormContentWhere);
            $arr[$itemPatientworkannexDataKey]['content'] = $patientFormContentDataField;
            $arr[$itemPatientworkannexDataKey]['content_where'] = $patientFormContentWhere;
            if (!empty($patientFormContentDataField)){
                $patientFormContentDataFieldData = json_decode($patientFormContentDataField,true);
                if (!empty($patientFormContentDataFieldData)){
                    $versionData = Laminas::$serviceManager->itemFormVersion->getField(['form_id' => $itemPatientworkannexDataValue['form_id']], true);
                    foreach ($patientFormContentDataFieldData as $k => $datum) {
                        $field = DataHelper::getFieldId($k);
                        $picArr = [];
                        if (isset($versionData[$field]['name']) && $versionData[$field]['name'] === '化验单') {
                            $originData = $patientFormContentDataFieldData[$k];
                            if (!empty($originData)){
                                foreach ($originData as $key=>$value) {
                                    $originData[$key]['url'] = str_replace("https://www.5-mc.cn","https://www.scitrials.cn",$value['url']);
                                }
                                $patientFormContentDataFieldData[$k]= $originData;
                            }

                        }
                    }
                    $patientFormContentDataFields = json_encode($patientFormContentDataFieldData);
                    Laminas::$serviceManager->patientFormContent->update(['data'=>$patientFormContentDataFields],$patientFormContentWhere);

                }
            }

        }
        echo '<pre>';print_r($arr);die;

    }

    public function restorePicBa($itemPatientworkannexIdS='8871,8241,8280,8431',$type=0){
        $day = date('Y-m-d');
        if ($day != '2023-02-22'){
            if($itemPatientworkannexIdS == '8871,8241,8280,8431'){
                return 1;
            }
        }
        if(empty($itemPatientworkannexIdS)){
            return 1;
        }
        $itemPatientworkannexWhere['where'] = [
            'id' => explode(',', $itemPatientworkannexIdS),
        ];
        $itemPatientworkannexWhere['columns'] = ['id','patient_id','form_id','item_id','itemsig_id','checktime_id','annex_title','annex_path'];
        $itemPatientworkannexData = Laminas::$serviceManager->itemPatientworkannex->fetchAll($itemPatientworkannexWhere);
        if(empty($itemPatientworkannexData)){
            return 1;
        }
        $arr = [];
        foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>$itemPatientworkannexDataValue) {
            $patientFormContentWhere = [
                'is_del' => 0,
                'patient_id' => $itemPatientworkannexDataValue['patient_id'],
                'form_id' => $itemPatientworkannexDataValue['form_id'],
                'item_id' => $itemPatientworkannexDataValue['item_id'],
                'itemsig_id' => $itemPatientworkannexDataValue['itemsig_id'],
                'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
            ];
            $patientFormContentDataField = Laminas::$serviceManager->patientFormContent->getOneFieldVal('data',$patientFormContentWhere);
            $arr[$itemPatientworkannexDataKey]['content'] = $patientFormContentDataField;
            $arr[$itemPatientworkannexDataKey]['content_where'] = $patientFormContentWhere;
            if (!empty($patientFormContentDataField)){
                $patientFormContentDataFieldData = json_decode($patientFormContentDataField,true);

                if (!empty($patientFormContentDataFieldData)){
                    $versionData = Laminas::$serviceManager->itemFormVersion->getField(['form_id' => $itemPatientworkannexDataValue['form_id']], true);
                    foreach ($patientFormContentDataFieldData as $k => $datum) {
                        $field = DataHelper::getFieldId($k);
                        $picArr = [];
                        if (isset($versionData[$field]['name']) && $versionData[$field]['name'] === '化验单') {
                            $originData = StringHelper::jsonDecode($patientFormContentDataFieldData[$k]);
                            $urlPath = 'https://www.scitrials.cn';
                            if (!empty($type)) $urlPath = 'https://www.5-mc.cn';
                            if (!empty($itemPatientworkannexDataValue['annex_path'])){
                                $picArr[] = [
                                    'name' => pathinfo($itemPatientworkannexDataValue['annex_path'])['basename'],
                                    'url' => $urlPath.'/common/showPic?path=' . $itemPatientworkannexDataValue['annex_path'],
                                ];
                            }

                            $patientFormContentDataFieldData[$k]= array_merge($originData,$picArr);

                        }
                    }
                    $arr[$itemPatientworkannexDataKey]['patientFormContentWhere'][] = $patientFormContentDataFieldData;
                    $patientFormContentDataFields = json_encode($patientFormContentDataFieldData);
                    Laminas::$serviceManager->patientFormContent->update(['data'=>$patientFormContentDataFields],$patientFormContentWhere);

                }
            }
            Laminas::$serviceManager->itemPatientworkannex->update(['is_del'=>0],[
                'id' => $itemPatientworkannexDataValue['id']
            ]);
        }
    }

    /**
     * Notes: 获取患者每个检查点下的访视日期
     * User: lltyy
     * DateTime: 2024/6/26 17:49
     *
     * @param array $info
     */
    public function fetchChecktimeDate($info = []){
        $item_id = isset($info['item_id']) && !empty($info['item_id']) ? $info['item_id'] : 0;
        $patient_id = isset($info['patient_id']) && !empty($info['patient_id']) ? $info['patient_id'] : 0;
        $arr = [];
        if(!empty($item_id)){
            //获取该项目下的访视日期的表单
            $filedFormDatas = $this->LocalService()->itemFormField->fetchDataByKey([
                'is_del' => 0,
                'item_id' => $item_id,
                'is_booked_time' => 1,
            ],['id','form_id'],'form_id',1);
            $form_arr = !empty($filedFormDatas) ? array_keys($filedFormDatas) : [];

            //获取该患者该表单下的访视日期数据
            $content_where = [
                'is_del' => 0,
            ];
            if(!empty($form_arr)){
                $content_where['form_id'] = $form_arr;
            }else{
                $content_where = [
                    new Operator('id', Operator::OP_LT, 0),
                ];
                $content_where = 'id < 0';
            }
            if(!empty($patient_id)){
                $content_where['patient_id'] = $patient_id;
            }
            $datas = $this->fetchAll(['where'=>$content_where,'columns'=>['patient_id','form_id','data']]);

            unset($content_where);
            unset($form_arr);
            if(!empty($datas)){
                foreach($datas as $data){
                    $data_patient = $data['patient_id'];
                    $data_form = $data['form_id'];
                    $data_contents = json_decode($data['data'],true);
                    $formDateField = isset($filedFormDatas[$data_form]) && !empty($filedFormDatas[$data_form]) ? array_column($filedFormDatas[$data_form],'id') : [];
                    $data_patientchecktime = isset($data_contents['patientchecktime_id']) && !empty($data_contents['patientchecktime_id']) ? $data_contents['patientchecktime_id'] : 0;
                    if(!empty($data_patientchecktime)){
                        unset($data_contents['patientchecktime_id']);
                        foreach($data_contents as $data_content_key=>$data_content){
                            if(!empty($data_content)){
                                $data_content_key_arr = explode('-',$data_content_key);
                                if(count($data_content_key_arr) > 1){
                                    $endKey = count($data_content_key_arr)-1;
                                    unset($data_content_key_arr[$endKey]);
                                }
                                $intersects = !empty($formDateField) && !empty($data_content_key_arr) ? array_values(array_intersect($data_content_key_arr, $formDateField)) : [];
                                if(!empty($intersects)){
                                    $arr[$data_patient][$data_patientchecktime][] = $data_content;
                                }
                            }
                        }
                    }
                    unset($formDateField);
                    unset($data_contents);
                }
            }
            unset($datas);
            unset($filedFormDatas);

            if(!empty($arr)){
                foreach ($arr as $arr_patient=>$arr_patient_times){
                    foreach($arr_patient_times as $arr_patient_time=>$arr_patient_dates){
                        array_unique($arr_patient_dates);
                        $arr[$arr_patient][$arr_patient_time] = implode('、',$arr_patient_dates);
                    }
                }
            }
        }
        if(!empty($patient_id)){
            $arr = isset($arr[$patient_id]) && !empty($arr[$patient_id]) ? $arr[$patient_id] : [];
        }
        return $arr;
    }

    /**
     * Notes:获取指定条件下的数据
     * User: lltyy
     * DateTime: 2024/5/15 9:20
     *
     * @param $where 条件
     * @param $columns 字段
     * @param string $key 键值
     * @param int $is_more 是否有多笔数据【0 否 1 是】
     * @return array
     */
    public function fetchDataByKey($where,$columns,$order=['id'],$key='id',$is_more = 0){
        $datas = [];
        $cond = [
            'where'=>$where,
            'columns'=>$columns,
            'order'=>$order
        ];
        $infoDatas = $this->fetchAll($cond);
        if(!empty($infoDatas)){
            foreach($infoDatas as $infoKey=>$infoData){
                $data_key = isset($infoData[$key]) && !empty($infoData[$key]) ? $infoData[$key] : '';
                if($is_more == 1){
                    $datas[$data_key][] = $infoData;
                }else{
                    $datas[$data_key] = $infoData;
                }
                unset($infoDatas[$data_key]);
            }
        }
        unset($cond);
        unset($infoDatas);

        return $datas;
    }

    /**
     * Notes:查询一对多表单数据
     * @param
     * @return
     * @author haojinhua
     * @date 2024-07-26
     */
    public function fetchRelationArr(array $conditionsString = []){
        ini_set('memory_limit', '512M');
        $where = ArrayUtils::merge([
            'is_del' => 0,
        ], $conditionsString ?: []);

        $checktime_datas = [];
        $nochecktime_datas = [];
        $cond = [
            'where'=>$where,
            'columns'=>['id','patient_id','form_id','item_id','itemsig_id','checktime_id'],
            'order'=>['id']
        ];
        $infoDatas = $this->fetchAll($cond);
        if(!empty($infoDatas)){
            foreach ($infoDatas as $infoData){
                $checktime_datas[$infoData['patient_id']][$infoData['checktime_id']][$infoData['itemsig_id']][$infoData['form_id']][] = $infoData['id'];
                $nochecktime_datas[$infoData['patient_id']][$infoData['itemsig_id']][$infoData['form_id']][] = $infoData['id'];
            }
        }

        unset($infoDatas);
        return [$checktime_datas,$nochecktime_datas];
    }

    /**
     * Notes: 统计
     * @param
     * @return
     * @author haojinhua
     * @date 2024-09-02
     */
    public function getsaeNum($where){
        $res = [];
        $where = !empty($where) ? $where : ['is_del' => 0];
        $cond = [
            'where'=>$where,
            'columns'=>['id','patient_id','form_id','item_id','itemsig_id'],
            'order'=>['id']
        ];
        $infoDatas = $this->fetchAll($cond);
        if(!empty($infoDatas)){
            foreach ($infoDatas as $infoData){
                $res[$infoData['item_id']][$infoData['itemsig_id']][$infoData['form_id']]['allnum'] = !empty($res[$infoData['item_id']][$infoData['itemsig_id']][$infoData['form_id']]['allnum']) ? $res[$infoData['item_id']][$infoData['itemsig_id']][$infoData['form_id']]['allnum'] : 0;
                $res[$infoData['item_id']][$infoData['itemsig_id']][$infoData['form_id']][$infoData['patient_id']]['patientnum'] = !empty($res[$infoData['item_id']][$infoData['itemsig_id']][$infoData['form_id']][$infoData['patient_id']]['patientnum']) ? $res[$infoData['item_id']][$infoData['itemsig_id']][$infoData['form_id']][$infoData['patient_id']]['patientnum'] : 0;
                $res[$infoData['item_id']][$infoData['itemsig_id']][$infoData['form_id']]['allnum'] ++;
                $res[$infoData['item_id']][$infoData['itemsig_id']][$infoData['form_id']][$infoData['patient_id']]['patientnum'] ++;
            }
        }

        return $res;
    }

    public function fetchFormPatient($arr = []){
        $item_id = isset($arr['item_id']) && !empty($arr['item_id']) ? $arr['item_id'] : [];
        $itemsig_id = isset($arr['itemsig_id']) && !empty($arr['itemsig_id']) ? $arr['itemsig_id'] : [];
        $form_id = isset($arr['form_id']) && !empty($arr['form_id']) ? $arr['form_id'] : [];
        $key_arr = isset($arr['key']) && !empty($arr['key']) ? $arr['key'] : ['itemsig_id'];

        $where = [
            'is_del' => 0,
        ];
        if(!empty($item_id)){
            $where['item_id'] = $item_id;        }
        if(!empty($itemsig_id)){
            $where['itemsig_id'] = $itemsig_id;
        }
        if(!empty($form_id)){
            $where['form_id'] = $form_id;
        }
        $datas = $this->fetchAll([
            'where'=>$where,
            'columns'=>['patient_id','item_id','itemsig_id','form_id']
        ]);
        $info = [];
        if(!empty($datas)){
            foreach($datas as $dataKey=>$data){
                $data_key_str = '';
                foreach($key_arr as $key){
                    $data_key = isset($data[$key]) && !empty($data[$key]) ? $data[$key] : 0;
                    $data_key_str .= $data_key.'_';
                }
                $data_key_str = !empty($data_key_str) ? trim($data_key_str,'_') : '0';
                $info[$data_key_str] = isset($info[$data_key_str]) && !empty($info[$data_key_str]) ? $info[$data_key_str] : [];
                if(!in_array($data['patient_id'],$info[$data_key_str])){
                    $info[$data_key_str][] = $data['patient_id'];
                }
                unset($datas[$dataKey]);
            }
        }

        return $info;
    }


    /**
     * Notes: 获取表单操作原因 取最新的操作原因数据用
     * @param
     * @return
     * @author haojinhua
     * @date 2024-10-14
     */
    public function getFormReason(){
        ini_set('memory_limit', '512M');
        $datas = [];
        $where = ['is_del' => 0];
        $cond  = [
            'where'=>$where,
            'columns'=>['patient_id','form_id','item_id','itemsig_id','checktime_id','data'],
            'order'=>['id']
        ];
        $infoDatas = $this->fetchAll($cond);
        if(!empty($infoDatas)){
            foreach ($infoDatas as $infoData){
                $e_info = $infoData['data'];
                // 解码 JSON 字符串为 PHP 数组
                $edit_info = json_decode($e_info, true);
                if(!empty($edit_info) && isset($edit_info['edit_reason']) && !empty($edit_info['edit_reason'])){
                    $edit_reasons  = json_decode($edit_info['edit_reason'], true);
                    foreach ($edit_reasons as $edit_reason){
                        $datas[$infoData['item_id']][$infoData['itemsig_id']][$infoData['checktime_id']][$infoData['form_id']][$infoData['patient_id']][$edit_reason['prop']] = $edit_reason['value'];
                    }
                }
            }
        }

        return $datas;
    }


    /**
     * Notes:识别数据 - 匹配
     * User: lltyy
     * DateTime: 2023/5/12 14:51
     *
     */
    public function scanAbnormalJudge(array $arr=[]) {
        $item_id = isset($arr['item_id']) && !empty($arr['item_id']) ? $arr['item_id'] : [];
        $itemsig_id = isset($arr['itemsig_id']) && !empty($arr['itemsig_id']) ? $arr['itemsig_id'] : [];
        $patient_id = isset($arr['patient_id']) && !empty($arr['patient_id']) ? $arr['patient_id'] : [];

        //信息匹配
        $abnormalJudgeArr = [];
        $where = 'id < 0';
        //获取常规类（识别）开启CS/AE的表单内容对应的检查项
        $itemcheckname_where = [
            'is_del' => 0,
            new Operator('form_field_id', Operator::OP_GT, 0),
        ];
        if(!empty($item_id)){
            $itemcheckname_where['item_id'] = $item_id;
        }
        $itemcheckname_field_arr = $this->LocalService()->itemCheckname->fetchCol('form_field_id',$itemcheckname_where);
        if(!empty($itemcheckname_field_arr)) {
            //获取对应的异常判断信息
            $patientFormcontentIdArr = [];
            $abnormalJudgeWhere = [
                'is_del' => 0,
                'item_checkname_id' => array_values(array_keys($itemcheckname_field_arr)),
                new Operator('patientformcontent_id', Operator::OP_GT, 0),
            ];
            if (!empty($item_id)) {
                $abnormalJudgeWhere['item_id'] = $item_id;
            }
            if (!empty($itemsig_id)) {
                $abnormalJudgeWhere['itemsig_id'] = $itemsig_id;
            }
            if (!empty($patient_id)) {
                $abnormalJudgeWhere['patient_id'] = $patient_id;
            }
            $abnormalJudgeDatas = $this->LocalService()->itemIdentificationresultchange->fetchAll([
                'where' => $abnormalJudgeWhere,
                'columns' => ['item_checkname_id', 'patientformcontent_id', 'is_normal_type', 'update_time', 'update_user_id'],
                'order' => ['update_time']
            ]);
            unset($abnormalJudgeWhere);
            if (!empty($abnormalJudgeDatas)) {
                foreach ($abnormalJudgeDatas as $abnormalJudgeKey => $abnormalJudgeData) {
                    $abnormalJudgeArr[$abnormalJudgeData['patientformcontent_id']][$abnormalJudgeData['item_checkname_id']] = $abnormalJudgeData;
                    $patientFormcontentIdArr[] = $abnormalJudgeData['patientformcontent_id'];
                    unset($abnormalJudgeDatas[$abnormalJudgeKey]);
                }
            }
            unset($abnormalJudgeDatas);
            //更新患者进度表单内容异常判断信息
            //更新患者进度表单内容异常判断信息
            if(!empty($patientFormcontentIdArr)) {
                $where = [
                    'is_del' => 0,
                    'id' => $patientFormcontentIdArr,
                ];
            }
            unset($patientFormcontentIdArr);
        }

        $bool = true;
        $page = 0;
        $limit = 1000;
        $last_id = 0;
        while ($bool) {
            $page++;
            echo "PAGE {$page}：" . PHP_EOL;
            $last_id = $this->updateAbnormalJudge(ArrayUtils::merge($where, [
                new Operator('id', Operator::OP_GT, $last_id)
            ]), $limit,0,$itemcheckname_field_arr,$abnormalJudgeArr);
            if(!$last_id) $bool = false;
        }
        unset($wordDatas);
    }

    /**
     * Notes: 更新历史常规类（识别）异常判断信息
     * User: lltyy
     * DateTime: 2024/10/23 9:41
     *
     * @param array $arr
     * @return int
     */
    public function updateAbnormalJudge($where,$limit=0,$offset=0,&$itemcheckname_field_arr,&$abnormalJudgeArr=[]){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','data','create_time','create_user_id','update_time','update_user_id'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $patientFormcontentDatas = $this->fetchAll($cond);
        $last_id = 0;
        if(!empty($patientFormcontentDatas)){
            foreach($patientFormcontentDatas as $patientFormcontentKey=>$patientFormcontentData){
                $last_id = $patientFormcontentData['id'];
                $patientFormcontentData_content = json_decode($patientFormcontentData['data'],true);
                $is_edit = 0;
                $update_data = [
                    'create_user_id'=>$patientFormcontentData['create_user_id'],
                    'create_time'=>$patientFormcontentData['create_time'],
                    'update_user_id'=>$patientFormcontentData['update_user_id'],
                    'update_time'=>$patientFormcontentData['update_time'],
                ];
                $content_childData = [];
                if(isset($abnormalJudgeArr[$patientFormcontentData['id']]) && !empty($abnormalJudgeArr[$patientFormcontentData['id']])){
                    foreach($abnormalJudgeArr[$patientFormcontentData['id']] as $abnormalJudgeCheckId=>$abnormalJudgeCheck){
                        $abnormalJudgeCheckField = isset($itemcheckname_field_arr[$abnormalJudgeCheckId]) && !empty($itemcheckname_field_arr[$abnormalJudgeCheckId]) ? $itemcheckname_field_arr[$abnormalJudgeCheckId] : 0;
                        if(!empty($abnormalJudgeCheckField)){
                            $is_edit = 1;
                            $content_childData[$abnormalJudgeCheckField] = [
                                'field_id'=>$abnormalJudgeCheckField,
                                'normal_type'=>$abnormalJudgeCheck['is_normal_type']
                            ];
                            if(!empty($abnormalJudgeCheck['update_time']) && $abnormalJudgeCheck['update_time'] > $update_data['update_time']){
                                $update_data['update_user_id'] = $abnormalJudgeCheck['update_user_id'];
                                $update_data['update_time'] = $abnormalJudgeCheck['update_time'];
                            }
                        }
                        unset($abnormalJudgeCheckField);
                    }
                    unset($abnormalJudgeArr[$patientFormcontentData['id']]);
                }
                if($is_edit == 1){
                    $patientFormcontentData_content['childData'] = json_encode($content_childData);
                    $update_data['data'] = json_encode($patientFormcontentData_content);
                    $this->update($update_data,'id = '.$patientFormcontentData['id']);
                }
                unset($content_childData);
                unset($update_data);
                unset($patientFormcontentData_content);
                unset($is_edit);
                unset($patientFormcontentDatas[$patientFormcontentKey]);
            }
        }
        unset($cond);
        unset($patientFormcontentDatas);

        return $last_id;
    }

    /**
     * Notes: 获取人员操作合并用药医嘱数
     * User: lltyy
     * DateTime: 2024/12/2 8:02
     *
     * @param array $info
     */
    public function getUserMergeMedicalCount(array $info = []){
        $start_date_time = isset($info['start_date_time']) && !empty($info['start_date_time']) ? $info['start_date_time'] : strtotime(date('Y-m-d').' 00:00:00');
        $end_date_time = isset($info['end_date_time']) && !empty($info['end_date_time']) ? $info['end_date_time'] : strtotime(date('Y-m-d', strtotime('+1 day')).' 00:00:00');
        $item_id_arr = isset($info['item_ids']) && !empty($info['item_ids']) ? $info['item_ids'] : [];
        $arr = [];
        //获取信息
        $where = ['is_del' => 0];
        if(!empty($start_date_time) && !empty($end_date_time)){
             $where[] = new Operator('create_time', Operator::OP_GTE, $start_date_time);
             $where[] = new Operator('create_time', Operator::OP_LT, $end_date_time);
        }
        $form_where = [
            'is_del' => 0,
            'type' => 1,
            'var_name' => 'CM',
            new Operator('item_id', Operator::OP_GT, 0),
        ];
        if(isset($info['item_ids'])){
            if(!empty($item_id_arr)){
                $where['item_id'] = $item_id_arr;
                $form_where['item_id'] = $item_id_arr;
            }else{
                $where = $form_where = [
                    'id' => 0,
                ];
            }
        }
        $form_arr = $this->LocalService()->itemForm->fetchCol('id',$form_where);
        unset($form_where);
        if(!empty($form_arr)){
            $where['form_id'] = array_values($form_arr);
        }else{
            $where = [
                'id' => 0,
            ];
        }
        unset($form_arr);
        $datas = $this->fetchAll([
            'where'=>$where,
            'columns'=>['id','create_user_id','create_time','update_user_id','update_time']
        ]);
        unset($where);
        if(!empty($datas)){
            foreach($datas as $dataKey=>$data){
                $data_create = !empty($data['create_user_id']) ? $data['create_user_id'] : 0;
                $data_update = !empty($data['update_user_id']) ? $data['update_user_id'] : 0;
                $create_add = $update_add = 0;
                if(!empty($start_date_time) && !empty($end_date_time)) {
                    if (!empty($data_create) && $data['create_time'] >= $start_date_time && $data['create_time'] < $end_date_time) {
                        $create_add = 1;
                    }
                }else {
                    if(!empty($data_create)){
                        $create_add = 1;
                    }
                }
                if($create_add == 1 && $update_add == 1){
                    $arr[$data_create] = isset($arr[$data_create]) && !empty($arr[$data_create]) ? $arr[$data_create] : 0;
                    $arr[$data_create] += 1;
                    if($data_create != $data_update){
                        $arr[$data_update] = isset($arr[$data_update]) && !empty($arr[$data_update]) ? $arr[$data_update] : 0;
                        $arr[$data_update] += 1;
                    }
                }else {
                    if($create_add == 1){
                        $arr[$data_create] = isset($arr[$data_create]) && !empty($arr[$data_create]) ? $arr[$data_create] : 0;
                        $arr[$data_create] += 1;
                    }
                    if($update_add == 1){
                        $arr[$data_update] = isset($arr[$data_update]) && !empty($arr[$data_update]) ? $arr[$data_update] : 0;
                        $arr[$data_update] += 1;
                    }
                }
                unset($data_create);
                unset($data_update);
                unset($update_add);
                unset($create_add);
                unset($datas[$dataKey]);
            }
        }
        unset($datas);

        return $arr;
    }

    /**
     * Notes: 更新SAE数据完成状态
     * User: lltyy
     * DateTime: 2025/4/3 11:03
     *
     */
    public function scanData(){
        //获取患者填写的检查点表单信息
        $where = [
            'is_del' => 0,
        ];
        //获取检查类、常规类识别类表单
        $formWhere = [
            'is_del' => 0,
            'group_id' => FormGroup::SAE,
        ];
        $form_arr = $this->LocalService()->itemForm->fetchCol('finish_condition',$formWhere);
        unset($formWhere);
        if(!empty($form_arr)){
            $where['form_id'] = array_values(array_keys($form_arr));
        }else{
            $where = [
                'id' => 0
            ];
        }
        $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,$form_arr);
            if(!$last_id) $bool = false;
        }
        unset($form_arr);
    }

    /**
     * Notes: 更新SAE数据完整性
     * User: lltyy
     * DateTime: 2025/4/3 11:03
     *
     * @param $where
     * @param int $limit
     * @param int $offset
     * @return int
     */
    public function mateData($where,$limit=0,$offset=0,&$form_arr=[]){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','item_id','itemsig_id','patient_id','checktime_id','form_id','data','create_user_id','create_time','update_user_id','update_time','is_complete'],
            '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'];
                $old_complete = $data['is_complete'];
                $model = new PatientFormModel();
                $is_complete = $model->getIsComplete(json_decode($data['data'],true));
                if($is_complete != $old_complete){
                    $this->isSetInfo(false)->update(['is_complete'=>$is_complete,'update_user_id'=>$data['update_user_id'],'update_time'=>$data['update_time']],[
                        'id' => $data['id']
                    ]);
                }

                //更新患者表单信息表
                $fieldData = [
                    'form_id' => $data['form_id'],
                    'item_id' => $data['item_id'],
                    'patient_id' => $data['patient_id'],
                    'itemsig_id' => $data['itemsig_id'],
                    'checktime_id' => 0,
                    'is_complete' => $is_complete,
                    'start_at' => 0,
                    'end_at' => 0,
                    'is_del' => 0
                ];
                if($form_arr[$data['form_id']] == Form::FORM_FINISH_CONDITION_ALL){//全部填写
                    //判断是否存在未填写完成的信息
                    $noCompleteCount = $this->getCount([
                        'is_del' => 0,
                        'is_complete' => 0,
                        'patient_id' => $data['patient_id'],
                        'form_id' => $data['form_id'],
                    ]);
                    if(!empty($noCompleteCount)){
                        $fieldData['is_complete'] = 0;
                    }
                    unset($noCompleteCount);
                }
                $patientForm = $this->LocalService()->patientForm->memoryCache()->fetchOne([
                    'where' => [
                        'form_id' => $data['form_id'],
                        'item_id' => $data['item_id'],
                        'patient_id' => $data['patient_id'],
                        'is_del' => 0
                    ]
                ]);
                if (!empty($patientForm)) {
                    $fieldData['update_user_id'] = !empty($data['update_user_id']) ? $data['update_user_id'] : $data['create_user_id'];
                    $fieldData['update_time'] = !empty($data['update_user_id']) ? $data['update_time'] : $data['create_time'];
                    $this->LocalService()->patientForm->isSetInfo(false)->update($fieldData, 'id = '.$patientForm['id']);
                } else {
                    $fieldData['create_user_id'] = $data['create_user_id'];
                    $fieldData['create_time'] = $data['create_time'];
                    $this->LocalService()->patientForm->isSetInfo(false)->save($fieldData);
                }
                unset($patientForm);
                unset($patientFormId);
                unset($fieldData);
                unset($model);
                unset($old_complete);
                unset($is_complete);
                unset($datas[$dataKey]);
            }
        }

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

        return $last_id;

    }

    public function importDataExecute()
    {
        $keys = Laminas::$serviceManager->redisExtend->getRedisInstance(6)->keys('task:improtExecute:*');

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

}
