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

namespace Application\Service\DB\Collect;

use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\DataHelper;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Ddl\Column\Datetime;
use Laminas\Db\Sql\Predicate\NotIn;
use Laminas\Db\Sql\Predicate\Operator;

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

    /**
     * Notes: 获取指定条件下的数据
     * User: lltyy
     * DateTime: 2025/8/26 10:49
     *
     * @param $where //查询条件
     * @param $columns //查询字段
     * @param $order //排序值
     * @param array $key_arr //【键值=》数据数量】
     * @return array
     */
    public function fetchDataByKey($where,$columns,$order,$key_arr=[]){
        $datas = [];
        $cond = [
            'where'=>$where,
            'columns'=>$columns,
            'order'=>$order
        ];
        $infoDatas = $this->fetchAll($cond);
        unset($cond);
        if(!empty($infoDatas)){
            foreach($infoDatas as $infoDataKey=>$infoData){
                foreach($key_arr as $key=>$key_num){
                    if($key_num == 1){//一对多
                        $datas[$key][$infoData[$key]][] = $infoData;
                    }
                    if($key_num == 1){//一对一
                        $datas[$key][$infoData[$key]] = $infoData;
                    }
                }
                unset($infoDatas[$infoDataKey]);
            }
        }
        unset($key_arr);
        unset($infoDatas);
        return $datas;
    }

    /**
     * Notes: 新增受试者用药信息
     * User: lltyy
     * DateTime: 2025/8/26 11:29
     *
     * @param array $params
     */
    public function savePatientdrugData(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
        $annex_id = isset($params['annex_id']) && !empty($params['annex_id']) ? $params['annex_id'] : 0;//附件ID
        $drug_id = isset($params['drug_id']) && !empty($params['drug_id']) ? $params['drug_id'] : [];//药物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) && (!empty($annex_id) || !empty($drug_id))){
            $send_drug = !empty($drug_id) ? $drug_id : [];
            if(!empty($annex_id)){
                //获取该附件下已匹配未核查的药物信息
                $send_drug = $this->LocalService()->doctoradviceOriginal->fetchCol('drug_id',['is_del'=>0,'annex_id'=>$annex_id,new Operator('drug_id',Operator::OP_GT,0)]);
                $send_drug = !empty($send_drug) ? array_values(array_unique(array_values($send_drug))) : [];
            }
            if(!empty($send_drug)){
                $drug_arr = $item_drug_arr = [];//获取药物对应的通用名信息及别名信息
                //判断该项目下是否有设置药物信息
                $all_itemdrug_arr = [];
                $item_drug_datas = $this->LocalService()->collectItemdrug->fetchAll([
                    'where'=>['is_del'=>0,'item_id'=>$item_id],
                    'columns'=>['drug_id','parent_drug'],
                    'order'=>['parent_drug','id']
                ]);
                if(!empty($item_drug_datas)){
                    foreach($item_drug_datas as $item_drug_key=>$item_drug_data){
                        $item_parent_drug = !empty($item_drug_data['parent_drug']) ? $item_drug_data['parent_drug'] : $item_drug_data['drug_id'];
                        if(in_array($item_drug_data['drug_id'],$send_drug) || in_array($item_parent_drug,$send_drug)){
                            $item_drug_arr[$item_drug_data['drug_id']] = $item_parent_drug;
                        }
                        $all_itemdrug_arr[$item_drug_data['drug_id']] = $item_parent_drug;
                        unset($item_parent_drug);
                        unset($item_drug_datas[$item_drug_key]);
                    }
                }
                unset($item_drug_datas);

                //获取字典项药物信息
                $drug_where = [
                    'is_del'=>0
                ];
                //获取药物的通用名信息
                $parent_drug_arr = $send_drug;
                $parent_drug_id = $this->LocalService()->collectDrug->fetchCol('parent_drug',['is_del'=>0,['id'=>$send_drug,new Operator('parent_drug',Operator::OP_GT,0)]]);
                if(!empty($parent_drug_id)){
                    $parent_drug_arr = array_merge($parent_drug_arr,array_values(array_unique(array_values($parent_drug_id))));
                    $parent_drug_arr = array_values(array_unique($parent_drug_arr));
                }
                unset($parent_drug_id);
                $drug_where['or'] = [
                    ['id'=>$parent_drug_arr],
                    ['parent_drug'=>$parent_drug_arr]
                ];
                unset($parent_drug_arr);
                $drug_datas = $this->LocalService()->collectDrug->fetchAll([
                    'where'=>$drug_where,
                    'columns'=>['id','parent_drug'],
                    'order'=>['parent_drug','id']
                ]);
                unset($drug_where);
                if(!empty($drug_datas)){
                    foreach($drug_datas as $drug_key=>$drug_data){
                        $parent_drug = !empty($drug_data['parent_drug']) ? $drug_data['parent_drug'] : $drug_data['id'];
                        if(isset($all_itemdrug_arr[$drug_data['id']]) && !empty($all_itemdrug_arr[$drug_data['id']])){
                            $parent_drug = $all_itemdrug_arr[$drug_data['id']];
                        }
                        $drug_arr[$drug_data['id']] = $parent_drug;
                        unset($parent_drug);
                        unset($drug_datas[$drug_key]);
                    }
                }
                unset($drug_datas);
                unset($all_itemdrug_arr);

                //获取CM及识别信息
                $cmAndOcrData = $this->fetchCmAndOcrPatientDrugDatas([
                    'item_id' => $item_id,
                    'patient_id' => $patient_id,
                    'drug_arr' => $drug_arr,
                    'item_drug_arr' => $item_drug_arr
                ]);
                //更新受害者用药情况
                $update_drug_arr = $send_drug;
                if(!empty($item_drug_arr)){
                    foreach($item_drug_arr as $item_drug_key=>$item_parent_drug){
                        if(!in_array($item_parent_drug,$update_drug_arr)){
                            $update_drug_arr[] = $item_parent_drug;
                        }
                    }
                }
                if(!empty($drug_arr)){
                    foreach($drug_arr as $drug_key=>$drug_parent_drug){
                        if(!in_array($drug_parent_drug,$update_drug_arr)){
                            $update_drug_arr[] = $drug_parent_drug;
                        }
                    }
                }
                if(!empty($update_drug_arr)){
                    //获取该患者已存储的药物信息
                    $have_drug_arr = [];
                    $patient_drugs = $this->LocalService()->collectPatientdrug->fetchAll([
                        'where'=>['item_id'=>$item_id,'patient_id'=>$patient_id],
                        'columns'=>['id','drug_id','cm_num','is_del']
                    ]);
                    if(!empty($patient_drugs)){
                        foreach($patient_drugs as $patient_drug_key=>$patient_drug){
                            $have_drug_arr[$patient_drug['drug_id']] = $patient_drug;
                            unset($patient_drugs[$patient_drug_key]);
                        }
                    }
                    unset($patient_drugs);

                    $save_drug_arr = [];
                    foreach($update_drug_arr as $update_drug_key=>$update_drug){
                        $is_update = 0;
                        if(isset($cmAndOcrData[$update_drug])){
                            $is_update = 1;
                        }else{
                            if(isset($have_drug_arr[$update_drug]) && $have_drug_arr[$update_drug]['is_del'] == 0){
                                $is_update = 1;
                            }
                        }
                        if($is_update == 1){
                            $save_data = [
                                'cm_num'=>isset($cmAndOcrData[$update_drug]) && !empty($cmAndOcrData[$update_drug]['cm_num']) ? $cmAndOcrData[$update_drug]['cm_num'] : 0,//CM条目
                                'img_num'=>isset($cmAndOcrData[$update_drug]) && !empty($cmAndOcrData[$update_drug]['img_num']) ? $cmAndOcrData[$update_drug]['img_num'] : 0,//相关图片
                                'new_img'=>isset($cmAndOcrData[$update_drug]) && !empty($cmAndOcrData[$update_drug]['new_img']) ? $cmAndOcrData[$update_drug]['new_img'] : 0,//新相关图片数
                                'ocr_num'=>isset($cmAndOcrData[$update_drug]) && !empty($cmAndOcrData[$update_drug]['ocr_num']) ? $cmAndOcrData[$update_drug]['ocr_num'] : 0,//识别条目数
                                'new_ocr'=>isset($cmAndOcrData[$update_drug]) && !empty($cmAndOcrData[$update_drug]['new_ocr']) ? $cmAndOcrData[$update_drug]['new_ocr'] : 0,//待处理识别条目数
                                'is_check'=>isset($cmAndOcrData[$update_drug]) && !empty($cmAndOcrData[$update_drug]['is_check']) ? $cmAndOcrData[$update_drug]['is_check'] : 0,//核查状态【0 待核查 1 已核查】
                                'check_user_id'=>isset($cmAndOcrData[$update_drug]) && !empty($cmAndOcrData[$update_drug]['check_user_id']) ? $cmAndOcrData[$update_drug]['check_user_id'] : 0,//最新核查人
                                'check_time'=>isset($cmAndOcrData[$update_drug]) && !empty($cmAndOcrData[$update_drug]['check_time']) ? $cmAndOcrData[$update_drug]['check_time'] : 0,//最新核查时间
                            ];
                            if(empty($save_data['new_img']) && empty($save_data['new_ocr'])){
                                $save_data['is_check'] = 1;
                            }
                            $save_data['item_id'] = $item_id;
                            $save_data['itemsig_id'] = $itemsig_id;
                            $save_data['patient_id'] = $patient_id;
                            $save_data['drug_id'] = $update_drug;
                            $save_data['is_del'] = 0;
                            $is_add_log = 0;
                            if(isset($have_drug_arr[$update_drug]) && !empty($have_drug_arr[$update_drug])){
                                $save_data['id'] = $have_drug_arr[$update_drug]['id'];
                                $save_data['update_user_id'] = $user_id;
                                $save_data['update_time'] = $update_time;
                                if($have_drug_arr[$update_drug]['is_del'] == 1){
                                    $is_add_log = 1;
                                }
                            }else{
                                $save_data['create_user_id'] = $user_id;
                                $save_data['create_time'] = $update_time;
                                $save_data['update_user_id'] = 0;
                                $save_data['update_time'] = 0;
                                $is_add_log = 1;
                            }
                            $result = $this->LocalService()->collectPatientdrug->isSetInfo(false)->save($save_data);
                            if($save_data['is_del'] == 0){
                                $save_drug_arr[$update_drug] = $save_data;
                                $save_drug_arr[$update_drug]['id'] = isset($save_data['id']) && !empty($save_data['id']) ? $save_data['id'] : $result;
                            }
                            if($result && $is_add_log == 1){
                                $resultid = isset($save_data['id']) && !empty($save_data['id']) ? $save_data['id'] : $result;

                                //日志
                                $this->LocalService()->log->saveFileLog($resultid,'CollectPatientdrug',$save_data,0,'受试者用药信息-新增','',' ',[]);
                                unset($resultid);
                            }
                            //释放空间
                            unset($is_add_log);
                            unset($result);
                            unset($save_data);
                        }
                        if(isset($cmAndOcrData[$update_drug])){
                            unset($cmAndOcrData[$update_drug]);
                        }
                        unset($is_update);
                    }
                    unset($have_drug_arr);

                    //删除已存在通用名信息对应的受试者别名信息
                    if(!empty($save_drug_arr)){
                        foreach($save_drug_arr as $save_drug_id=>$save_drug_info){
                            if(empty($save_drug_info['cm_num']) && empty($save_drug_info['img_num']) && empty($save_data['ocr_num']) && empty($save_drug_info['new_img']) && empty($save_drug_info['new_ocr'])){
                                $save_parent_drug = isset($item_drug_arr[$save_drug_id]) && !empty($item_drug_arr[$save_drug_id]) ? $item_drug_arr[$save_drug_id] : 0;
                                if(empty($save_parent_drug)){
                                    $save_parent_drug = isset($drug_arr[$save_drug_id]) && !empty($drug_arr[$save_drug_id]) ? $drug_arr[$save_drug_id] : 0;
                                }
                                if($save_parent_drug != $save_drug_id && isset($save_drug_arr[$save_parent_drug]) && isset($save_drug_arr[$save_parent_drug]['id']) && !empty($save_drug_arr[$save_parent_drug]['id'])){
                                    $this->LocalService()->collectPatientdrug->isSetInfo(false)->update(['is_del'=>1,'update_user_id'=>$save_drug_info['update_user_id'],'update_time'=>$save_drug_info['update_time']],['id'=>$save_drug_info['id']]);
                                }
                            }
                        }
                    }
                    unset($save_drug_arr);
                }

                //释放空间
                unset($drug_arr);
                unset($item_drug_arr);
                unset($update_drug_arr);
                unset($cmAndOcrData);

            }
            unset($send_drug);
        }

        //释放空间
        unset($item_id);
        unset($itemsig_id);
        unset($patient_id);
        unset($annex_id);
        unset($user_id);
        unset($update_time);

        return true;
    }

    /**
     * Notes: 获取受试者药物识别、CM情况
     * User: lltyy
     * DateTime: 2025/9/8 9:20
     *
     * @param array $params
     * @return array[]
     */
    public function fetchCmAndOcrPatientDrugDatas(array $params){
        $item_id = isset($params['item_id']) && !empty($params['item_id']) ? $params['item_id'] : 0;//项目ID
        $patient_id = isset($params['patient_id']) && !empty($params['patient_id']) ? $params['patient_id'] : 0;//受试者ID
        $drug_arr = isset($params['drug_arr']) && !empty($params['drug_arr']) ? $params['drug_arr'] : [];//药物字典项设置情况
        $item_drug_arr = isset($params['item_drug_arr']) && !empty($params['item_drug_arr']) ? $params['item_drug_arr'] : [];//项目药物设置情况
        $data = [];
        if(!empty($item_id) && !empty($patient_id) && !empty($drug_arr)){
            //相关的顶级药物信息ID
            $update_drug_arr = [];
            //药物处理信息
            $drug_check = [
                'check_user_id'=>[],//药物最新处理人员
                'check_time'=>[],//药物最新处理时间
            ];

            //CM、识别情况
            $cm_ocr_data = [
                'cm_num'=>[],//药物CM条目数量
                'ocr_num'=>[],//药物已处理识别条目数量
                'newocr_num'=>[],//药物待处理识别条目数量
                'img'=>[],//已处理相关图片信息
                'new_img'=>[]//待处理相关图片信息
            ];

            //获取CM条目信息
            $cm_drug_arr = [];
            $cm_datas = $this->LocalService()->patientFormContent->fetchAll([
                'where'=>['is_del'=>0,'item_id'=>$item_id,'patient_id'=>$patient_id,'drug_id'=>array_values(array_keys($drug_arr))],
                'columns'=>['id','drug_id','create_user_id','create_time','update_user_id','update_time'],
                'order'=>['update_time','create_time','id']
            ]);
            if(!empty($cm_datas)){
                foreach($cm_datas as $cm_key=>$cm_data){
                    $cm_drug_arr['id'] = $cm_data['drug_id'];
                    //通用名药物ID
                    $cm_drug = isset($item_drug_arr[$cm_data['drug_id']]) && !empty($item_drug_arr[$cm_data['drug_id']]) ? $item_drug_arr[$cm_data['drug_id']] : 0;
                    if(empty($cm_drug) && isset($drug_arr[$cm_data['drug_id']]) && !empty($drug_arr[$cm_data['drug_id']])){
                        $cm_drug = $drug_arr[$cm_data['drug_id']];
                    }
                    if(!empty($cm_drug)){
                        if(!in_array($cm_drug,$update_drug_arr)){
                            $update_drug_arr[] = $cm_drug;
                        }
                        //CM条目数
                        $cm_ocr_data['cm_num'][$cm_drug] = isset($cm_ocr_data['cm_num'][$cm_drug]) && !empty($cm_ocr_data['cm_num'][$cm_drug]) ? $cm_ocr_data['cm_num'][$cm_drug] : 0;
                        $cm_ocr_data['cm_num'][$cm_drug] += 1;

                        //核查信息
                        $drug_check['check_time'][$cm_drug] = isset($drug_check['check_time'][$cm_drug]) && !empty($drug_check['check_time'][$cm_drug]) ? $drug_check['check_time'][$cm_drug] : 0;
                        $cm_check_time = !empty($cm_data['update_user_id']) ? $cm_data['update_time'] : $cm_data['create_time'];
                        if($drug_check['check_time'][$cm_drug] < $cm_check_time){
                            $drug_check['check_user_id'][$cm_drug] = !empty($cm_data['update_user_id']) ? $cm_data['update_user_id'] : $cm_data['create_user_id'];
                            $drug_check['check_time'][$cm_drug] = $cm_check_time;
                        }
                        unset($cm_check_time);
                    }
                    unset($cm_drug);
                    unset($cm_datas[$cm_key]);
                }
            }
            unset($cm_datas);

            //获取识别信息
            $ocr_datas = $this->LocalService()->doctoradviceOriginal->fetchAll([
                'where'=>[
                    'is_del'=>0,
                    'patient_id'=>$patient_id,
                    'or'=>[
                        ['drug_id'=>array_values(array_keys($drug_arr)),'dualtherapy_type'=>0],
                        ['dualtherapy_drug'=>array_values(array_keys($drug_arr)),new Operator('dualtherapy_type',Operator::OP_GT,0)]
                    ]
                ],
                'columns'=>['annex_id','drug_id','dualtherapy_type','dualtherapy_drug','create_user_id','create_time','update_user_id','update_time'],
                'order'=>['update_time','create_time','id']
            ]);
            if(!empty($ocr_datas)){
                foreach($ocr_datas as $ocr_key=>$ocr_data){
                    //顶级药物ID
                    $child_ocr_drug = !empty($ocr_data['dualtherapy_type']) ? $ocr_data['dualtherapy_drug'] : $ocr_data['drug_id'];
                    $ocr_drug = isset($item_drug_arr[$child_ocr_drug]) && !empty($item_drug_arr[$child_ocr_drug]) ? $item_drug_arr[$child_ocr_drug] : 0;
                    if(empty($ocr_drug) && isset($drug_arr[$child_ocr_drug]) && !empty($drug_arr[$child_ocr_drug])){
                        $ocr_drug = $drug_arr[$child_ocr_drug];
                    }
                    unset($child_ocr_drug);
                    if(!empty($ocr_drug)){
                        if(!in_array($ocr_drug,$update_drug_arr)){
                            $update_drug_arr[] = $ocr_drug;
                        }
                        if(!empty($ocr_data['dualtherapy_type'])){//已核查信息
                            //识别条目
                            $cm_ocr_data['ocr_num'][$ocr_drug] = isset($cm_ocr_data['ocr_num'][$ocr_drug]) && !empty($cm_ocr_data['ocr_num'][$ocr_drug]) ? $cm_ocr_data['ocr_num'][$ocr_drug] : 0;
                            $cm_ocr_data['ocr_num'][$ocr_drug] += 1;

                            //核查信息
                            $drug_check['check_time'][$ocr_drug] = isset($drug_check['check_time'][$ocr_drug]) && !empty($drug_check['check_time'][$ocr_drug]) ? $drug_check['check_time'][$ocr_drug] : 0;
                            $ocr_check_time = !empty($ocr_data['update_user_id']) ? $ocr_data['update_time'] : $ocr_data['create_time'];
                            if($drug_check['check_time'][$ocr_drug] < $ocr_check_time){
                                $drug_check['check_user_id'][$ocr_drug] = !empty($ocr_data['update_user_id']) ? $ocr_data['update_user_id'] : $ocr_data['create_user_id'];
                                $drug_check['check_time'][$ocr_drug] = $ocr_check_time;
                            }

                            //相关图片数
                            $cm_ocr_data['img'][$ocr_drug] = isset($cm_ocr_data['img'][$ocr_drug]) && !empty($cm_ocr_data['img'][$ocr_drug]) ? $cm_ocr_data['img'][$ocr_drug] : [];
                            if(!empty($ocr_data['annex_id']) && !in_array($ocr_data['annex_id'],$cm_ocr_data['img'][$ocr_drug])){
                                $cm_ocr_data['img'][$ocr_drug][] = $ocr_data['annex_id'];
                            }
                            unset($ocr_check_time);
                        }else{//未核查信息
                            //识别条目
                            $cm_ocr_data['newocr_num'][$ocr_drug] = isset($cm_ocr_data['newocr_num'][$ocr_drug]) && !empty($cm_ocr_data['newocr_num'][$ocr_drug]) ? $cm_ocr_data['newocr_num'][$ocr_drug] : 0;
                            $cm_ocr_data['newocr_num'][$ocr_drug] += 1;

                            //相关图片数
                            $cm_ocr_data['new_img'][$ocr_drug] = isset($cm_ocr_data['new_img'][$ocr_drug]) && !empty($cm_ocr_data['new_img'][$ocr_drug]) ? $cm_ocr_data['new_img'][$ocr_drug] : [];
                            if(!empty($ocr_data['annex_id']) && !in_array($ocr_data['annex_id'],$cm_ocr_data['new_img'][$ocr_drug])){
                                $cm_ocr_data['new_img'][$ocr_drug][] = $ocr_data['annex_id'];
                            }
                        }
                    }
                    unset($ocr_drug);
                    unset($ocr_datas[$ocr_key]);
                }
            }
            unset($ocr_datas);

            //处理药物情况
            if(!empty($update_drug_arr)){
                foreach($update_drug_arr as $update_drug_key=>$update_drug){
                    $data[$update_drug] = [
                        'cm_num'=>isset($cm_ocr_data['cm_num'][$update_drug]) && !empty($cm_ocr_data['cm_num'][$update_drug]) ? $cm_ocr_data['cm_num'][$update_drug] : 0,//CM条目
                        'img_num'=>isset($cm_ocr_data['img'][$update_drug]) && !empty($cm_ocr_data['img'][$update_drug]) ? count($cm_ocr_data['img'][$update_drug]) : 0,//相关图片
                        'new_img'=>0,//新相关图片数
                        'ocr_num'=>isset($cm_ocr_data['ocr_num'][$update_drug]) && !empty($cm_ocr_data['ocr_num'][$update_drug]) ? $cm_ocr_data['ocr_num'][$update_drug] : 0,//识别条目
                        'new_ocr'=>isset($cm_ocr_data['newocr_num'][$update_drug]) && !empty($cm_ocr_data['newocr_num'][$update_drug]) ? $cm_ocr_data['newocr_num'][$update_drug] : 0,//新识别条目数
                        'is_check'=>1,//核查状态【0 待核查 1 已核查】
                        'check_user_id'=>isset($drug_check['check_user_id'][$update_drug]) && !empty($drug_check['check_user_id'][$update_drug]) ? $drug_check['check_user_id'][$update_drug] : 0,//最新核查人
                        'check_time'=>isset($drug_check['check_time'][$update_drug]) && !empty($drug_check['check_time'][$update_drug]) ? $drug_check['check_time'][$update_drug] : 0,//最新核查时间
                    ];
                    if(isset($cm_ocr_data['new_img'][$update_drug]) && !empty($cm_ocr_data['new_img'][$update_drug])){
                        $old_drugimg_arr = isset($cm_ocr_data['img'][$update_drug]) && !empty($cm_ocr_data['img'][$update_drug]) ? $cm_ocr_data['img'][$update_drug] : [];
                        foreach($cm_ocr_data['new_img'][$update_drug] as $drug_img_key=>$drug_img){
                            if(!in_array($drug_img,$old_drugimg_arr)){
                                $data[$update_drug]['new_img'] += 1;
                            }
                        }
                        unset($old_drugimg_arr);
                    }
                    if(!empty($data[$update_drug]['new_img']) || !empty($data[$update_drug]['new_ocr'])){
                        $data[$update_drug]['is_check'] = 0;
                    }

                    //释放空间
                    if(isset($cm_ocr_data['img'][$update_drug])){
                        unset($cm_ocr_data['img'][$update_drug]);
                    }
                    if(isset($cm_ocr_data['new_img'][$update_drug])){
                        unset($cm_ocr_data['new_img'][$update_drug]);
                    }
                    if(isset($cm_ocr_data['ocr_num'][$update_drug])){
                        unset($cm_ocr_data['ocr_num'][$update_drug]);
                    }
                    if(isset($cm_ocr_data['newocr_num'][$update_drug])){
                        unset($cm_ocr_data['newocr_num'][$update_drug]);
                    }
                    if(isset($drug_check['check_user_id'][$update_drug])){
                        unset($drug_check['check_user_id'][$update_drug]);
                    }
                    if(isset($drug_check['check_time'][$update_drug])){
                        unset($drug_check['check_time'][$update_drug]);
                    }
                    unset($update_drug_arr[$update_drug_key]);
                }
            }

            unset($update_drug_arr);
            unset($drug_check);
            unset($cm_ocr_data);
        }

        unset($item_id);
        unset($patient_id);
        unset($all_drug_arr);
        unset($parent_drug_arr);

        return $data;
    }

    /**
     * Notes: 识别条目预合并CM
     * User: lltyy
     * DateTime: 2025/8/28 16:26
     * 开始日期[medical_date]：开始用药日期【最早开始日期】
     * 结束日期[end_date]：结束用药日期【最晚结束日期】
     * 出院带药[is_dispensary]：只要有一条出院带药就默认 是
     * 剂量[dosage_num]：即单次剂量【最小剂量】
     * 剂量[dosage_unit]：剂量单位【最小剂量对应的剂量单位】
     * 给药途径[dosage_way]：给药途径【最小剂量对应的给药途径】
     * 给药频率[dosage_times]：给药频率【最小剂量对应的给药频率】
     * @param array $params
     * @return array
     */
    public function fetchMergeCmData(array $params){
        $item_id = isset($params['item_id']) && !empty($params['item_id']) ? $params['item_id'] : 0;//项目ID
        $patient_id = isset($params['patient_id']) && !empty($params['patient_id']) ? $params['patient_id'] : 0;//受试者ID
        $form_id = isset($params['form_id']) && !empty($params['form_id']) ? $params['form_id'] : 0;//CM表单ID
        $drug_arr = isset($params['drug_arr']) && !empty($params['drug_arr']) ? $params['drug_arr'] : [];//药物ID
        $ocr_arr = isset($params['ocr_arr']) && !empty($params['ocr_arr']) ? $params['ocr_arr'] : [];//识别条目ID

        $data = [
            'medical_date' => '',//最早开始日期
            'end_date' => '',//最晚结束日期
            'is_dispensary' => 0,//出院带药
            'dosage_num' => '',//最小剂量数值
            'dosage_unit' => 0,//最小剂量对应的单位ID
            'dosage_way' => 0,//给药途径
            'dosage_times' => 0//给药频率
        ];//CM合并信息
        $cmDefault = [
            'CMNAM'=>$this->LocalService()->collectItemdrug->getOneFieldVal('name',['is_del'=>0,'item_id'=>$item_id,'parent_drug'=>0,'drug_id'=>$drug_arr]),//药物名称
            'CMSTDAT'=>'',//开始用药日期
            'CMENDAT'=>'',//结束用药日期
            'DMONG'=>'否',//出院带药标识
            'CMDO'=>'',//单次剂量
            'CMDOS'=>'',//剂量单位
            'CMROU'=>'',//给药途径
            'CMD'=>'',//给药频率
            'CMINDC100'=>''//用药原因
        ];//CM合并表单默认信息

        if(!empty($drug_arr)){
            //获取药物通用名以及该项目设置的药物用药原因
            $drugDatas = $this->LocalService()->collectItemdrug->fetchAll([
                'where'=>['is_del'=>0,'drug_id'=>$drug_arr],
                'columns'=>['parent_drug','name']
            ]);
            if(empty($drugDatas)){
                $drugDatas = $this->LocalService()->collectDrug->fetchAll([
                    'where'=>['is_del'=>0,'id'=>$drug_arr],
                    'columns'=>['parent_drug','name']
                ]);
            }
            if(!empty($drugDatas)){
                //药物通用名
                foreach($drugDatas as $drugDataInfo){
                    if(empty($drugDataInfo['parent_drug']) && ($cmDefault['CMNAM'] == '' || is_null($cmDefault['CMNAM']))){
                        $cmDefault['CMNAM'] = $drugDataInfo['name'];
                    }
                }
                //该项目设置的用药原因
                $cmDrugSetDatas = $this->LocalService()->projectCmdrugset->fetchAll([
                    'where'=>['is_del'=>0,'item_id'=>$item_id],
                    'columns'=>['cm_english','drug_name']
                ]);
                if(!empty($cmDrugSetDatas)){
                    foreach($cmDrugSetDatas as $cmDrugSetDataKey=>$cmDrugSetData){
                        if(empty($cmDefault['CMINDC100'])){
                            $cmDrugSetData_drugs = json_decode($cmDrugSetData['drug_name'],true);
                            foreach($drugDatas as $drugData){
                                if(in_array(trim($drugData['name']),$cmDrugSetData_drugs)){
                                    $cmDefault['CMINDC100'] = $cmDrugSetData['cm_english'];
                                }
                            }
                            unset($cmDrugSetData_drugs);
                        }
                        unset($cmDrugSetDatas[$cmDrugSetDataKey]);
                    }
                }
                unset($cmDrugSetDatas);
            }
            unset($drugDatas);
        }

        //获取识别条目信息
        $ocr_where = ['is_del'=>0,'patient_id'=>$patient_id,'drug_id'=>$drug_arr];
        if(!empty($ocr_arr)){//有识别条目ID 只获取指定识别条目的合并记录
            $ocr_where['id'] = $ocr_arr;
        }else{//无识别条目 则获取待核查识别条目的合并记录
            $ocr_where['dualtherapy_type'] = 0;
        }
        $ocr_datas = $this->LocalService()->doctoradviceOriginal->fetchAll([
            'where'=>$ocr_where,
            'columns'=>['id','medical_date','dosage_num','dosage_unit','dosage_way','dosage_times','is_dispensary','end_date'],
            'order'=>['medical_date','end_date','id']
        ]);
        if(!empty($ocr_datas)){
            foreach($ocr_datas as $ocr_key=>&$ocr_data){
                $ocr_data['medical_date'] = trim($ocr_data['medical_date']) != '' ? str_replace('-','',trim($ocr_data['medical_date'])) : '';
                $ocr_data['end_date'] = trim($ocr_data['end_date']) != '' ? str_replace('-','',trim($ocr_data['end_date'])) : '';
                $data = [
                    'medical_date' => isset($data['medical_date']) && $data['medical_date'] != '' ? $data['medical_date'] : '',//最早开始日期
                    'end_date' => isset($data['end_date']) && $data['end_date'] != '' ? $data['end_date'] : '',//最晚结束日期
                    'is_dispensary' => isset($data['is_dispensary']) && !empty($data['is_dispensary']) ? $data['is_dispensary'] : 0,//出院带药
                    'dosage_num' => isset($data['dosage_num']) && $data['dosage_num'] != '' ? $data['dosage_num'] : '',//最小剂量数值
                    'dosage_unit' => isset($data['dosage_unit']) && $data['dosage_unit'] != '' ? $ocr_data['dosage_unit'] : 0,//最小剂量对应的单位ID
                    'dosage_way' => isset($data['dosage_way']) && !empty($data['dosage_way']) ? $data['dosage_way'] : 0,//给药途径
                    'dosage_times' => isset($data['dosage_times']) && !empty($data['dosage_times']) ? $data['dosage_times'] : 0//给药频率
                ];
                //获取最早开始日期
                if(!is_null($ocr_data['medical_date']) && $ocr_data['medical_date'] != ''){
                    if($data['medical_date'] == '' || ($data['medical_date'] != '' && intval($ocr_data['medical_date']) < intval($data['medical_date']))){
                        $data['medical_date'] = $ocr_data['medical_date'];
                    }
                }
                //获取最晚结束日期
                if(!is_null($ocr_data['end_date']) && $ocr_data['end_date'] != ''){
                    if($data['end_date'] == '' || ($data['end_date'] != '' && intval($ocr_data['end_date']) > intval($data['end_date']))){
                        $data['end_date'] = $ocr_data['end_date'];
                    }
                }
                //出院带药标识
                if($ocr_data['is_dispensary'] == 1 && empty($data['is_dispensary'])){
                    $data['is_dispensary'] = 1;
                }

                //获取小剂量以及最小剂量对应的 剂量单位、给药途径、给药频率等信息
                if(!is_null($ocr_data['dosage_num']) && trim($ocr_data['dosage_num']) != ''){
                    if($data['dosage_num'] == '' || ($data['dosage_num'] != '' && floatval(trim($ocr_data['dosage_num'])) < floatval($data['dosage_num']))){
                        $data['dosage_num'] = trim($ocr_data['dosage_num']);
                        $data['dosage_unit'] = $ocr_data['dosage_unit'];
                        $data['dosage_way'] = $ocr_data['dosage_way'];
                        $data['dosage_times'] = $ocr_data['dosage_times'];
                    }
                }
                if($data['is_dispensary'] == 1){
                    $data['end_date'] = '';
                }

                unset($ocr_datas[$ocr_key]);
            }

            //获取该CM表单内容信息
            $cmFieldVar = $takeSelectArr = $selectNameArr = $selectTakeArr = [];
            $cmFieldDatas = $this->LocalService()->itemFormField->fetchAll([
                'where'=>['is_del'=>0,'form_id'=>$form_id],
                'columns'=>['id','parent','name','var_name','medical_type'],
                'order'=>['parent','id']
            ]);
            if(!empty($cmFieldDatas)){
                foreach($cmFieldDatas as $cmFieldKey=>$cmFieldData){
                    if(!empty($cmFieldData['parent'])){
                        if(in_array($cmFieldVar[$cmFieldData['parent']],['CMDOS','CMROU','CMD'])){
                            $selectNameArr[$cmFieldData['id']] = $cmFieldData['name'];
                            if(!is_null($cmFieldData['medical_type']) && !empty($cmFieldData['medical_type'])){
                                $cmFieldData_medical_types = explode(',',$cmFieldData['medical_type']);
                                if(!empty($cmFieldData_medical_types)){
                                    foreach($cmFieldData_medical_types as $cmFieldData_medical_type){
                                        if(!empty($cmFieldData_medical_type)){
                                            $takeSelectArr[$cmFieldData_medical_type] = $cmFieldData['name'];
                                            $selectTakeArr[$cmFieldData['id']] = $cmFieldData_medical_type;
                                        }
                                    }
                                }
                                unset($cmFieldData_medical_types);
                            }
                        }
                    }else{
                        $cmFieldVar[$cmFieldData['id']] = $cmFieldData['var_name'];
                    }
                    unset($cmFieldDatas[$cmFieldKey]);
                }
            }
            unset($cmFieldDatas);

            //CM表单默认信息
            $cmDefault['CMSTDAT'] = $data['medical_date'] != '' ? \Datetime::createFromFormat('Ymd', $data['medical_date'])->format('Y-m-d') : '';//开始用药日期
            $cmDefault['CMENDAT'] = $data['end_date'] != '' && $data['is_dispensary'] != 1 ? \Datetime::createFromFormat('Ymd', $data['end_date'])->format('Y-m-d') : '';//结束用药日期
            $cmDefault['DMONG'] = $data['is_dispensary'] == 1 ? '是' : '否';//出院带药标识
            $cmDefault['CMDO'] = $data['dosage_num'] != '' ? $data['dosage_num'] : '';//单次剂量
            $cmDefault['CMDOS'] = !empty($data['dosage_unit']) && isset($takeSelectArr[$data['dosage_unit']]) && $takeSelectArr[$data['dosage_unit']] != '' ? $takeSelectArr[$data['dosage_unit']] : '';//剂量单位
            $cmDefault['CMROU'] = !empty($data['dosage_way']) && isset($takeSelectArr[$data['dosage_way']]) && $takeSelectArr[$data['dosage_way']] != '' ? $takeSelectArr[$data['dosage_way']] : '';//给药途径
            $cmDefault['CMD'] = !empty($data['dosage_times']) && isset($takeSelectArr[$data['dosage_times']]) && $takeSelectArr[$data['dosage_times']] != '' ? $takeSelectArr[$data['dosage_times']] : '';//给药频率

            //如果无剂量、单位、给药途径、给药频率等信息，则获取该患者该药物下的最新一笔CM信息，无CM的话 获取项目药物设置信息
            if($cmDefault['CMDO'] == '' || empty($cmDefault['CMDOS']) || empty($cmDefault['CMROU']) || empty($cmDefault['CMD'])){
                $lastCmData = [];
                if(!empty($form_id)){
                    //获取该患者该药物下的最新一笔CM信息
                    $lastCmData = $this->LocalService()->patientFormContent->fetchOne([
                        'where'=>['is_del'=>0,'patient_id'=>$patient_id,'drug_id'=>$drug_arr],
                        'columns'=>['data'],
                        'order'=>['id desc']
                    ]);
                }
                if(!empty($lastCmData)){
                    $content_data = json_decode($lastCmData['data'],true);
                    if(!empty($content_data)){
                        foreach($content_data as $content_key=>$content_value){
                            if (!DataHelper::isField($content_key)) {
                                continue;
                            }
                            $postFieldId = DataHelper::getFieldId($content_key);
                            if(!empty($postFieldId) && isset($cmFieldDatas[$postFieldId]) && !is_null($cmFieldVar[$postFieldId]) && $cmFieldVar[$postFieldId] != ''){
                                //剂量
                                if($cmFieldVar[$postFieldId] == 'CMDO' && $cmDefault['CMDO'] == '' && !is_null($content_value) && $content_value != ''){
                                    $cmDefault['CMDO'] = $content_value;
                                    $data['dosage_num'] = $content_value;
                                }
                                //剂量单位
                                if($cmFieldVar[$postFieldId] == 'CMDOS' && empty($cmDefault['CMDOS']) && !is_null($content_value) && !empty($content_value)){
                                    $cmDefault['CMDOS'] = isset($selectNameArr[$content_value]) && $selectNameArr[$content_value] != '' ? $selectNameArr[$content_value] : '';
                                    $data['dosage_unit'] = isset($selectTakeArr[$content_value]) && !empty($selectTakeArr[$content_value]) ? $selectTakeArr[$content_value] : 0;
                                }
                                //给药途径
                                if($cmFieldVar[$postFieldId] == 'CMROU' && empty($cmDefault['CMROU']) && !is_null($content_value) && !empty($content_value)){
                                    $cmDefault['CMROU'] = isset($selectNameArr[$content_value]) && $selectNameArr[$content_value] != '' ? $selectNameArr[$content_value] : '';
                                    $data['dosage_way'] = isset($selectTakeArr[$content_value]) && !empty($selectTakeArr[$content_value]) ? $selectTakeArr[$content_value] : 0;
                                }
                                //给药频率
                                if($cmFieldVar[$postFieldId] == 'CMD' && empty($cmDefault['CMD']) && !is_null($content_value) && !empty($content_value)){
                                    $cmDefault['CMD'] = isset($selectNameArr[$content_value]) && $selectNameArr[$content_value] != '' ? $selectNameArr[$content_value] : '';
                                    $data['dosage_times'] = isset($selectTakeArr[$content_value]) && !empty($selectTakeArr[$content_value]) ? $selectTakeArr[$content_value] : 0;
                                }
                            }
                            unset($postFieldId);
                            unset($content_data[$content_key]);
                        }
                        unset($cmFieldVar);
                    }
                    unset($content_data);
                }else{//获取项目药物设置信息
                    $itemDrug = $this->LocalService()->collectItemdrug->fetchOne([
                        'where'=>['is_del'=>0,'drug_id'=>$drug_arr,'item_id'=>$item_id,'parent_drug'=>0],
                        'columns'=>['dosage_num','dosage_unit','dosage_times','dosage_way']
                    ]);
                    if(!empty($itemDrug)){
                        //剂量
                        if($data['dosage_num'] == '' && !is_null($itemDrug['dosage_num']) && $itemDrug['dosage_num'] != ''){
                            $cmDefault['CMDO'] = $itemDrug['dosage_num'];
                            $data['dosage_num'] = $itemDrug['dosage_num'];
                        }
                        //剂量单位
                        if(empty($data['dosage_unit']) && !is_null($itemDrug['dosage_unit']) && !empty($itemDrug['dosage_unit'])){
                            $cmDefault['CMROU'] = isset($takeSelectArr[$itemDrug['dosage_unit']]) && $takeSelectArr[$itemDrug['dosage_unit']] != '' ? $takeSelectArr[$itemDrug['dosage_unit']] : '';
                            $data['dosage_unit'] = $itemDrug['dosage_unit'];
                        }
                        //给药途径
                        if(empty($data['dosage_way']) && !is_null($itemDrug['dosage_way']) && !empty($itemDrug['dosage_way'])){
                            $cmDefault['CMROU'] = isset($takeSelectArr[$itemDrug['dosage_way']]) && $takeSelectArr[$itemDrug['dosage_way']] != '' ? $takeSelectArr[$itemDrug['dosage_way']] : '';
                            $data['dosage_way'] = $itemDrug['dosage_way'];
                        }
                        //给药频率
                        if(empty($data['dosage_times']) && !is_null($itemDrug['dosage_times']) && !empty($itemDrug['dosage_times'])){
                            $cmDefault['CMROU'] = isset($takeSelectArr[$itemDrug['dosage_times']]) && $takeSelectArr[$itemDrug['dosage_times']] != '' ? $takeSelectArr[$itemDrug['dosage_times']] : '';
                            $data['dosage_times'] = $itemDrug['dosage_times'];
                        }
                    }
                    unset($itemDrug);
                }
                unset($lastCmData);
            }

            unset($cmFieldVar);
            unset($takeSelectArr);
            unset($selectNameArr);
            unset($selectTakeArr);

        }
        unset($ocr_datas);
        unset($ocr_arr);
        unset($drug_arr);

        return ['merge_data'=>$data,'cmDefault'=>$cmDefault];

    }

    /**
     * Notes: 异步更新该项目下所有受试者的对应的药物信息
     * User: lltyy
     * DateTime: 2025/9/9 9:27
     *
     */
    public function scanItemPatientDrugData(array $params){
        $item_id = isset($params['item_id']) && !empty($params['item_id']) ? $params['item_id'] : 0;
        $user_id = isset($params['user_id']) && !empty($params['user_id']) ? $params['user_id'] : 0;
        $drug_arr = isset($params['drug_id']) && !empty($params['drug_id']) ? $params['drug_id'] : [];
        if(!empty($item_id) && !empty($drug_arr)){
            $where = ['is_del'=>0,'item_id'=>$item_id];
            $bool = true;
            $page = 0;
            $limit = 1000;
            $last_id = 0;
            while ($bool) {
                $page++;
                $mateWhere = $where;
                $mateWhere[] = new Operator('id',Operator::OP_GT,$last_id);
                $last_id = $this->mateItemPatientDrugData($mateWhere,$limit,0,$user_id,$drug_arr);
                unset($mateWhere);
                if(!$last_id) $bool = false;
            }
            unset($where);
        }
        unset($item_id);
        unset($user_id);
        unset($drug_arr);

    }


    /**
     * Notes: 执行更新该项目下所有受试者的对应的药物信息
     * User: lltyy
     * DateTime: 2025/9/9 9:27
     *
     * @param $where
     * @param int $limit
     * @param int $offset
     * @param $user_id
     * @param $update_drug_arr
     * @return int
     */
    public function mateItemPatientDrugData($where,$limit=0,$offset=0,&$user_id,&$update_drug_arr){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','item_id','itemsig_id'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->LocalService()->patient->fetchAll($cond);
        $last_id = 0;
        if(!empty($datas)){
            foreach($datas as $dataKey=>$data){
                $last_id = $data['id'];
                $this->LocalService()->collectPatientdrug->savePatientdrugData([
                    'item_id'=>$data['item_id'],
                    'itemsig_id'=>$data['itemsig_id'],
                    'patient_id'=>$data['id'],
                    'drug_id'=>$update_drug_arr,
                    'user_id'=>$user_id
                ]);
                unset($datas[$dataKey]);
            }
        }

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

    /**
     * Notes: 更新识别条目中的药物ID
     * User: lltyy
     * DateTime: 2025/8/27 21:20
     *
     */
    public function scanOcrDrugData(){
        $where = ['id'=>0];

        //获取药物名称ID
        $drug_name_arr = [];
        $drug_arr = $this->LocalService()->collectDrug->fetchCol('name',['is_del'=>0]);
        if(!empty($drug_arr)){
            foreach($drug_arr as $drug_id=>$drug_name){
                $drug_name = trim($drug_name);
                $drug_name_arr[$drug_name] = $drug_id;
            }
            $where = ['is_del'=>0,new NotIn('drug_id',array_values(array_keys($drug_arr))),new Operator('drug_id',Operator::OP_GT,0)];
        }
        unset($drug_arr);

        $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->mateOcrDrugData($mateWhere,$limit,0,$drug_name_arr);
            unset($mateWhere);
            if(!$last_id) $bool = false;
        }
        unset($form_field_arr);
        unset($drug_arr);
        unset($where);
    }


    /**
     * Notes: 执行更新识别条目中的药物ID
     * User: lltyy
     * DateTime: 2025/8/27 21:20
     *
     * @param $where
     * @param int $limit
     * @param int $offset
     * @param $drug_name_arr
     * @return int
     */
    public function mateOcrDrugData($where,$limit=0,$offset=0,&$drug_name_arr){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','name','is_lock','dualtherapy_type','update_user_id','update_time'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->LocalService()->doctoradviceOriginal->fetchAll($cond);
        $last_id = 0;
        if(!empty($datas)){
            foreach($datas as $dataKey=>$data){
                $last_id = $data['id'];
                $drug_name = trim($data['name']);
                $drug_id = isset($drug_name_arr[$drug_name]) && !empty($drug_name_arr[$drug_name]) ? $drug_name_arr[$drug_name] : 0;
                if(!empty($drug_id)){
                    $dualtherapy_type = $data['is_lock'] == 2 ? 3 : $data['dualtherapy_type'];
                    $update_data = [
                        'drug_id'=>$drug_id,
                        'update_user_id'=>$data['update_user_id'],
                        'update_time'=>$data['update_time'],
                        'dualtherapy_type'=>$dualtherapy_type,
                        'dualtherapy_drug'=>!empty($dualtherapy_type) ? $drug_id : 0
                    ];
                    $this->LocalService()->doctoradviceOriginal->isSetInfo(false)->update($update_data,['id'=>$data['id']]);
                    unset($dualtherapy_type);
                }
                unset($update_data);
                unset($drug_id);
                unset($drug_name);
                unset($datas[$dataKey]);
            }
        }

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

        return $last_id;

    }

    /**
     * Notes: 更新CM合并用药表单药物ID
     * User: lltyy
     * DateTime: 2025/8/27 21:20
     *
     */
    public function scanPatientFormContentData(){

        $where = ['id'=>0];

        //获取CM合并用药表单信息
        $form_arr = $this->LocalService()->itemForm->fetchCol('id',['is_del' => 0,'type' => 1,'var_name' => 'CM']);
        $form_arr = !empty($form_arr) ? array_values($form_arr) : [];
        //获取CM合并用药表单药物名称字段
        $form_field_arr = [];
        if(!empty($form_arr)){
            $field_datas = $this->LocalService()->itemFormField->fetchAll([
                'where'=>['is_del' => 0,'var_name' => 'CMNAM','form_id'=>$form_arr],
                'columns'=>['id','form_id']
            ]);
            if(!empty($field_datas)){
                foreach($field_datas as $field_key=>$field_data){
                    $form_field_arr[$field_data['form_id']] = $field_data['id'];
                    unset($field_datas[$field_key]);
                }
            }
            unset($field_datas);
            $where = ['drug_id'=>0,'form_id'=>$form_arr];
        }
        unset($form_arr);

        //获取药物名称ID
        $drug_arr = [];
        $drug_infos = $this->LocalService()->collectDrug->fetchCol('name',['is_del'=>0]);
        if(!empty($drug_infos)){
            foreach($drug_infos as $drug_info_key=>$drug_info){
                if(!isset($drug_arr[$drug_info])){
                    $drug_arr[$drug_info] = $drug_info_key;
                }
                unset($drug_infos[$drug_info_key]);
            }
        }
        unset($drug_infos);

        $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->matePatientFormContentData($mateWhere,$limit,0,$form_field_arr,$drug_arr);
            unset($mateWhere);
            if(!$last_id) $bool = false;
        }
        unset($form_field_arr);
        unset($drug_arr);
        unset($where);
    }

    /**
     * Notes: 执行更新CM合并用药表单药物ID
     * User: lltyy
     * DateTime: 2025/8/27 21:20
     *
     * @param $where
     * @param int $limit
     * @param int $offset
     * @param $form_field_arr
     * @param $drug_arr
     * @return int
     */
    public function matePatientFormContentData($where,$limit=0,$offset=0,&$form_field_arr,&$drug_arr){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','form_id','data','update_user_id','update_time'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->LocalService()->patientFormContent->fetchAll($cond);
        $last_id = 0;
        if(!empty($datas)){
            foreach($datas as $dataKey=>$data){
                $last_id = $data['id'];
                $cm_name_id = isset($form_field_arr[$data['form_id']]) && !empty($form_field_arr[$data['form_id']]) ? $form_field_arr[$data['form_id']] : 0;
                if(!empty($cm_name_id)){
                    $data_content = !empty($data['data']) ? json_decode($data['data'],true) : [];
                    $drug_name = isset($data_content[$cm_name_id]) && !is_null($data_content[$cm_name_id]) && $data_content[$cm_name_id] != '' ? trim($data_content[$cm_name_id]) : '';
                    $drug_id = $drug_name != '' && isset($drug_arr[$drug_name]) && !empty($drug_arr[$drug_name]) ? $drug_arr[$drug_name] : 0;
                    if(!empty($drug_id)){
                        $this->LocalService()->patientFormContent->isSetInfo(false)->update(['drug_id'=>$drug_id,'update_user_id'=>$data['update_user_id'],'update_time'=>$data['update_time']],['id'=>$data['id']]);
                    }
                    unset($drug_id);
                    unset($drug_name);
                    unset($data_content);
                }
                unset($cm_name_id);
                unset($datas[$dataKey]);
            }
        }

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

        return $last_id;

    }

    /**
     * Notes: 更新CM表单受试者药物信息更新
     * User: lltyy
     * DateTime: 2025/8/27 21:20
     *
     */
    public function scanCmPatientDrugData(){

        $where = ['is_del'=>0,new Operator('drug_id',Operator::OP_GT,0)];
        //获取药物名称ID
        $drug_arr = $parent_drug_arr = [];
        $drug_datas = $this->LocalService()->collectDrug->fetchAll([
            'where'=>['is_del'=>0],
            'columns'=>['id','parent_drug']
        ]);
        if(!empty($drug_datas)){
            $drug_arr = array_values(array_column($drug_datas,'id'));
            foreach($drug_datas as $drug_key=>$drug_data){
                if(!empty($drug_data['parent_drug'])){
                    $parent_drug_arr[$drug_data['id']] = $drug_data['parent_drug'];
                }
                unset($drug_datas[$drug_key]);
            }
        }
        unset($drug_datas);

        $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->mateCmPatientDrugData($mateWhere,$limit,0,$drug_arr,$parent_drug_arr);
            unset($mateWhere);
            if(!$last_id) $bool = false;
        }
        unset($form_field_arr);
        unset($drug_arr);
        unset($where);
    }

    /**
     * Notes: 执行更新CM表单受试者药物信息更新
     * User: lltyy
     * DateTime: 2025/8/27 21:20
     *
     * @param $where
     * @param int $limit
     * @param int $offset
     * @param $drug_arr
     * @param $parent_drug_arr
     * @return int
     */
    public function mateCmPatientDrugData($where,$limit=0,$offset=0,&$drug_arr,&$parent_drug_arr){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','item_id','itemsig_id','patient_id','drug_id','create_user_id','create_time'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->LocalService()->patientFormContent->fetchAll($cond);
        $last_id = 0;
        if(!empty($datas)){
            foreach($datas as $dataKey=>$data){
                $last_id = $data['id'];
                $drug_id = $data['drug_id'];
                if(isset($parent_drug_arr[$drug_id]) && !empty($parent_drug_arr[$drug_id])){
                    $drug_id = $parent_drug_arr[$drug_id];
                }
                if(in_array($drug_id,$drug_arr)){
                    $this->LocalService()->collectPatientdrug->savePatientdrugData([
                        'item_id'=>$data['item_id'],
                        'itemsig_id'=>$data['itemsig_id'],
                        'patient_id'=>$data['patient_id'],
                        'drug_id'=>[$data['drug_id']],
                        'user_id'=>$data['create_user_id'],
                        'time'=>$data['create_time']
                    ]);
                }
                unset($drug_id);
                unset($datas[$dataKey]);
            }
        }

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

        return $last_id;

    }

    /**
     * Notes: 更新识别受试者药物信息更新
     * User: lltyy
     * DateTime: 2025/8/27 21:20
     *
     */
    public function scanOcrPatientDrugData(){

        $where = ['is_del'=>0,'is_lock'=>[0,1],new Operator('patient_id',Operator::OP_GT,0),new Operator('drug_id',Operator::OP_GT,0)];
        //获取药物名称ID
        $drug_arr = $parent_drug_arr = [];
        $drug_datas = $this->LocalService()->collectDrug->fetchAll([
            'where'=>['is_del'=>0],
            'columns'=>['id','parent_drug']
        ]);
        if(!empty($drug_datas)){
            $drug_arr = array_values(array_column($drug_datas,'id'));
            foreach($drug_datas as $drug_key=>$drug_data){
                if(!empty($drug_data['parent_drug'])){
                    $parent_drug_arr[$drug_data['id']] = $drug_data['parent_drug'];
                }
                unset($drug_datas[$drug_key]);
            }
        }
        unset($drug_datas);

        //获取受试者信息
        $patient_arr = $this->LocalService()->patient->fetchAll([
            'where'=>['is_del'=>0],
            'columns'=>['id','item_id','itemsig_id']
        ]);
        $patient_arr = !empty($patient_arr) ? ArrayHelper::index($patient_arr,'id') : [];

        $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->mateOcrPatientDrugData($mateWhere,$limit,0,$drug_arr,$parent_drug_arr,$patient_arr);
            unset($mateWhere);
            if(!$last_id) $bool = false;
        }
        unset($form_field_arr);
        unset($drug_arr);
        unset($where);
    }

    /**
     * Notes: 执行更新识别受试者药物信息更新
     * User: lltyy
     * DateTime: 2025/8/27 21:20
     *
     * @param $where
     * @param int $limit
     * @param int $offset
     * @param $drug_arr
     * @param $parent_drug_arr
     * @param $patient_arr
     * @return int
     */
    public function mateOcrPatientDrugData($where,$limit=0,$offset=0,&$drug_arr,&$parent_drug_arr,&$patient_arr){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','patient_id','drug_id','create_user_id','create_time'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->LocalService()->doctoradviceOriginal->fetchAll($cond);
        $last_id = 0;
        if(!empty($datas)){
            foreach($datas as $dataKey=>$data){
                $last_id = $data['id'];
                if(isset($patient_arr[$data['patient_id']]) && !empty($patient_arr[$data['patient_id']])){
                    $drug_id = $data['drug_id'];
                    if(isset($parent_drug_arr[$drug_id]) && !empty($parent_drug_arr[$drug_id])){
                        $drug_id = $parent_drug_arr[$drug_id];
                    }
                    if(in_array($drug_id,$drug_arr)) {
                        $this->LocalService()->collectPatientdrug->savePatientdrugData([
                            'item_id' => $patient_arr[$data['patient_id']]['item_id'],
                            'itemsig_id' => $patient_arr[$data['patient_id']]['itemsig_id'],
                            'patient_id' => $data['patient_id'],
                            'drug_id' => [$data['drug_id']],
                            'user_id' => $data['create_user_id'],
                            'time' => $data['create_time']
                        ]);
                    }
                    unset($drug_id);
                }
                unset($datas[$dataKey]);
            }
        }

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

        return $last_id;
    }
}