<?php

namespace Application\Service\DB\Doctoradvice;

use Application\Common\StatusCode;
use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Interop\Container\ContainerInterface;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\DateHelper;
use Laminas\Db\Sql\Expression;
use Application\Form\item\patient\PatientFormModel;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Stdlib\ArrayUtils;
use Laminas\Stdlib\Parameters;

class DoctoradviceOriginal extends \Application\Service\DB\AbstractDb
{
    private $matchRatio = 90;
    private $matchRatio_many = 70;

    //长期医嘱：LMO
    //临时医嘱：TMO
    private $DoctoradviceType = ['TMO'=>1,'LMO'=>2];

    private $delete_str_arr = ['；','\n',"↑","↓","#","！","~","*","☑","★","◆","。",".","(",")","（","）","?",":","：","√","？","^","<",">","|","、","《","》","，",",","{","}","[","]","【","】","+","--","=","～"];

    private $is_dispensary = 0;

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

    /**
     * Notes : 1、获取项目 2、获取中心 3、获取受试者
     * @param int $type
     * Author:唐伯虎不虎
     * Date:2024/7/10 11:27
     */
    public function getbaseinfo($type,$item_id = 0,$itemsig_id = 0,$limit=20,$offset=0)
    {
        $collectWhere['where'] = [
            'is_del' => 0,
        ];
        if($type == 1){
            $collectWhere['group'] = ['item_id'];
        }elseif($type == 2){
            $collectWhere['where']['item_id'] = $item_id;
            $collectWhere['group'] = ['itemsig_id'];
        }else{
            $collectWhere['where'] = [
                'is_del' => 0,
                'item_id' => $item_id,
                'itemsig_id' => $itemsig_id,
            ];
            $collectWhere['group'] = ['patient_id'];
            $collectWhere['limit'] = $limit;
            $collectWhere['offset'] = $offset;
        }
        $collectWhere['columns'] = ['item_id','itemsig_id','patient_id'];
        $baseData = $this->LocalService()->collectTable->fetchAll($collectWhere);
        if(!empty($baseData)){
            if($type == 1){
                return array_column($baseData,'item_id');
            }elseif($type == 2){
                return array_column($baseData,'itemsig_id');
            }else{
                return array_column($baseData,'patient_id');
            }
        }else{
            throw new InvalidArgumentException("沒有您想要的內容");
        }
    }


    /**
     * Notes : 医嘱识别调用-数据匹配
     * @param int $table_id
     * @return bool
     * Author:唐伯虎不虎
     * Date:2024/7/10 11:05
     */
    public function handleOcrData($annex)
    {
        $annex_id = $annex['annexId'];
        $dataReMatch = 0;
        if(isset($annex['dataReMatch'])) $dataReMatch = 1;
        if(empty($annex_id)) return false;

        $info_type = 0;//数据类型【0 医嘱 1 出院医嘱】
        //获取附件表单ID、检查点ID
        $annexData = $this->LocalService()->patientFormContentImg->fetchOne([
            'where'=> [
                'is_del' => 0,
                'id' => $annex_id,
            ],
            'columns'=>['checktime_id','form_id','info_collect_type']
        ]);

        $form_id = !empty($annexData) ? $annexData['form_id'] : 0;
        $checktime_id = !empty($annexData) ? $annexData['checktime_id'] : 0;
        $info_collect_type = !empty($annexData) ? $annexData['info_collect_type'] : 0;
        unset($annexData);
        if(!empty($info_collect_type)){
            $info_collect_type_code = $this->LocalService()->collectCategory->getOneFieldVal('category_code',[
                'is_del' => 0,
                'id' => $info_collect_type,
            ]);
            if($info_collect_type_code == 'DischargeRecord'){
                $info_type = 1;
            }
            unset($info_collect_type_code);
        }
        unset($info_collect_type);

        //获取识别内容
        $OcrData = $this->LocalService()->collectTable->fetchOne(['where'=> [
            'is_del' => 0,
            'annex_id' => $annex_id,
        ],'columns'=>['id','item_id','annex_id','itemsig_id','patient_id','content']]);
        $content = !empty($OcrData) ? json_decode($OcrData['content'],true) : [];

        if(empty($OcrData)) return false;
        $item_id = $OcrData['item_id'];

        //获取黑/白名单数据
        $wordDatas = $this->LocalService()->collectMedicalword->wordNameData([
            'is_del' => 0,
        ]);
        $white_word_arr = isset($wordDatas['white_word']) && !empty($wordDatas['white_word']) ? $wordDatas['white_word'] : [];
        $black_word_arr = isset($wordDatas['black_word']) && !empty($wordDatas['black_word']) ? $wordDatas['black_word'] : [];
        $black_white_word_arr = isset($wordDatas['black_white_word']) && !empty($wordDatas['black_white_word']) ? $wordDatas['black_white_word'] : [];
        unset($wordDatas);

        //获取药物字典项数据
        $drugDatas = [];
        $drug = $this->LocalService()->collectDrug->fetchAll(['where'=> [
            'is_del' => 0,
        ],'columns'=>['id','name'],'order'=>['category_type','drug_order']]);
        if(!empty($drug)){
            foreach($drug as  &$drugData){
                $mate_drug_name = $drugData['name'];

                $mate_drug_name = mb_substr($mate_drug_name,0,8);

                if(strpos($mate_drug_name,'(') !== false){
                    $delete_index = strpos($mate_drug_name,'(');
                    $mate_drug_name = substr_replace($mate_drug_name,'',$delete_index);
                    unset($delete_index);
                }
                if(strpos($mate_drug_name,'（') !== false){
                    $delete_index = strpos($mate_drug_name,'（');
                    $mate_drug_name = substr_replace($mate_drug_name,'',$delete_index);
                    unset($delete_index);
                }
                $mate_drug_name = str_replace($this->delete_str_arr,'',$mate_drug_name);

                $drugData['name'] = $mate_drug_name;

                $drugDatas[$drugData['name']] = $drugData;
            }
        }
        unset($drug);

        //获取该项目下的设置的药物信息
        $itemDrugDatas = [];
        $itemDrugs = $this->LocalService()->collectItemdrug->fetchAll(['where'=> [
            'is_del' => 0,
        ],'columns'=>['id','name','drug_id'],'order'=>['category_type','drug_order']]);
        if(!empty($itemDrugs)){
            foreach($itemDrugs as  $itemDrugKey=>&$itemDrug){
                $itemDrug['name'] = mb_substr($itemDrug['name'],0,8);
                if(strpos($itemDrug['name'],'(') !== false){
                    $delete_index = strpos($itemDrug['name'],'(');
                    $itemDrug['name'] = substr_replace($itemDrug['name'],'',$delete_index);
                    unset($delete_index);
                }
                if(strpos($itemDrug['name'],'（') !== false){
                    $delete_index = strpos($itemDrug['name'],'（');
                    $itemDrug['name'] = substr_replace($itemDrug['name'],'',$delete_index);
                    unset($delete_index);
                }
                $itemDrug['name'] = str_replace($this->delete_str_arr,'',$itemDrug['name']);
                $itemDrugDatas[$drugData['name']] = $itemDrug;
                unset($itemDrugs[$itemDrugKey]);
            }
        }
        unset($itemDrugs);


        //如果当前的单子是已经匹配过的，并且是没有匹配出任何数据，那么采用第二种无表头策略
        $historyData = [];
        if($dataReMatch == 1){
            $historyData = $this->LocalService()->doctoradviceOriginal->fetchCol('id',[
                'annex_id' => $annex_id,
                'is_del' => 0,
            ]);
        }

        //获取剂量单位数据
        $takeDatas = $this->LocalService()->collectMedicaltake->fetchAll(['where'=>'is_del = 0 ','columns'=>['id','name','english','take_type','take_number'],'order'=>['take_order']]);

        $arr['table_id']   = $OcrData['id'];
        $arr['item_id']   = $OcrData['item_id'];
        $arr['annex_id']   = $OcrData['annex_id'];
        $arr['itemsig_id'] = $OcrData['itemsig_id'];
        $arr['patient_id'] = $OcrData['patient_id'];
        $arr['info_type'] = $info_type;
        $arr['checktime_id'] = $checktime_id;
        $arr['form_id'] = $form_id;
        $startTime = $endTime = '';

        //出院医嘱 时间存储
        $dischargeorderTime = '';
        $contentLength = count($content);
        $where = [
            'patient_id' => $OcrData['patient_id'],
            'annex_id' => $OcrData['annex_id'],
            'checktime_id' => $checktime_id,
            'form_id' => $form_id,
            'is_lock' => 0,
            'mate_type' => 1,
            'is_del' => 0,
        ];
        foreach($content as $key=>$value){
            if($info_type == 1){
                $arr['medical_name'] = str_replace($this->delete_str_arr,'',$value[1]);
                preg_match('/[\x{4e00}-\x{9fa5}a-zA-Z（）()]+/u', $value[1], $matches);
                $arr['medical_name_reduce'] = $matches[0];

                $arr['ocr_start_date'] = ($value[2] != '未提供') ? $this->timeHandler($value[2]) : '';

                $arr['ocr_end_date'] =  '';
                if($arr['ocr_start_date'] != '')$dischargeorderTime = $arr['ocr_start_date'];
                $this->transformData($arr,$white_word_arr,$black_word_arr,$black_white_word_arr,$drugDatas,$takeDatas);
                //更新出院时间
                if($key == ($contentLength - 1) && $dischargeorderTime != ''){
                    $this->LocalService()->doctoradviceOriginal->update(['medical_date'=>$dischargeorderTime],$where);
                }
                continue;
            }
            if($dataReMatch == 1 && empty($historyData)){
                $contentIndex = [];
            }else{
                list($startIndex,$endIndex,$contentIndex) = $this->mergeData($value[0]);
                //可能存在表头在第二行的情况，向下冗余，提高准确率
                if(empty($contentIndex)){
                    list($startIndex,$endIndex,$contentIndex) = $this->mergeData($value[1]);
                }
            }

            foreach($value as $dataK => $dataV){
                $arr['ocr_start_date'] = '';
                $arr['ocr_end_date'] = '';
                $arr['medical_name'] = '';
                $arr['medical_name_reduce'] = '';

                $dataV = (array)$dataV;
                //空数据
                $filtered = array_filter($dataV);
                if( count($filtered) === 0 && is_array($dataV) == true) continue;

                //临时处理 没有头部 只有两个数组元素
                if(count($dataV) == 2 && empty($contentIndex)){
                    $arr['ocr_start_date'] = str_replace("\n",'',$dataV[0]);

                    $arr['ocr_start_date'] = $this->timeHandler($arr['ocr_start_date']);
                    $arr['medical_name'] = str_replace($this->delete_str_arr,'',$dataV[0]);
                    preg_match('/(\d+)[a-zA-Z]/', $arr['medical_name'], $matches);

                    $arr['dosage_num'] = isset($matches[1]) ? $matches[1] : '';
                    preg_match('/[\x{4e00}-\x{9fa5}a-zA-Z（）()]+/u',str_replace("\n",'',$arr['medical_name']) , $matches);
                    $arr['medical_name_reduce'] = $matches[0];
                    //匹配服用剂量

                    $arr['ocr_end_date'] = $this->timeHandler(str_replace("\n",'',$dataV[1]));;
                }elseif(empty($contentIndex)){
                    //统一方法失效时获取
                    foreach($dataV as $k=>$v){
                        //判断当前是否是时间格式 年月日、月日、十分等情况
                        $v = str_replace("\n",'',$v);

                        $timecheck = $this->timeHandler($v);
                        if(!empty($timecheck) && $k<2 ){
                            $arr['ocr_start_date'] .= $timecheck;
                        }elseif(!empty($timecheck) && $k>2){
                            $arr['ocr_end_date'] .= $timecheck;
                        }else{
                            $arr['medical_name'] .= $v;
                        }
                    }
                    $arr['medical_name_reduce'] = $arr['medical_name'];
                    $arr['matchall'] = count($value) <= 3 ? true : false;

                }else{
                    if($dataK == 0) continue;

                    //统一方法获取
                    foreach($dataV as $k=>$v){
                        $v = str_replace("\n",'',$v);
                        if(in_array($k,$startIndex)){

                            $arr['ocr_start_date'] .= $this->timeHandler($v);;
                        }

                        if(in_array($k,$endIndex)){
                            $arr['ocr_end_date'] .= $this->timeHandler($v);;
                            continue;
                        }

                        if(in_array($k,$contentIndex)){
                            $arr['medical_name'] .= str_replace($this->delete_str_arr,'',$v);
                            preg_match('/(\d+)[a-zA-Z]/', $arr['medical_name'], $matches);
                            $arr['dosage_num'] = isset($matches[1]) ? $matches[1] : '';
                            preg_match('/^[\p{L}\p{N}\p{Zs}\(\)]+/u', str_replace("\n",'',$arr['medical_name']), $matches1);
                            $arr['medical_name_reduce'] .= $matches1[0];
                            continue;
                        }
                        if($arr['medical_name'] == '' && $arr['medical_name_reduce'] == '') continue;
                    }
                    //可能是一整张单子识别成1条了
                    $arr['matchall'] = count($value) <= 3 ? true : false;
                }

                //如果结束时间没有则开始时间赋值结束时间
                if(empty($arr['ocr_end_date']) && !empty($arr['ocr_start_date'])) $arr['ocr_end_date'] =$arr['ocr_start_date'];

                if(!empty($arr['ocr_start_date']) && $startTime == '') $startTime = $arr['ocr_start_date'];
                if(!empty($arr['ocr_end_date']) && $endTime == '') $endTime = $arr['ocr_end_date'];

                $this->transformData($arr,$white_word_arr,$black_word_arr,$black_white_word_arr,$drugDatas,$takeDatas,$itemDrugDatas);
            } 
        }


        //查询当前单子没有时间的数据
        $timeMissingData = $this->LocalService()->doctoradviceOriginal->fetchCol('id',ArrayUtils::merge($where, [
            [
                'or' => [
                    'medical_date' => '',
                    'end_date' => '',
                ]
            ]
        ]));

        if(!empty($timeMissingData)){
            if(!empty($startTime) || !empty($endTime)){
                foreach($timeMissingData as $key=>$value){
                    if(!empty($startTime)) $changeArr['medical_date'] = $startTime;
                    if(!empty($endTime)) $changeArr['end_date'] = $endTime;

                    $this->LocalService()->doctoradviceOriginal->update($changeArr,['id'=>$value]);
                }
            }
        }

        //更新拆分标识
        $this->LocalService()->collectTable->update(['is_split'=>1,'checktime_id'=>$checktime_id,'form_id'=>$form_id], [
            'is_del' => 0,
            'annex_id' => $annex_id,
        ]);

        //如果有出院带药字样，更新当前单子所有数据为 出院带药
        if($this->is_dispensary == 1) $this->LocalService()->doctoradviceOriginal->update(['is_dispensary'=>1],['annex_id'=>$annex_id,'is_del'=>0]);

        //更新受试者药物情况
        $this->LocalService()->swTaskClient->send([
            'svName' => 'collectPatientdrug',
            'methodName' => 'savePatientdrugData',
            'params' => [
                'item_id' => $OcrData['item_id'],
                'itemsig_id' => $OcrData['itemsig_id'],
                'patient_id' => $OcrData['patient_id'],
                'annex_id' => $annex_id
            ]
        ]);

        return true;
    }

    public function timeHandler($date)
    {
        //验证是否是年月日格式
        if(DateHelper::isValidDate($date)){
            return $date;
        }
        //年月日时分
        if(DateHelper::YMDHSisValidDate($date)){
            return $date;
        }

        //验证是否是日/月格式
        if(DateHelper::isDayMonthTime($date)){
            return DateHelper::dateToMonthDay($date);
        }

        return '';
    }


    //整合医嘱数据
    public function mergeData($data)
    {

        $startTime = ['100'=>'开始时间','95'=>'日期','90'=>'时间','98'=>'起始'];

        $doctorAdvice = ['长期医嘱','医嘱','医内容'];

        $endtTime = ['80'=>'执行日期','85'=>'日期','20'=>'停','30'=>'时间','100'=> '停止时间'];

        $startTimeKey = [];

        $endtTimeKey = [];

        $doctorAdviceKey = [];

        foreach($data as $k=>$v){
            $Pending = trim($v);
            $Pending = str_replace("\n",'',$Pending);

            foreach($startTime as $startk=>$startv){
                if(strpos($Pending, $startv) !== false && count($startTimeKey) < 2) {
                    $startTimeKey[$startk] = $k;
                    if(isset($data[$k-1]) && empty($data[$k-1]) && !in_array($k-1,$startTimeKey))$startTimeKey[] = $k-1;
                    if(isset($data[$k+1]) && empty($data[$k+1]) && !in_array($k+1,$startTimeKey))$startTimeKey[] = $k+1;
                }
                continue;
            }


            foreach($endtTime as $endk=>$endv){
                if(strpos($Pending, $endv) !== false && count($endtTimeKey) < 2 && !in_array($k,$startTimeKey)) {
                    $endtTimeKey[$endk] = $k;
                }
                continue;
            }

            foreach($doctorAdvice as $endk=>$endv){
                if(strpos($Pending, $endv) !== false && empty($doctorAdviceKey)) {
                    $doctorAdviceKey[] = $k;
                    //复杂表格可能出现医嘱列名与内容不对称的情况

                    if(!isset($data[$k-1]))$doctorAdviceKey[] = $k-1;
                    if(!isset($data[$k+1]))$doctorAdviceKey[] = $k+1;

                }
                continue;
            }
        }
        if(!empty($doctorAdviceKey)) $doctorAdviceKey = array_unique($doctorAdviceKey);
        if(empty($endtTimeKey) && !empty($startTimeKey)) $endtTimeKey = $startTimeKey;
        return [$startTimeKey,$endtTimeKey,$doctorAdviceKey];
    }


    public function transformData($data,$white_word_arr,&$black_word_arr=[],&$black_white_word_arr=[],&$drug_arr=[],&$takeDatas=[],&$item_drug_arr = [])
    {
        //去除左右空格
        $medical_name = trim($data['medical_name']);
        //识别时间拼接医嘱名称
        $mate_medical_name = trim($data['ocr_start_date']).$medical_name;

        //字符串替换
        $mate_medical_name = str_replace($this->delete_str_arr,'',$mate_medical_name);

        $mate_medical_name .= trim($data['ocr_end_date']);

        $data['medical_name'] = $mate_medical_name;

        $mate_type = 0;

        //获取当前药物是白名单、还是黑名单

        //已匹配上白名单的词
        $white_word = [];
        if(!empty($white_word_arr)){
            foreach($white_word_arr as $white_word_str){
                if(strpos($mate_medical_name,$white_word_str) !== false){
                    $white_word[] = $white_word_str;
                }
            }
        }

        if (!empty($white_word)) {
            //已匹配上黑名单的词
            $black_word = [];
            if(!empty($black_word_arr)){
                foreach($black_word_arr as $black_word_str){
                    if(strpos($mate_medical_name,$black_word_str) !== false){
                        $black_word[] = $black_word_str;
                    }
                }
            }

            if (!empty($black_word)) {
                //已匹配上黑名单下的白名单词
                $black_white_word = [];
                if(!empty($black_white_word_arr)){
                    foreach($black_white_word_arr as $black_white_word_str){
                        if(strpos($mate_medical_name,$black_white_word_str) !== false){
                            $black_white_word[] = $black_white_word_str;
                        }
                    }
                }
                if (empty($black_white_word)) {
                    $mate_type = 2;
                } else {
                    $mate_type = 1;
                }
                unset($black_white_word);
            } else {
                $mate_type = 1;
            }
            unset($black_word);
        }
        unset($white_word);
        unset($medical_name_arr);

        //更新日期
        $medical_date = trim($data['ocr_start_date']);

        $medical_date = strlen($medical_date) > 3 ? $medical_date : '';

        $medical_date = $this->LocalService()->ocrRawdata->replaceRawdata($medical_date,1);

        $data['medical_date'] = $medical_date != '' ? $medical_date : '';

        //更新日期
        $end_date = trim($data['ocr_end_date']);
        $end_date = strlen($end_date) > 3 ? $end_date : '';
        $end_date = $this->LocalService()->ocrRawdata->replaceRawdata($end_date,1);
        $data['end_date'] = $end_date != '' ? $end_date : '';

        //获取匹配的药物名称
        $dosage_id = $dosage_unit = $dosage_way = $dosage_times = $is_dispensary = $drug_id = 0;
        $drug_name = '';

        if($data['matchall'] == true) $mate_type = 1;

        if($mate_type == 1){
            if($data['matchall'] == true){
                unset($data['matchall']);
                $mateAllDrug = $this->mateAllDrugData($data,$drug_arr,$item_drug_arr);
                if(!empty($mateAllDrug)){

                    foreach($mateAllDrug as $k=>$v){
                        $originalData = [
                            'mate_type' => 1,
                            'is_lock'=>0,
                            'drug_id'=>$v['id'],
                            'name'=>$v['name']
                        ];
                        if($data['info_type'] == 1) $originalData['is_dispensary'] = 1;

                        $this->insert(array_merge($originalData,$data));
                    }
                }
                return true;
            }else{
                $mate_drug = $this->mateDrugdata($data,$drug_arr,$item_drug_arr);
            }

            $drug_id = $mate_drug['id'];
            $drug_name = $mate_drug['name'];
            //如果符合白名单并且没有匹配上药物则默认未匹配
            if(!$drug_id && $mate_type == 1) return true;
            if(!empty($takeDatas)){
                foreach($takeDatas as $takeDataType=>$takeData){

                    $takeData_id = $takeData['id'];
                    $takeData_name = $takeData['name'];
                    $takeData_english = $takeData['english'];
                    $takeData_type = $takeData['take_type'];

                    //规格
                    if($takeData_type == 1){
                        if(empty($dosage_id) && strpos($medical_name,$takeData_name) !== false){
                            $dosage_id = $takeData_id;
                            continue;
                        }
                        if(empty($dosage_id) && !empty($takeData_english) && strpos($medical_name,$takeData_english) !== false){
                            $dosage_id = $takeData_id;
                            continue;
                        }
                    }

                    //剂量单位
                    if($takeData_type == 2){

                        if(empty($dosage_unit) && strpos($medical_name,$takeData_name) !== false){
                            $dosage_unit = $takeData_id;
                            continue;
                        }
                        if(empty($dosage_unit) && !empty($takeData_english) && strpos($medical_name,$takeData_english) !== false){
                            $dosage_unit = $takeData_id;
                            continue;
                        }

                    }

                    //服用方式
                    if($takeData_type == 3){
                        if(empty($dosage_way) && strpos($medical_name,$takeData_name) !== false){
                            $dosage_way = $takeData_id;
                            continue;
                        }
                        if(empty($dosage_way) && !empty($takeData_english) && strpos($medical_name,$takeData_english) !== false){
                            $dosage_way = $takeData_id;
                            continue;
                        }
                    }

                    //服用频率
                    if($takeData_type == 4){
                        if(empty($dosage_times) && strpos($medical_name,$takeData_name) !== false){
                            $dosage_times = $takeData_id;
                            continue;
                        }
                        if(empty($dosage_times) && !empty($takeData_english) && strpos($medical_name,$takeData_english) !== false){
                            $dosage_times = $takeData_id;
                            continue;
                        }
                    }

                    //出院带药
                    if($takeData_type == 5){
                        if(empty($is_dispensary) && strpos($medical_name,$takeData_name) !== false){
                            $is_dispensary = $takeData_id;
                            continue;
                        }
                        if(empty($is_dispensary) && !empty($takeData_english) && strpos($medical_name,$takeData_english) !== false){
                            $is_dispensary = $takeData_id;
                            continue;
                        }
                    }
                }
            }

            $originalData = [
                'mate_type' => $mate_type,
                'is_lock'=>0,
                'medical_date'=>$medical_date,
                'end_date'=>$end_date,
                'drug_id'=>$drug_id,
                'dosage_id'=>$dosage_id,
                'dosage_unit'=>$dosage_unit,
                'dosage_way'=>$dosage_way,
                'dosage_times'=>$dosage_times,
                'is_dispensary'=>$is_dispensary,
                'name'=>$drug_name
            ];
            $originalData = array_merge($originalData,$data);

            //出院医嘱 取药（出院带药） 默认为 是
            if($data['info_type'] == 1){
                $originalData['is_dispensary'] = 1;

                $update = [];
                $changeOcrEndDate = $this->timeHandler(trim($data['ocr_end_date']));
                if(!empty($changeOcrEndDate)){
                    $update['ocr_end_date'] = $changeOcrEndDate;
                }
                $changeEndDate = $this->timeHandler(trim($data['end_date']));
                if($this->timeHandler(trim($data['end_date']))){
                    $update['end_date'] = $changeEndDate;
                }

                //查询已保存数据
                $storageDatas = $this->fetchCol('medical_name',[
                    'is_del' => 0,
                    'mate_type' => 1,
                    'annex_id' => $data['annex_id'],
                ]);
                if(!empty($storageDatas)){
                    foreach($storageDatas as $key=>$value){
                        $update['medical_name'] = $update['ocr_end_date'].$value;
                        $this->update($update,['id'=>$key]);
                    }
                }

            }
            unset($originalData['matchall']);
            $this->insert($originalData);
        }


    }


    /**
     * Notes : 获取医嘱详细信息
     * @param $patient_id
     * @param $annex_id
     * @param int $type
     * @param $sig_id
     * @param $is_lock
     * @param $item_id
     * @param $info_type //数据类型【0 医嘱用药  1 出院医嘱用药】
     * @return mixed
     * Author:唐伯虎不虎
     * Date:2024/7/11 15:52
     */
    public function getannexinfo($patient_id,$annex_id,$type=1,$sig_id,$is_lock,$item_id,$info_type=0)
    {
        $info_type = empty($info_type) ? 0 : $info_type;
        //获取受试者附件产生的用药信息
        $doctoradviceWhere['where'] = [
            'patient_id' => $patient_id,
            'annex_id' => $annex_id,
            'is_del' => 0,
            'info_type' => $info_type,
        ];
        if($is_lock == 0) $doctoradviceWhere['where']['mate_type'] = 1 ;
        if($is_lock == 1) $doctoradviceWhere['where']['is_lock']= 1;
        $doctoradviceWhere['columns'] = ['id','medical_date','medical_name','end_date','drug_id','dosage_num','dosage_unit','dosage_id','dosage_way','dosage_times','is_dispensary','adjust_num','checktime_id'];
        $doctoradviceWhere['order'] = ['id'];

        $datas = $this->LocalService()->doctoradviceOriginal->fetchAll($doctoradviceWhere);

        if(!empty($datas)){
            //获取项目字典项用药ID
            $save_drug_arr = [];
            foreach($datas as $ocrContentInfo){
                if(!empty($ocrContentInfo['drug_id']) && !in_array($ocrContentInfo['drug_id'],$save_drug_arr)){
                    $save_drug_arr[] = $ocrContentInfo['drug_id'];
                }
            }

            //获取历史已锁定药物数据【锁定：获取当前受试者，当前药物历史已锁定数据】
            $sigLockContentDatas = $this->LocalService()->doctoradviceOriginal->fetchDrugDataByPatientSig(['no_annex'=>$annex_id,'item_id'=>$item_id,'drug_arr'=>$save_drug_arr]);


            //获取药物名称信息
            $drugNameArr = [];
            if(!empty($save_drug_arr)){
                $drugNameArr = $this->LocalService()->collectDrug->fetchCol('name',[
                    'is_del' => 0,
                    'id' => $save_drug_arr,
                ]);
            }
            unset($save_drug_arr);

            $lockDrugDetails = [];
            if(isset($sigLockContentDatas['patient_drug'])){
                $lockDrugDetails = isset($sigLockContentDatas['patient_drug'][$patient_id]) && !empty($sigLockContentDatas['patient_drug'][$patient_id]) ? $sigLockContentDatas['patient_drug'][$patient_id] : [];
                unset($sigLockContentDatas['patient_drug']);
            }

            //项目中用药字典项
            $takeInfos = $this->LocalService()->collectMedicaltake->fetchAll(['where'=>'is_del = 0 ','columns'=>['id','english','name']]);
            if(!empty($takeInfos)){
                $takeNameArr = ArrayHelper::index($takeInfos, 'id');
                unset($takeInfos);
            }

            //出院医嘱开始时间  获取住院医嘱最大的结束日期
            $maxDate = '';
            if($info_type == 1){
                $checktime_id = $datas[0]['checktime_id'];
                $maxDate = $this->getmaxdate($patient_id,$checktime_id)['maxDate'];
            }



            foreach($datas as $k=>&$info){


                $info_drug_id = !is_null($info['drug_id']) && !empty($info['drug_id']) ? $info['drug_id'] : 0;
                //获取用药名称

                $info['name'] = isset($drugNameArr[$info_drug_id]) && !empty($drugNameArr[$info_drug_id]) ? $drugNameArr[$info_drug_id] : '';
                $info['medical_date'] = !is_null($info['medical_date']) && !empty($info['medical_date']) ? $info['medical_date'] : '';//开始日期

                if($info_type == 1 && $info['medical_date'] == '' && $maxDate != ''){
                    $info['medical_date'] = $maxDate;
                }
                $info['end_date'] = strpos($info['end_date'], '-') !== false ? $this->LocalService()->ocrRawdata->replaceRawdata($info['end_date'],1) : $info['end_date'];

                $info['end_date'] = !is_null($info['end_date']) && !empty($info['end_date']) ? $info['end_date'] : '';//结束日期


                $info['drug_id'] = !is_null($info['drug_id']) && !empty($info['drug_id']) ? $info['drug_id'] : '';//药物
                $info['dosage_num'] = !is_null($info['dosage_num']) && $info['dosage_num'] != '' ? $info['dosage_num'] : '';//剂量
                $info['dosage_unit'] = !is_null($info['dosage_unit']) && !empty($info['dosage_unit']) ? $info['dosage_unit'] : '';//剂量单位
                $info['dosage_way'] = !is_null($info['dosage_way']) && !empty($info['dosage_way']) ? $info['dosage_way'] : '';//服用方式
                $info['dosage_times'] = !is_null($info['dosage_times']) && !empty($info['dosage_times']) ? $info['dosage_times'] : '';//服用频次
                $info['adjust_num'] = !is_null($info['adjust_num']) && !empty($info['adjust_num']) ? $info['adjust_num'] : '';//调整量
                $info['medical_name'] = !is_null($info['medical_name']) && !empty($info['medical_name']) ? $info['medical_name'] : '';

                $content_drug = !empty($info['drug_id']) ? $info['drug_id'] : 0;
                $info['other_save'] = isset($lockDrugDetails) && !empty($lockDrugDetails[$content_drug]) ? $lockDrugDetails[$content_drug] : '';

                //未锁定
                if($is_lock != 1){
                    //获取默认锁定信息
                    $lockDrug = [];
                    if(isset($sigLockContentDatas['patient'][$patient_id]) && isset($sigLockContentDatas['patient'][$patient_id][$content_drug]) && !empty($sigLockContentDatas['patient'][$patient_id][$content_drug])){
                        $lockDrug = $sigLockContentDatas['patient'][$patient_id][$content_drug];
                    }else{
                        if(isset($sigLockContentDatas['sig'][$sig_id]) && isset($sigLockContentDatas['sig'][$sig_id][$content_drug]) && !empty($sigLockContentDatas['sig'][$sig_id][$content_drug])){
                            $lockDrug = $sigLockContentDatas['sig'][$sig_id][$content_drug];
                        }else{
                            if(isset($sigLockContentDatas['all'][$content_drug]) && !empty($sigLockContentDatas['all'][$content_drug])){
                                $lockDrug = $sigLockContentDatas['all'][$content_drug];
                            }else{
                                $lockDrug = $this->LocalService()->collectDrug->fetchOne([
                                    'where' => [
                                        'is_del' => 0,
                                        'id' => $content_drug,
                                    ],
                                    'columns'=>['dosage_num','dosage_unit','dosage_times','dosage_way','is_dispensary']
                                ]);

                            }
                        }
                    }

                    if(!empty($lockDrug)){
                        //无剂量默认获取当前患者或当前中心该药物已锁定的剂量
                        if(empty($info['dosage_num'])){
                            if(isset($lockDrug['dosage_num']) && !empty($lockDrug['dosage_num'])){
                                $info['dosage_num'] = $lockDrug['dosage_num'];
                            }
                        }

                        if(empty($info['dosage_unit'])){
                            if(isset($lockDrug['dosage_unit']) && !empty($lockDrug['dosage_unit'])){
                                $info['dosage_unit'] = $lockDrug['dosage_unit'];
                            }
                        }


                        //无服用频率默认获取当前患者或当前中心该药物已锁定的服用频率
                        if(empty($info['dosage_times'])){
                            if(isset($lockDrug['dosage_times']) && !empty($lockDrug['dosage_times'])){
                                $info['dosage_times'] = $lockDrug['dosage_times'];
                            }
                        }

                        if(empty($info['dosage_way'])){
                            if(isset($lockDrug['dosage_way']) && !empty($lockDrug['dosage_way'])){
                                $info['dosage_way'] = $lockDrug['dosage_way'];
                            }
                        }
                    }

                    $info['is_dispensary'] = !empty($info['is_dispensary']) ? $info['is_dispensary'] : '';
                    $info['date_bool'] = $info['end_date_bool'] = 0;
                    // 开始时间
                    if (!is_null($info['medical_date']) && $info['medical_date'] != '') {
                        $info['medical_date'] = $this->LocalService()->ocrRawdata->replaceRawdata($info['medical_date'], 2);
                        $info['medical_date'] = substr($info['medical_date'], 0, 8);
                    }

                    $validDate = $this->LocalService()->tmpDoctoradviceannex->validAnnexDate($info['medical_date']);
                    $ocrContent['date_bool'] = 1;

                    $validEndDate = $this->LocalService()->tmpDoctoradviceannex->validAnnexDate($info['end_date']);

                    if($validEndDate['code'] != 200){
                        $info['end_date'] = $info['medical_date'];
                    }else{
                        if(!empty($info['medical_date']) && !empty($contentData['end_date']) && ($info['end_date'] < $info['medical_date'])){
                            $info['end_date'] = $info['medical_date'];
                        }

                        //有结束日期无开始日期  则 开始日期 = 结束日期
                        if(empty($contentData['medical_date']) && !empty($contentData['end_date'])){
                            $info['end_date'] = $info['medical_date'];
                        }
                    }
                    $info['medical_date'] = $validDate['date'];

                    $info['end_date_bool'] = 1;


//

                }
                if($type == 0){
                    if(!empty($info['dosage_unit'])){
                        $dosage_unit = $info['dosage_unit'];
                        $info['dosage_unit'] = isset($takeNameArr[$dosage_unit]) && !empty($dosage_unit) ? $takeNameArr[$dosage_unit]['name'] : '';
                        if(isset($takeNameArr[$dosage_unit]) && !empty($dosage_unit) && !empty($takeNameArr[$dosage_unit]['english'])) $info['dosage_unit'].= '('.$takeNameArr[$dosage_unit]['english'].')';
                    }

                    if(!empty($info['dosage_times'])){
                        $dosage_times = $info['dosage_times'];
                        $info['dosage_times'] = isset($takeNameArr[$dosage_times]) && !empty($dosage_times) ? $takeNameArr[$dosage_times]['name'] : '';
                        if(isset($takeNameArr[$dosage_times]) && !empty($dosage_times) && !empty($takeNameArr[$dosage_times]['english'])) $info['dosage_times'].= '('.$takeNameArr[$dosage_times]['english'].')';
                    }

                    if(!empty($info['dosage_way'])){
                        $dosage_way = $info['dosage_way'];
                        $info['dosage_way'] = isset($takeNameArr[$dosage_way]) && !empty($dosage_way) ? $takeNameArr[$dosage_way]['name'] : '';
                        if(isset($takeNameArr[$dosage_way]) && !empty($dosage_way) && !empty($takeNameArr[$dosage_way]['english'])) $info['dosage_way'].= '('.$takeNameArr[$dosage_way]['english'].')';
                    }


                    //取药（出院带药）
                    $info['is_dispensary'] = !empty($info['is_dispensary']) ? '是' : '否';

                }
            }
        }

        return $datas;
    }


    public function getmaxdate($patient_id,$checktime_id)
    {
        $BatchData = $this->fetchOne([
            'where'=> [
                'patient_id' => $patient_id,
                'checktime_id' => $checktime_id,
                'is_del' => 0,
                'mate_type' => 1,
                'is_lock' => 1,
            ],
            'columns'=>[new Expression('max(`end_date`) as `maxDate`')]
        ]);

        return $BatchData;
    }


    /**
     * Notes : 获取受试者锁定药物信息
     * @param array $info
     * @return array[]
     * Author:唐伯虎不虎
     * Date:2024/7/11 14:12
     */
    public function fetchDrugDataByPatientSig(array $info=[]){

        $no_annex = isset($info['no_annex']) && !empty($info['no_annex']) ? $info['no_annex'] : 0;
        $drug_id = isset($info['drug_id']) && !empty($info['drug_id']) ? $info['drug_id'] : 0;
        $sig_id = isset($info['sig_id']) && !empty($info['sig_id']) ? $info['sig_id'] : 0;
        $patient_id = isset($info['patient_id']) && !empty($info['patient_id']) ? $info['patient_id'] : 0;
        $drug_arr = isset($info['drug_arr']) && !empty($info['drug_arr']) ? $info['drug_arr'] : [];
        $noselect_take = isset($info['noselect_take']) && !empty($info['noselect_take']) ? $info['noselect_take'] : 0;
        $item_id = isset($info['item_id']) && !empty($info['item_id']) ? $info['item_id'] : 0;

        $arr = [
            'sig'=>[],
            'patient'=>[],
            'all'=>[],
//            'use_num'=>[],
            'patient_drug'=>[],
            'lock_drug'=>[],
//            'lock_drug_data'=>[]
        ];

        $where = $this->_getDrugDataWhere($no_annex,$drug_id,$sig_id,$drug_arr,$patient_id,$item_id);

        $cond = [
            'where'=>$where,
            'columns'=>['itemsig_id','patient_id','drug_id','annex_id','medical_date','end_date','dosage_num','dosage_unit','dosage_way','dosage_times','is_dispensary'],
            'order'=>['medical_date asc','end_date asc']
        ];

        $lockDatas = $this->fetchAll($cond);

        unset($where);   unset($cond);


        if(!empty($lockDatas)){
            $patientDrugDatas = $takeNameArr = [];
            if($noselect_take != 1){
                $takeInfos = $this->LocalService()->collectMedicaltake->fetchAll(['where'=>'is_del = 0 and take_type in (2,3,4) ','columns'=>['id','english','name']]);
                if(!empty($takeInfos)){
                    foreach($takeInfos as $takeKey=>$takeInfo){
                        $takeId = $takeInfo['id'];
                        $takeNameArr[$takeId] = !empty($takeInfo['english']) ? $takeInfo['name'].'('.$takeInfo['english'].')' : $takeInfo['name'];
                        unset($takeInfos[$takeKey]);
                    }
                }
                unset($takeInfos);
            }


            foreach($lockDatas as $lockKey=>$lockData){
                //中心ID
                $lock_sig = $lockData['itemsig_id'];
                //受试者ID
                $lock_patient = $lockData['patient_id'];
                //药物ID
                $lock_drug = $lockData['drug_id'];

                //根据不同情况赋值
                if(!isset($arr['sig'][$lock_sig][$lock_drug])){
                    $arr['sig'][$lock_sig][$lock_drug] = $lockData;
                }
                if(!isset($arr['patient'][$lock_patient][$lock_drug])){
                    $arr['patient'][$lock_patient][$lock_drug] = $lockData;
                }
                if(!isset($arr['all'][$lock_drug])){
                    $arr['all'][$lock_drug] = $lockData;
                }

                //开始时间
                $medical_date = !is_null($lockData['medical_date']) && !empty($lockData['medical_date']) ? $lockData['medical_date'] : 0;
                if(!empty($medical_date)){
                    $patientDrugDatas[$lock_patient][$lock_drug]['start_date'][] = $medical_date;
                }

                //结束时间
                $end_date = !is_null($lockData['end_date']) && !empty($lockData['end_date']) ? $lockData['end_date'] : 0;
                if(!empty($end_date)){
                    $patientDrugDatas[$lock_patient][$lock_drug]['end_date'][] = $end_date;
                }

                //日总剂量
                $dosage_num = !is_null($lockData['dosage_num']) && !empty($lockData['dosage_num']) ? $lockData['dosage_num'] : 0;
                //剂量单位
                $dosage_unit = !is_null($lockData['dosage_unit']) && !empty($lockData['dosage_unit']) ? $lockData['dosage_unit'] : 0;

//                $num_unit = $dosage_num;
                if(!empty($dosage_num)){
                    if(!empty($dosage_unit) && isset($takeNameArr[$dosage_unit]) && !empty($takeNameArr[$dosage_unit])){
//                        $num_unit .= '（'.$takeNameArr[$dosage_unit].'）';
                        $patientDrugDatas[$lock_patient][$lock_drug]['dosage_num'][] = $dosage_num.$takeNameArr[$dosage_unit];
                    }else{
                        $patientDrugDatas[$lock_patient][$lock_drug]['dosage_num'][] = $dosage_num;
                    }
                }
                //服用频次
                $times_id = !is_null($lockData['dosage_times']) && !empty($lockData['dosage_times']) ? $lockData['dosage_times'] : 0;
                if(!empty($times_id)) $patientDrugDatas[$lock_patient][$lock_drug]['dosage_times'][] = $times_id;

                //取药（出院带药）
                if($lockData['is_dispensary'] == 1) $patientDrugDatas[$lock_patient][$lock_drug]['is_dispensary'] = 1;

                unset($lockDatas[$lockKey]);
            }

            if(!empty($patientDrugDatas)){
                foreach($patientDrugDatas as $patientId=>$lockDrugDatas){
                    foreach($lockDrugDatas as $lockDrugId=>$lockDrugData){

                        $lock_mes_arr = [];//展示信息

                        //开始日期
                        $drug_startdate_arr = isset($lockDrugData['start_date']) && !empty($lockDrugData['start_date']) ? $lockDrugData['start_date'] : [];
                        $drug_startdate_arr = array_unique($drug_startdate_arr);
                        $drug_startdate_arr = array_values($drug_startdate_arr);
                        sort($drug_startdate_arr);
                        if(!empty($drug_startdate_arr)){
                            $lock_mes_arr[] = '（'.$drug_startdate_arr[0].'）';
                        }

                        $arr['lock_drug'][$patientId][$lockDrugId]['medical_date'] = !empty($drug_startdate_arr) ? $drug_startdate_arr[0] : '';
                        unset($drug_startdate_arr);

                        //剂量
                        $drug_dosagenum_arr = isset($lockDrugData['dosage_num']) && !empty($lockDrugData['dosage_num']) ? $lockDrugData['dosage_num'] : [];
                        $drug_dosagenum_arr = array_unique($drug_dosagenum_arr);
                        $drug_dosagenum_arr = array_values($drug_dosagenum_arr);
                        if(!empty($drug_dosagenum_arr)){
                            $lock_mes_arr[] = '（'.implode('/',$drug_dosagenum_arr).'）';
                        }
                        $arr['lock_drug'][$patientId][$lockDrugId]['dosage_num'] = $drug_dosagenum_arr;
                        unset($drug_dosagenum_arr);

                        //服用频率
                        $drug_timesid_arr = isset($lockDrugData['dosage_times']) && !empty($lockDrugData['dosage_times']) ? $lockDrugData['dosage_times'] : [];
                        $drug_timesid_arr = array_unique($drug_timesid_arr);
                        $drug_timesid_arr = array_values($drug_timesid_arr);
                        $drug_timesid_name = [];
                        if(!empty($drug_timesid_arr)){
                            foreach($drug_timesid_arr as $drug_timesid){
                                if(isset($takeNameArr[$drug_timesid]) && !empty($takeNameArr[$drug_timesid])){
                                    $drug_timesid_name[] = $takeNameArr[$drug_timesid];
                                }
                            }
                            $lock_mes_arr[] = '（'.implode('/',$drug_timesid_name).'）';
                        }
                        $arr['lock_drug'][$patientId][$lockDrugId]['dosage_times'] = $drug_timesid_name;
                        unset($drug_timesid_arr);
                        unset($drug_timesid_name);

                        //结束日期
                        $drug_enddate_arr = isset($lockDrugData['end_date']) && !empty($lockDrugData['end_date']) ? $lockDrugData['end_date'] : [];
                        $drug_enddate_arr = array_unique($drug_enddate_arr);
                        $drug_enddate_arr = array_values($drug_enddate_arr);
                        rsort ($drug_enddate_arr);
                        if(!empty($drug_enddate_arr)){
                            $lock_mes_arr[] = '（'.$drug_enddate_arr[0].'）';
                        }
                        $arr['lock_drug'][$patientId][$lockDrugId]['end_date'] = !empty($drug_enddate_arr) ? $drug_enddate_arr[0] : '';
                        unset($drug_enddate_arr);

                        //结束日期
                        $arr['lock_drug'][$patientId][$lockDrugId]['is_dispensary'] = 0;
                        if(isset($lockDrugData['is_dispensary']) && $lockDrugData['is_dispensary'] == 1){
                            $lock_mes_arr[] = '（取药）';
                            $arr['lock_drug'][$patientId][$lockDrugId]['is_dispensary'] = 1;
                        }
                        $arr['patient_drug'][$patientId][$lockDrugId] = implode('、',$lock_mes_arr);

                        unset($lock_mes_arr);
                        unset($lockDrugDatas[$lockDrugId]);
                    }
                    unset($patientDrugDatas[$patientId]);
                }
                unset($takeNameArr);
            }
            unset($patientDrugDatas);
        }
        unset($lockDatas);
        return $arr;
    }


    /**
     * Notes : 通过annex_id 获取表单医嘱类型
     * @param $annex_id
     * @return int
     * Author:唐伯虎不虎
     * Date:2024/7/12 14:03
     */
    public function _getDoctoradviceType($annex_id)
    {
        $form_id = $this->LocalService()->patientFormContentImg->getOneFieldVal('form_id',[
            'id' => $annex_id,
        ]);

        $FormVarName = $this->LocalService()->itemForm->getOneFieldVal('var_name',[
            'id' => $form_id,
        ]);
        return ($this->DoctoradviceType[$FormVarName] > 0) ? $this->DoctoradviceType[$FormVarName] : 0;
    }


    /**
     * Notes : 生成Where条件
     * @param $no_annex
     * @param $drug_id
     * @param $sig_id
     * @param $drug_arr
     * @param $patient_id
     * @return string
     * Author:唐伯虎不虎
     * Date:2024/7/12 14:03
     */
    public function _getDrugDataWhere($no_annex,$drug_id,$sig_id,$drug_arr,$patient_id,$item_id)
    {
        $where = [
            'is_del' => 0,
            'is_lock' => 1,
            'item_id' => $item_id,
        ];
        if(!empty($no_annex)) $where[] = new Operator('annex_id', Operator::OP_NE, $no_annex);
        //药物ID
        if(!empty($drug_id)){
            $where['drug_id'] = $drug_id;
        }
        if(!empty($drug_arr)){
            $where['drug_id'] = $drug_arr;
        }
        if(!empty($sig_id)){
            $where['itemsig_id'] = $sig_id;
        }
        if(!empty($patient_id)){
            $where['patient_id'] = $patient_id;
        }
        return $where;
    }

    /**
     * Notes : 匹配药物
     * @param array $medicalData
     * @param array $drugDatas
     * @return int|mixed
     * Author:唐伯虎不虎
     * Date:2024/2/1 10:43
     */
    public function mateDrugdata(array $medicalData, array $drugDatas, array $itemDrugDatas=[]) {
        //医嘱为空，返回[]
        if(empty($medicalData['medical_name_reduce']))   return ['id'=>0,'name'=>''];

        //如果能直接命中 则直接返回
        if(isset($itemDrugDatas[$medicalData['medical_name_reduce']])){
            return ['id'=>$itemDrugDatas[$medicalData['medical_name_reduce']]['drug_id'],'name'=>$itemDrugDatas[$medicalData['medical_name_reduce']]['name']];
        }else{
            if(isset($drugDatas[$medicalData['medical_name_reduce']])) {
                return ['id'=>$drugDatas[$medicalData['medical_name_reduce']]['id'],'name'=>$drugDatas[$medicalData['medical_name_reduce']]['name']];
            }
        }

        $firstArr = [];
        if(!empty($itemDrugDatas)){
            foreach($itemDrugDatas as &$itemDrugData) {
                if($isMate = $this->mateStr($medicalData['medical_name_reduce'], $itemDrugData['name'])) {
                    $matchRate = $this->stringdistance($itemDrugData['name'],$medicalData['medical_name_reduce']);
                    if(isset($firstArr['matchRate']) && $matchRate > $firstArr['matchRate']){
                        $firstArr['id'] = $itemDrugData['drug_id'];
                        $firstArr['name'] = $itemDrugData['name'];
                        $firstArr['matchRate'] =$matchRate;
                    }elseif(!isset($firstArr['matchRate'])){
                        $firstArr['id'] = $itemDrugData['drug_id'];
                        $firstArr['name'] = $itemDrugData['name'];
                        $firstArr['matchRate'] =$matchRate;
                    }
                }
            }
        }
        if(empty($firstArr) && !empty($drugDatas)){
            foreach($drugDatas as &$drugData) {
                if($isMate = $this->mateStr($medicalData['medical_name_reduce'], $drugData['name'])) {
                    $matchRate = $this->stringdistance($drugData['name'],$medicalData['medical_name_reduce']);
                    if(isset($firstArr['matchRate']) && $matchRate > $firstArr['matchRate']){
                        $firstArr['id'] = $drugData['id'];
                        $firstArr['name'] = $drugData['name'];
                        $firstArr['matchRate'] =$matchRate;
                    }elseif(!isset($firstArr['matchRate'])){
                        $firstArr['id'] = $drugData['id'];
                        $firstArr['name'] = $drugData['name'];
                        $firstArr['matchRate'] =$matchRate;
                    }

                }
            }
        }

        if(!empty($firstArr)){
            $TmpStr = str_replace('-','',$firstArr['name']);
            if(ctype_digit($TmpStr)) return ['id'=>0,'name'=>''];
            return $firstArr;
        }

        $match = [];
        $arr = [];
        $matchDrug = [];//项目药物对应的项目药物ID
        if(!$isMate) {
            //字符串拆分药物匹配，分词平均匹配率大于70即可匹配成功
            $number = mb_strlen($medicalData['medical_name_reduce']);
            for ($i = 0; $i < $number; $i++) {
                $searhWord = mb_substr($medicalData['medical_name_reduce'],$i,2,'UTF-8');
                if(mb_strlen($searhWord) < 2) continue;
                if(!empty($itemDrugDatas)){
                    foreach($itemDrugDatas as $itemDrugDataVal) {
                        if(!is_string($itemDrugDataVal['name'])) continue;
                        if($this->mateStr($itemDrugDataVal['name'], $searhWord)) {
                            $matchRate = $this->stringdistance($itemDrugDataVal['name'],$medicalData['medical_name_reduce']);
                            if(($matchRate >= $this->matchRatio_many)){
                                $match[$itemDrugDataVal['drug_id']] = $matchRate;
                                $matchDrug[$itemDrugDataVal['drug_id']]['name'] = $itemDrugDataVal['name'];
                            }
                        }
                    }
                }
                if(empty($match) && !empty($drugDatas)){
                    foreach($drugDatas as $drugvalue) {
                        if(!is_string($drugvalue['name'])) continue;
                        if($this->mateStr($drugvalue['name'], $searhWord)) {
                            $matchRate = $this->stringdistance($drugvalue['name'],$medicalData['medical_name_reduce']);
                            if(($matchRate >= $this->matchRatio_many)){
                                $match[$drugvalue['id']] = $matchRate;
                                $matchDrug[$drugvalue['drug_id']]['name'] = $drugvalue['name'];
                            }
                        }
                    }
                }
            }
        }
        if(!empty($match)){
            $maxValue = max($match);
            $maxKey = array_search($maxValue, $match);
            $arr['id'] = $maxKey;
            $arr['name'] = isset($matchDrug[$maxKey]) && isset($matchDrug[$maxKey]['name']) && $matchDrug[$maxKey]['name'] != '' ? $matchDrug[$maxKey]['name'] : '';
            unset($maxKey);
            unset($maxKey);
        }
        unset($drugItemDrugArr);
        unset($match);

        return ['id'=>empty($arr) ? 0 : $arr['id'],'name'=>empty($arr) ? '' : $arr['name']];
    }

    //一条医嘱内容有多个药物匹配
    public function mateAllDrugData(array $medicalData, array $drugDatas, array $itemDrugDatas=[])
    {
        $mateDrug = [];
        if(!empty($itemDrugDatas)){
            foreach($itemDrugDatas as $itemDrugData){
                if($isMate = $this->mateStr($medicalData['medical_name'], $itemDrugData['name'])) {
                    $mateDrug[$itemDrugData['drug_id']]['id'] = $itemDrugData['drug_id'];
                    $mateDrug[$itemDrugData['drug_id']]['name'] = $itemDrugData['name'];
                }
            }
        }
        if(empty($mateDrug)){
            foreach($drugDatas as &$drugData) {
                if($isMate = $this->mateStr($medicalData['medical_name'], $drugData['name'])) {
                    $mateDrug[$drugData['id']]['id'] = $drugData['id'];
                    $mateDrug[$drugData['id']]['name'] = $drugData['name'];
                }
            }
        }

        $result = [];
        if(!empty($mateDrug)) $result = $this->getSpecificNamesFromArray($mateDrug);

        return $result;
    }


    private function mateStr(string $str, string $searchStr) {
        return stripos($str, $searchStr) !== false;
    }

    public function stringdistance($string1,$string2)
    {
        $distance = levenshtein($string1, $string2);

        $maxLength = max(strlen($string1), strlen($string2));
        return  round((1 - ($distance / $maxLength)) * 100, 2);
    }

    // 优先提取更精确的匹配
    public function getSpecificNamesFromArray(array $items) {
        // 按照 name 的长度从大到小排序
        usort($items, function($a, $b) {
            return strlen($b['name']) - strlen($a['name']);
        });

        $filtered = [];

        foreach ($items as $item) {
            $alreadyMatched = false;
            foreach ($filtered as $fItem) {
                if (strpos($fItem['name'], $item['name']) !== false) {
                    $alreadyMatched = true;
                    break;
                }
            }
            // 如果没有更具体的匹配，将当前项加入结果集
            if (!$alreadyMatched) {
                $filtered[] = $item;
            }
        }

        return $filtered;
    }

    /**
     * Notes : 年月日格式验证
     * @param $dateString
     * @return false|int
     * Author:唐伯虎不虎
     * Date:2024/7/9 14:46
     */
    function isDateFormat($dateString) {
        $pattern = '/^\d{4}-\d{2}-\d{2}$/'; // 定义匹配的正则表达式
        return preg_match($pattern, $dateString);
    }

    /**
     * Notes : 定义匹配的正则表达式
     * @param $timeString
     * @return false|int
     * Author:唐伯虎不虎
     * Date:2024/7/9 14:47
     */
    function isTimeFormat($timeString) {
        $pattern = '/^(0[1-9]|1[0-2])-([0-2][0-9]|3[01])([0-1][0-9]|2[0-3]):([0-5][0-9])$/';
        return preg_match($pattern, $timeString);
    }


    public function _getNamesByIds($item_id,$datas,$type = 1)
    {
        if(empty($datas)) return [];
        //获取 用药信息字典项
        $takeInfos = $this->LocalService()->collectMedicaltake->fetchAll(['where'=>['is_del' => 0],'columns'=>['id','english','name']]);
        $takeNameArr = [];
        if(!empty($takeInfos)){
            $takeNameArr = ArrayHelper::index($takeInfos, 'id');
            unset($takeInfos);
        }

        //获取项目字典项用药ID
        $save_drug_arr = [];
        $annex_id = [];
        foreach($datas as $ocrContentInfo){
            if(!empty($ocrContentInfo['drug_id']) && !in_array($ocrContentInfo['drug_id'],$save_drug_arr)){
                $save_drug_arr[] = $ocrContentInfo['drug_id'];
            }
            if(!empty($ocrContentInfo['annex_id']) && !in_array($ocrContentInfo['annex_id'],$save_drug_arr)){
                $annex_id[] = $ocrContentInfo['annex_id'];
            }
        }
        //获取药物名称信息
        $drugNameArr = $this->LocalService()->collectDrug->fetchCol('name',[
            'is_del' => 0,
            'id' => $save_drug_arr,
        ]);

        //查询项目是否设置需要展示药物分类
        $doctoradvice_group = $this->LocalService()->itemInfo->getOneFieldVal('doctoradvice_group', [
            'is_del' => 0,
            'id' => $item_id,
        ]);
        $categoryName = [];
        if($doctoradvice_group == 1){
            $drugCategoryId = $this->LocalService()->collectDrug->fetchCol('category_id',[
                'is_del' => 0,
                'id' => $save_drug_arr,
            ]);

            if(!empty($drugCategoryId)){
                //药物分类
                $categoryName = $this->LocalService()->collectDrugcategory->fetchCol('category_name',[
                    'is_del' => 0,
                    'id' => $drugCategoryId,
                ]);
            }

        }

        $annexSrcArr = $this->LocalService()->patientFormContentImg->fetchCol('img_src',[
            'id' => $annex_id
        ]);

        unset($save_drug_arr,$annex_id);

        foreach($datas as $key=>&$info){

            $info['english'] = $this->LocalService()->collectDrug->getOneFieldVal('drug_remark',[
                'id' => $info['drug_id'],
            ]);

            $info_drug = !is_null($info['drug_id']) && !empty($info['drug_id']) ? $info['drug_id'] : 0;
            //药物分类
            if($doctoradvice_group == 1){
                $info['category_name'] = !empty($categoryName) && isset($categoryName[$drugCategoryId[$info_drug]]) ? $categoryName[$drugCategoryId[$info_drug]] : '';
            }

            $info['name'] = isset($drugNameArr[$info_drug]) && !empty($drugNameArr[$info_drug]) ? $drugNameArr[$info_drug] : '';
            $info['doctoradvice_type'] = $this->_getDoctoradviceType($info['annex_id']);

            $info['is_dispensary'] = (int)$info['is_dispensary'];
            $info['dualtherapy_type'] = (int)$info['dualtherapy_type'];

            if($type == 2){

                $info['img_src'] = $annexSrcArr[$info['annex_id']];

                $Doseandunit = $dosageunit_english = $dosageunit_name ='';

                if(!empty($info['dosage_num'])) $Doseandunit = $info['dosage_num'];

                if(!empty($info['dosage_unit']) && !empty($takeNameArr)){
                    $dosage_unit = $info['dosage_unit'];

                    $dosageunit_name .= $takeNameArr[$info['dosage_unit']]['name'];

                    if(!empty($takeNameArr[$dosage_unit]['english'])) $dosageunit_english.= '('.$takeNameArr[$dosage_unit]['english'].')';
                    $info['dosage_unit'] = '';
                    $info['dosage_unit'] .= $Doseandunit.$dosageunit_name.$dosageunit_english;
                }

                if(!empty($info['dosage_way']) && !empty($takeNameArr)){
                    $dosage_unit = $info['dosage_way'];

                    $info['dosage_way'] = $takeNameArr[$info['dosage_way']]['name'];
                    if(!empty($takeNameArr[$dosage_unit]['english'])) $info['dosage_way'].= '('.$takeNameArr[$dosage_unit]['english'].')';
                }else{
                    $info['dosage_way'] = '';
                }

                if(!empty($info['dosage_times']) && !empty($takeNameArr)){
                    $dosage_times = $info['dosage_times'];
                    $info['dosage_times'] = $takeNameArr[$info['dosage_times']]['name'];
                    if(!empty($takeNameArr[$dosage_times]['english'])) $info['dosage_times'].= '('.$takeNameArr[$dosage_times]['english'].')';
                }else{
                    $info['dosage_times'] = '';
                }
                $info['is_dispensary'] = (empty($info['is_dispensary'])) ? '否' : '是';

                if($info['dualtherapy_type'] == 1){
                    $info['dualtherapy_type'] = '新增合并用药';
                }elseif($info['dualtherapy_type'] == 2){
                    $info['dualtherapy_type'] = '已有合并用药';
                }elseif($info['dualtherapy_type'] == 3){
                    $info['dualtherapy_type'] = '弃用';
                }

            }elseif($type == 3){
                if($info['dualtherapy_type'] == 1){
                    $info['dualtherapy_type'] = '新增合并用药';
                }elseif($info['dualtherapy_type'] == 2){
                    $info['dualtherapy_type'] = '已有合并用药';
                }elseif($info['dualtherapy_type'] == 3){
                    $info['dualtherapy_type'] = '弃用';
                }
//                 = ($info['dualtherapy_type'] == 1) ? '合并用药' : '弃用';
                $dataID = $this->LocalService()->doctoradviceOriginal->fetchCol('id',[
                    'dualtherapy_type' => 0,
                    'is_del' => 0,
                    'is_lock' => 1,
                    'patient_id' => $info['patient_id'],
                    'item_id' => $item_id,
                    'drug_id' => $info['drug_id'],
                ]);

                if(!empty($info['dosage_way']) && !empty($takeNameArr)){
                    $dosage_unit = $info['dosage_way'];

                    $info['dosage_way'] = $takeNameArr[$info['dosage_way']]['name'];
                    if(!empty($takeNameArr[$dosage_unit]['english'])) $info['dosage_way'].= '('.$takeNameArr[$dosage_unit]['english'].')';
                }else{
                    $info['dosage_way'] = '';
                }
                if(!empty($dataID)){
                    $request['patient_id'] = $info['patient_id'];
                    $request['item_id'] = $item_id;
                    $request['info_id'] = $dataID;
                    $res = $this->patientDrugMerageData($request);
                    if(!empty($res)){
                        //首行数据
                        $FirstLineData = $res[$info['drug_id']];
                        $info['medical_date'] = isset($FirstLineData['medical_date']) ? $FirstLineData['medical_date'] : '';
                        $info['end_date'] = isset($FirstLineData['end_date']) ? $FirstLineData['end_date'] : '';
                        $info['is_dispensary'] = isset($FirstLineData['is_dispensary']) && !empty($FirstLineData['is_dispensary']) ? '是' : '否';
                        $info['dosage_unit'] = isset($FirstLineData['min_num_unit']) ? $FirstLineData['min_num_unit'] : '';
//                        $info['dosage_times'] = isset($FirstLineData['dosage_times']) ? $FirstLineData['dosage_times'] : '';

                        if(isset($FirstLineData['dosage_times']) && !empty($takeNameArr)){
                            $dosage_times = $FirstLineData['dosage_times'];
                            $info['dosage_times'] = $takeNameArr[$dosage_times]['name'];
                            if(!empty($takeNameArr[$dosage_times]['english'])) $info['dosage_times'].= '('.$takeNameArr[$dosage_times]['english'].')';
                        }
                        $info['day_num_unit'] = isset($FirstLineData['day_num_unit']) ? $FirstLineData['day_num_unit'] : '';
                        $info['max_num_unit'] = isset($FirstLineData['max_num_unit']) ? $FirstLineData['max_num_unit'] : '';
                    }
                }else{
                    $info['medical_date'] = '';
                    $info['end_date'] = '';
                    $info['is_dispensary'] = '';
                    $info['dosage_times'] = '';
                    $info['dosage_unit'] = '';
                    $info['dosage_num'] = '';
                }
            }
        }

        return $datas;

    }

    /**
     * Notes: 日期验证
     * User: lltyy
     * DateTime: 2024/7/16 9:58
     *
     * @param $annex_date
     * @return array
     */
    public function validatetime($annex_date)
    {
        $code = 200;
        $msg = '';
        if(!empty($annex_date)) {
            $annex_date_year = substr($annex_date,0,4);
            $annex_date_month = substr($annex_date,4,2);
            $annex_date_day = substr($annex_date,6,2);
            $annex_date_str = $annex_date_year.'-'.$annex_date_month.'-'.$annex_date_day;
            $date_reg = "/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/";
            //匹配日期格式
            if (preg_match ($date_reg, $annex_date_str, $parts)) {
                //检测是否为日期,checkdate为月日年
                if (checkdate($parts[2], $parts[3], $parts[1])) {
                    $code = 200;
                    $annex_date = $annex_date_year.$annex_date_month.$annex_date_day;
                }else{
                    $code = 60011;
                    $msg = '【'.$annex_date.'】格式不正确，【正确格式如：20210607】！';
                }
            }else{
                $code = 60011;
                $msg = '【'.$annex_date.'】格式不正确，【正确格式如：20210607】！';
            }
        }


        return ['code'=>$code,'msg'=>$msg,'date'=>$annex_date];
    }


    //受试者合并用药批次
    public function _getdrugbatch($patient_id,$drug_id,$id)
    {
        $data = $this->LocalService()->doctoradviceOriginal->fetchAll([
            'where'=> [
                'patient_id' => $patient_id,
                'is_del' => 0,
                'drug_id' => $drug_id,
                new Operator('drug_id', Operator::OP_NE, ''),
            ],
            'columns'=>['id','drug_id','medical_date','end_date']
        ]);

        $result = [];
        if(!empty($data)){
            $drugArr = array_column($data,'drug_id');

            $drugDatas = $this->LocalService()->collectDrug->fetchCol('name',[
                'id' => $drugArr
            ]);

            foreach($data as $k=>$v){
                $name = "(".$v['medical_date'].'/'.$v['end_date'].")";
                if($v['id'] == $id) $name .= '【当前药物】';

                $result[$k]['label'] = $drugDatas[$v['drug_id']].$name;
                $result[$k]['value'] = $v['id'];
            }
        }
        return $result;
    }

    /**
     * Notes: 获取患者药物合并的信息
     * 开始日期[medical_date]：默认最早的日期
     * 结束日期[end_date]：默认最晚的日期
     * 出院带药[is_dispensary]：只要有一条出院带药就默认 是
     * 剂量[min_num_unit]：最小剂量
     * 首剂量[max_num_unit]： 最大剂量，如果首剂量 和 剂量 一致，则 首剂量 显示空
     * 日剂量[day_num_unit]：剂量 * 剂量对应的服用频率设置的总剂量计算【病例收集 - 医嘱用药信息设置 - 用药字典项 - 服用频率】
     * 服用频率[dosage_times]：剂量 对应的 服用频率
     * 用药方式[dosage_way]：剂量 对应的 用药方式
     * User: lltyy
     * DateTime: 2024/7/18 9:43
     *
     * @param array $arr
     * @return array
     */
    public function patientDrugMerageData($arr = []){
        $patient_id = isset($arr['patient_id']) && !empty($arr['patient_id']) ? $arr['patient_id'] : 0;
        $item_id = isset($arr['item_id']) && !empty($arr['item_id']) ? $arr['item_id'] : 0;
        $info_ids = isset($arr['info_id']) && !empty($arr['info_id']) ? $arr['info_id'] : '';

        if(empty($item_id) || empty($patient_id)){
            return [];
        }

        //获取患者已锁定未处理的用药数据
        $patientDrugDatas = [];
        $where = [
            'is_del' => 0,
            'is_lock' => 1,
            'patient_id' => $patient_id,
            'item_id' => $item_id,
            'dualtherapy_type' => 0,
            new Operator('drug_id', Operator::OP_GT, 0),
        ];
        if(!empty($info_ids)){
            $where['id'] = $info_ids;
        }

        $cond = [
            'where'=>$where,
            'columns'=>['id','drug_id','medical_date','end_date','dosage_num','dosage_unit','dosage_times','is_dispensary','dosage_way'],
            'order'=>['id']
        ];
        $datas = $this->LocalService()->doctoradviceOriginal->fetchAll($cond);

        unset($where);
        unset($cond);
        if(!empty($datas)){
            $takeDatas = $this->LocalService()->collectMedicaltake->fetchDataByKey('is_del = 0 ',['id','name','english','take_number'],['take_order'],'id',0);
            foreach($datas as $dataKey=>$data){
                $data_drug = $data['drug_id'];
                $patientDrugDatas[$data_drug] = [
                    'medical_date' => isset($patientDrugDatas[$data_drug]) && $patientDrugDatas[$data_drug]['medical_date'] != '' ? $patientDrugDatas[$data_drug]['medical_date'] : '',//最早开始日期
                    'end_date' => isset($patientDrugDatas[$data_drug]) && $patientDrugDatas[$data_drug]['end_date'] != '' ? $patientDrugDatas[$data_drug]['end_date'] : '',//最晚结束日期
                    'min_num' => isset($patientDrugDatas[$data_drug]) && $patientDrugDatas[$data_drug]['min_num'] != '' ? $patientDrugDatas[$data_drug]['min_num'] : '',//最小剂量数值
                    'min_unit' => isset($patientDrugDatas[$data_drug]) && $patientDrugDatas[$data_drug]['min_unit'] != '' ? $patientDrugDatas[$data_drug]['min_unit'] : '',//最小剂量对应的单位ID
                    'min_num_unit' => isset($patientDrugDatas[$data_drug]) && $patientDrugDatas[$data_drug]['min_num_unit'] != '' ? $patientDrugDatas[$data_drug]['min_num_unit'] : '',//最小剂量及单位
                    'day_num' => isset($patientDrugDatas[$data_drug]) && $patientDrugDatas[$data_drug]['day_num'] != '' ? $patientDrugDatas[$data_drug]['day_num'] : '',//日剂量数值
                    'day_unit' => isset($patientDrugDatas[$data_drug]) && $patientDrugDatas[$data_drug]['day_unit'] != '' ? $patientDrugDatas[$data_drug]['day_unit'] : '',//日剂量单位ID
                    'day_num_unit' => isset($patientDrugDatas[$data_drug]) && $patientDrugDatas[$data_drug]['day_num_unit'] != '' ? $patientDrugDatas[$data_drug]['day_num_unit'] : '',//日剂量及单位
                    'max_num' => isset($patientDrugDatas[$data_drug]) && $patientDrugDatas[$data_drug]['max_num'] != '' ? $patientDrugDatas[$data_drug]['max_num'] : '',//首剂量数值
                    'max_unit' => isset($patientDrugDatas[$data_drug]) && $patientDrugDatas[$data_drug]['max_unit'] != '' ? $patientDrugDatas[$data_drug]['max_unit'] : '',//首剂量对应的单位ID
                    'max_num_unit' => isset($patientDrugDatas[$data_drug]) && $patientDrugDatas[$data_drug]['max_num_unit'] != '' ? $patientDrugDatas[$data_drug]['max_num_unit'] : '',//首剂量及单位
                    'is_dispensary' => isset($patientDrugDatas[$data_drug]) && !empty($patientDrugDatas[$data_drug]['is_dispensary']) ? $patientDrugDatas[$data_drug]['is_dispensary'] : 0,//取药（出院带药）标识
                    'dosage_times' => isset($patientDrugDatas[$data_drug]) && !empty($patientDrugDatas[$data_drug]['dosage_times']) ? $patientDrugDatas[$data_drug]['dosage_times'] : 0,
                    'dosage_way' => isset($patientDrugDatas[$data_drug]) && !empty($patientDrugDatas[$data_drug]['dosage_way']) ? $patientDrugDatas[$data_drug]['dosage_way'] : 0,
                ];

                //获取最早开始日期
                $drug_start = $patientDrugDatas[$data_drug]['medical_date'] != '' ? $patientDrugDatas[$data_drug]['medical_date'] : '';
                if($drug_start == '' || (!is_null($data['medical_date']) && $data['medical_date'] != '' && (intval($data['medical_date']) < intval($drug_start)))){
                    $patientDrugDatas[$data_drug]['medical_date'] = $data['medical_date'];
                }
                unset($drug_start);

                //获取最晚结束日期
                $drug_end = $patientDrugDatas[$data_drug]['end_date'] != '' ? $patientDrugDatas[$data_drug]['end_date'] : '';
                if($drug_end == '' || (!is_null($data['end_date']) && $data['end_date'] != '' && (intval($data['end_date']) > intval($drug_end)))){
                    $patientDrugDatas[$data_drug]['end_date'] = $data['end_date'];
                }
                unset($drug_end);

                //获取剂量、单位
                $dosage_num = !is_null($data['dosage_num']) && $data['dosage_num'] != '' ? $data['dosage_num'] : '';
                $dosage_unit = $data['dosage_unit'];
                $dosage_unit_name = isset($takeDatas[$dosage_unit]) && !empty($takeDatas[$dosage_unit]) ? $takeDatas[$dosage_unit]['name'] : '';
                if(isset($takeDatas[$dosage_unit]) && !empty($takeDatas[$dosage_unit]) && $takeDatas[$dosage_unit]['english'] != ''){
                    $dosage_unit_name .= '('.$takeDatas[$dosage_unit]['english'].')';
                }

                //获取剂量（最小剂量）、日总剂量【剂量即最小剂量*服用频率设置的总剂量计算值】
                $drug_min_num = $patientDrugDatas[$data_drug]['min_num'] != '' ? $patientDrugDatas[$data_drug]['min_num'] : '';
                if($dosage_num != '' && ($drug_min_num == '' || floatval($dosage_num) < floatval($drug_min_num))){
                    $patientDrugDatas[$data_drug]['min_num'] = $dosage_num;
                    $patientDrugDatas[$data_drug]['min_unit'] = $dosage_unit;
                    $patientDrugDatas[$data_drug]['min_num_unit'] = $dosage_num.$dosage_unit_name;

                    //日总剂量
                    $patientDrugDatas[$data_drug]['dosage_times'] = $data['dosage_times'];
                    $patientDrugDatas[$data_drug]['dosage_way'] = $data['dosage_way'];
                    $times_num = isset($takeDatas[$data['dosage_times']]) && !empty($takeDatas[$data['dosage_times']]) ? $takeDatas[$data['dosage_times']]['take_number'] : 1;
                    $day_num = floatval($dosage_num) * floatval($times_num);
                    $patientDrugDatas[$data_drug]['day_num'] = $day_num;
                    $patientDrugDatas[$data_drug]['day_unit'] = $dosage_unit;
                    $patientDrugDatas[$data_drug]['day_num_unit'] = $day_num.$dosage_unit_name;
                    unset($times_num);
                    unset($day_num);

                }
                unset($drug_min_num);

                //获取首剂量（最大剂量）
                $drug_max_num = $patientDrugDatas[$data_drug]['max_num'] != '' ? $patientDrugDatas[$data_drug]['max_num'] : '';
                if($dosage_num != '' && ($drug_max_num == '' || floatval($dosage_num) > floatval($drug_max_num))){
                    $patientDrugDatas[$data_drug]['max_num'] = $dosage_num;
                    $patientDrugDatas[$data_drug]['max_unit'] = $dosage_unit;
                    $patientDrugDatas[$data_drug]['max_num_unit'] = $dosage_num.$dosage_unit_name;
                }
                unset($drug_max_num);
                unset($dosage_num);
                unset($dosage_unit);
                unset($dosage_unit_name);

                //获取取药（出院带药）标识
                if($data['is_dispensary'] == 1){
                    $patientDrugDatas[$data_drug]['is_dispensary'] = 1;
                }
                unset($drug_end);

                //如果首剂量 和 剂量 一致，则 首剂量 显示空
                if($patientDrugDatas[$data_drug]['min_num'] != '' && $patientDrugDatas[$data_drug]['max_num'] != '' && (floatval($patientDrugDatas[$data_drug]['min_num']) == floatval($patientDrugDatas[$data_drug]['max_num']))){
                    $patientDrugDatas[$data_drug]['max_num'] = '';
                    $patientDrugDatas[$data_drug]['max_unit'] = '';
                    $patientDrugDatas[$data_drug]['max_num_unit'] = '';
                }

                unset($datas[$dataKey]);
            }
            unset($takeDatas);
        }
        unset($datas);
        
        return $patientDrugDatas;
    }


    /**
     * Notes : 已有CM列表
     * @param $patient_id
     * @param $form_id
     * Author:唐伯虎不虎
     * Date:2024/8/6 10:57
     */
    public function haveCM($patient_id,$form_id,$drug_name)
    {
        //获取一对多表单列表固定头部
        $formfieldList = $this->LocalService()->itemFormField->fetchCol('name',[
            'form_id' => $form_id,
            'is_del' => 0,
            'is_list' => 1,
        ], ['order']);

        $CMNAM_id = $this->LocalService()->itemFormField->getOneFieldVal('id',[
            'form_id' => $form_id,
            'is_del' => 0,
            'is_list' => 1,
            'var_name' => 'CMNAM'
        ]);

        if(empty($formfieldList)) throw new InvalidArgumentException('当前表单未设置列表字段,请补充!');

        $filedata = [];

        foreach($formfieldList as $k=>$v){
            $arr['label'] = $v;
            $arr['prop'] = (string)$k;
            $filedata[] = $arr;
        }

        $_POST['limit'] = 100;
        //获取受试者一对多表单填写内容，并拼接成字符串
        $PatientFormModel = new PatientFormModel();
        $PatientFormModel->setPostValues([
            'form_id' => $form_id,
            'patient_id' => $patient_id,
        ]);
        $val = $PatientFormModel->view();

        $option = [];
        foreach($val as $key=>$value){
            if(!empty($CMNAM_id)){

                if (strpos($value[$CMNAM_id], $drug_name) !== false) {
                    foreach($formfieldList as $k=>$v){

                        foreach($value as $kk=>$vv){
                            if($kk === $k){
                                $option[$key]['label'] .= '【'.$vv.'】' ;
                            }
                        }
                    }
                    $option[$key]['value'] = $value['id'];
                }else{
                    unset($val[$key]);
                    continue;
                }
            }

        }

        return [$option,$filedata,$val];
    }


    public function execute()
    {
        $datas = $this->LocalService()->doctoradviceOriginal->fetchCol('annex_id',[
            'mate_type' => 1,
            'is_del' => 0,
            'is_lock' => 0,
            'item_id' => 2398,
        ]);

        $datas = array_unique($datas);

        foreach($datas as $k=>$v){
            $this->LocalService()->doctoradviceOriginal->update(['is_del'=>1],['annex_id'=>$v]);

            $this->LocalService()->doctoradviceOriginal->handleOcrData(['annexId'=>$v]);

        }
        return true;
    }

    /**
     * Notes: 获取人员操作医嘱数
     * User: lltyy
     * DateTime: 2024/12/2 8:02
     *
     * @param array $info
     */
    public function getUserMedicalCount(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,
            'is_lock' => 1,
        ];
        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);
        }
        if(isset($info['item_ids'])){
            if(!empty($item_id_arr)){
                $where['item_id'] = $item_id_arr;
            }else{
                $where = [
                    'id' => 0,
                ];
            }
        }
        $datas = $this->LocalService()->adminMedicallock->fetchAll([
            'where'=>$where,
            'columns'=>['info_id','create_time','create_user_id']
        ]);
        unset($where);
        if(!empty($datas)){
            foreach($datas as $dataKey=>$data){
                $data_create = $data['create_user_id'];
                $create_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){
                    $arr[$data_create] = isset($arr[$data_create]) && !empty($arr[$data_create]) ? $arr[$data_create] : 0;
                    $arr[$data_create] += 1;
                }
                unset($data_create);
                unset($create_add);
                unset($datas[$dataKey]);
            }
        }
        unset($datas);

        return $arr;
    }

}