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

namespace Application\Service\DB\Tmp;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\IsNotNull;
use Laminas\Db\Sql\Predicate\Like;
use Laminas\Db\Sql\Predicate\Operator;

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

    /**
     * Notes: 更新识别内容
     * User: lltyy
     * DateTime: 2023/5/24 9:39
     *
     * @param $content //更新内容
     * @param $setWordDatas //设置的白名单数据
     * @param $oldMateDatas //历史已匹配信息
     * @param $oldLockDatas //历史已锁定信息
     * @return int
     */
    public function saveRawData($content,&$setWordDatas,&$oldMateDatas){
        $ocrContentId = empty($content['id']) ? 0 : $content['id'];
        $save_data = [
            'id'=>$ocrContentId,
            'annex_id'=>$content['annex_id'],
            'itemsig_id'=>$content['itemsig_id'],
            'patient_id'=>$content['patient_id'],
            'raw_date'=>$content['annex_date'],
            'raw_result'=>$content['raw_result'] == '' ? '' : trim($content['raw_result']),
            'mate_type'=>1
        ];
        $result = $this->save($save_data);
        if($result){
            $ocrContentId = empty($ocrContentId) ? $result : $ocrContentId;

            //更新匹配信息
            $keyword_id = !empty($content['mate_data']) ? $content['mate_data'] : 0;
            $oldMateInfos = isset($oldMateDatas[$ocrContentId]) && !empty($oldMateDatas[$ocrContentId]) ? $oldMateDatas[$ocrContentId] : [];
            $oldMateInfo = isset($oldMateInfos[$keyword_id]) && !empty($oldMateInfos[$keyword_id]) ? $oldMateInfos[$keyword_id] : [];
            $old_is_mate = !empty($oldMateInfo) ? $oldMateInfo['is_mate'] : 0;
            $setWord = isset($setWordDatas[$keyword_id]) && !empty($setWordDatas[$keyword_id]) ? $setWordDatas[$keyword_id] : [];
            if($old_is_mate != 1){
                $this->LocalService()->tmpRawmate->update(['is_mate'=>0],['is_del'=>0,'is_mate'=>1,'raw_id'=>$ocrContentId]);
                if(!empty($oldMateInfo)){
                    $this->LocalService()->tmpRawmate->update(['is_mate'=>1],['id'=>$oldMateInfo['id']]);
                }else{
                    $save_mate = [
                        'annex_id'=>$content['annex_id'],
                        'itemsig_id'=>$content['itemsig_id'],
                        'patient_id'=>$content['patient_id'],
                        'category_name'=>!empty($setWord) ? $setWord['category_name'] : '',
                        'raw_id'=>$ocrContentId,
                        'raw_name'=>empty($content['raw_name']) ? '' : trim($content['raw_name']),
                        'keyword_id'=>$keyword_id,
                        'keyword_name'=>!empty($setWord) ? $setWord['keyword_name'] : '',
                        'mate_rate'=>100,
                        'name_rate'=>100,
                        'is_mate'=>1
                    ];
                    $this->LocalService()->tmpRawmate->save($save_mate);
                    unset($save_mate);
                }
            }
            unset($oldMateInfos);
            unset($oldMateInfo);
            unset($old_is_mate);
        }
        unset($save_data);
        unset($content);
        unset($setWord);

        return $ocrContentId;
    }

    /**
     * Notes:获取附件下指定条件的数据
     * User: lltyy
     * DateTime: 2023/5/26 8:21
     *
     * @param $where//数据条件
     * @param int $return_type//返回数据类型【0 附件下未匹配、已匹配、黑名单信息数据 1 附件下已匹配无识别结果数 2 附件下匹配上黑名单的名称】
     * @return array[]
     */
    public function fetchAnnexData($where,$return_type=0){
        $return_type = empty($return_type) ? 0 : $return_type;
        $arr = [
            'mate_id'=>[],//已匹配附件ID
            'mate_count'=>[],//附件下的已匹配数量
            'act_count'=>[],//附件下的已匹配有效数量
            'no_mate_id'=>[],//未匹配附件ID
            'no_mate_count'=>[],//附件下的未匹配数量
            'black_id'=>[],//黑名单附件ID
            'black_count'=>[],//附件下的黑名单数量
            'annex_date'=>[]//附件的采集时间
        ];
        $columns = ['annex_id','mate_type','raw_date'];
        if(!empty($return_type)){
            $arr = [];
            if($return_type == 1){//附件下已匹配无识别结果
                $columns = ['annex_id','mate_type','raw_result'];
            }
            if($return_type == 2){//附件下匹配上黑名单的名称
                $columns = ['annex_id','mate_type','raw_name'];
            }
        }
        $cond = [
            'where'=>$where,
            'columns'=>$columns
        ];
        $datas = $this->fetchAll($cond);
        $annex_date_arr = [];
        if(!empty($datas)){
            foreach($datas as $data){
                $mate_type = $data['mate_type'];
                $annex_id = $data['annex_id'];
                //附件时间
                if(empty($return_type)){
                    $annex_date_arr[$annex_id] = isset($annex_date_arr[$annex_id]) && !empty($annex_date_arr[$annex_id]) ? $annex_date_arr[$annex_id] : [];
                    $raw_date = $data['raw_date'];
                    if(!is_null($raw_date) && $raw_date != ''){
                        $annex_date_arr[$annex_id][$raw_date] = $raw_date;
                    }
                }

                //未匹配
                if(empty($mate_type) && empty($return_type)){//未匹配数
                    $arr['no_mate_id'][$annex_id] = $annex_id;
                    $arr['no_mate_count'][$annex_id] = isset($arr['no_mate_count'][$annex_id]) && !empty($arr['no_mate_count'][$annex_id]) ? $arr['no_mate_count'][$annex_id] : 0;
                    $arr['no_mate_count'][$annex_id] += 1;
                }
                //已匹配
                if($mate_type == 1){
                    if(empty($return_type)){//已匹配数
                        $arr['mate_id'][$annex_id] = $annex_id;
                        $arr['mate_count'][$annex_id] = isset($arr['mate_count'][$annex_id]) && !empty($arr['mate_count'][$annex_id]) ? $arr['mate_count'][$annex_id] : 0;
                        $arr['mate_count'][$annex_id] += 1;
                        $arr['act_count'][$annex_id] = isset($arr['act_count'][$annex_id]) && !empty($arr['act_count'][$annex_id]) ? $arr['act_count'][$annex_id] : 0;
                        $arr['act_count'][$annex_id] += 1;
                    }

                    if($return_type == 1){//已匹配上指标无结果数据
                        $raw_result = trim($data['raw_result']);
                        if($raw_result == '' || empty($raw_result)){
                            $arr[$annex_id] = isset($arr[$annex_id]) && !empty($arr[$annex_id]) ? $arr[$annex_id] : 0;
                            $arr[$annex_id]++;
                        }
                    }
                }
                //黑名单
                if($mate_type == 2){
                    if(empty($return_type)) {//黑名单数
                        $arr['black_id'][$annex_id] = $annex_id;
                        $arr['black_count'][$annex_id] = isset($arr['black_count'][$annex_id]) && !empty($arr['black_count'][$annex_id]) ? $arr['black_count'][$annex_id] : 0;
                        $arr['black_count'][$annex_id] += 1;
                    }

                    if($return_type == 2){//已匹配上黑名单名称
                        $arr[$annex_id] = isset($arr[$annex_id]) && !empty($arr[$annex_id]) ? $arr[$annex_id] : [];
                        $arr[$annex_id][] = $data['raw_name'];
                    }
                }
            }
        }
        if(empty($return_type)){
            if(!empty($annex_date_arr)){
                foreach($annex_date_arr as $annex_date_id=>$annex_dates){
                    $arr['annex_date'][$annex_date_id] = !empty($annex_dates) ? implode('、',$annex_dates) : '';
                }
            }

            if(!empty($arr['black_id'])){
                foreach($arr['black_id'] as $black_annex){
                    unset($arr['mate_id'][$black_annex]);//去除已匹配数据中黑名单附件
                    unset($arr['no_mate_id'][$black_annex]);//去除未匹配数据中黑名单附件
                }
            }

            if(!empty($arr['no_mate_id'])){
                foreach($arr['no_mate_id'] as $no_mate_annex){
                    unset($arr['mate_id'][$no_mate_annex]);//去除已匹配数据中未匹配附件
                }
            }
            $arr['no_mate_id'] = array_values($arr['no_mate_id']);
            $arr['mate_id'] = array_values($arr['mate_id']);
            $arr['black_id'] = array_values($arr['black_id']);
        }

        return $arr;
    }


    /**
     * Notes: 批量删除无效识别项
     * User: lltyy
     * DateTime: 2023/5/25 16:07
     *
     * @param $where//数据条件
     * @param array $delete_name_arr//要删除的识别内容数组
     * @param int $update_annex//是否更新附件信息【0 否 1 是】
     * @return int
     */
    public function deleteDataHaveName($where,array $delete_name_arr=[],$update_annex = 0){
        $count = 0;
        if(!empty($delete_name_arr)){
            $count = 1;
            //查询要删除的数据ID以及对应的附件ID
            $annex_arr = $delete_arr = [];
            $where_arr = [];
            foreach($delete_name_arr as $delete_name){
                $where_arr[] = new Like('raw_name',"%{$delete_name}%");
            }
            $where['or'] = $where_arr;
            $cond = [
                'where'=>$where,
                'columns'=>['id','annex_id']
            ];
            $datas = $this->fetchAll($cond);
            if(!empty($datas)){
                foreach($datas as $data){
                    $data_annex = $data['annex_id'];
                    $annex_arr[$data_annex] = $data_annex;
                    $delete_arr[] = $data['id'];
                }
            }
            unset($where_arr);
            unset($where);
            unset($cond);
            unset($datas);

            //删除符合要求的识别内容
            if(!empty($delete_arr)){
                $this->upDelState(['is_del'=>0,'id'=>$delete_arr],1);
                $this->LocalService()->tmpRawmate->upDelState(['is_del'=>0,'raw_id'=>$delete_arr],1);
                $this->LocalService()->tmpRawblack->upDelState(['is_del'=>0,'raw_id'=>$delete_arr],1);
                $this->LocalService()->tmpRawlock->upDelState(['is_del'=>0,'raw_id'=>$delete_arr],1);
            }
            unset($delete_arr);

            //更新附件信息
            if($update_annex == 1 && !empty($annex_arr)){
                $annex_arr = array_values($annex_arr);
                $annex_count_arr = $this->fetchAnnexData(['is_del'=>0,'annex_id'=>$annex_arr]);
            }
            unset($annex_arr);
        }

        return $count;
    }


    /**
     * Notes: 批量替换识别信息
     * User: lltyy
     * DateTime: 2023/5/25 16:07
     *
     * @param $where//数据条件
     * @param array $replace_datas//要替换的数组
     * @param int $update_ocr//是否重新匹配【0 否 1 是】
     * @return int
     */
    public function replaceDataHaveInfo($where,array $replace_datas=[],$update_ocr = 0)
    {
        $count = 0;
        if (!empty($replace_datas)) {
            $count = 1;

            //查询要替换的数据ID
            $where_arr = [];
            foreach ($replace_datas as $replace) {
                if ($replace['info_type'] == 0) {
                    $where_arr[] = new Like('raw_name',"%{$replace['replace_pre']}%");
                }
                if ($replace['info_type'] == 1) {
                    $where_arr[] = new Like('raw_result',"%{$replace['replace_pre']}%");
                }
            }
            unset($replace_arr);

            $where['or'] = $where_arr;
            $cond = [
                'where' => $where,
                'columns' => ['id', 'annex_id', 'raw_name', 'raw_result']
            ];
            $update_arr = $update_annex_arr = [];
            $datas = $this->fetchAll($cond);
            if (!empty($datas)) {
                foreach ($datas as $data) {
                    $raw_id = $data['id'];
                    $raw_name = $data['raw_name'];
                    $raw_result = $data['raw_result'];

                    foreach ($replace_datas as $replace_info) {
                        $replace_info['replace_after'] = $replace_info['replace_after'] != '' ? $replace_info['replace_after'] : '';
                        if ($replace['info_type'] == 0) {
                            $raw_name = str_replace($replace_info['replace_pre'], $replace_info['replace_after'], $raw_name);
                        }
                        if ($replace['info_type'] == 1) {
                            $raw_result = str_replace($replace_info['replace_pre'], $replace_info['replace_after'], $raw_result);
                        }
                    }
                    $update_data = [];
                    if ($raw_name != $data['raw_name']) {
                        $update_data['raw_name'] = $raw_name;
                    }
                    if ($raw_result != $data['raw_result']) {
                        $update_data['raw_result'] = $raw_result;
                    }
                    if (!empty($update_data)) {
                        if ($update_ocr == 0) {//更新明细信息
                            $this->LocalService()->tmpRawlock->update($update_data, ['is_del'=>0,'raw_id'=>$raw_id]);
                        }
                        if ($update_ocr == 1 && isset($update_data['raw_name'])) {//重新匹配
                            $update_arr[] = $raw_id;
                            $update_annex_arr[] = $data['annex_id'];
                            $update_data['mate_type'] = 0;
                        }
                        $this->update($update_data, ['id'=>$raw_id]);
                    }
                    unset($update_data);

                }
            }
            unset($where_arr);
            unset($cond);
            unset($datas);
            unset($replace_datas);

            //重新匹配
            if($update_ocr == 1 && !empty($update_arr)){
                //删除已匹配数据
                $this->LocalService()->tmpRawmate->upDelState(['is_del'=>0,'raw_id'=>$update_arr],1);
                $this->LocalService()->tmpRawblack->upDelState(['is_del'=>0,'raw_id'=>$update_arr],1);

                //获取指标关键字信息
                $keywordCond = [
                    'where'=>[
                        'is_del'=>0,
                        new IsNotNull('keyword_name'),
                        new Operator('keyword_name',Operator::OP_NE,"")
                    ],
                    'columns'=>['id','category_name','keyword_code','keyword_name'],
                    'order'=>['category_name','parent_id','id']
                ];
                $keywordDatas = $this->LocalService()->tmpKeyword->fetchAll($keywordCond);

                //获取指标黑名单信息
                $black_word_arr = [
                    'name'=>[],
                    'code'=>[]
                ];
                $blackCond = [
                    'where'=>['is_del'=>0],
                    'columns'=>['id','category_name','word_code','word_name'],
                    'order'=>['category_name','id']
                ];
                $blackDatas = $this->LocalService()->tmpRawword->fetchAll($blackCond);
                if(!empty($blackDatas)){
                    foreach($blackDatas as $blackData){
                        $black_word_arr['name'][] = $blackData['word_name'];
                        if($blackData['word_code'] != ''){
                            $black_word_arr['code'][] = $blackData['word_code'];
                        }
                    }
                }

                //重新跑匹配
                $this->LocalService()->tmpRawmate->mateRawdata(['id'=>$update_arr],0,0,$keywordDatas,$black_word_arr);

                //更新附件信息
                $raw_annex_arr = $this->fetchAnnexData(['is_del'=>0,'annex_id'=>$update_annex_arr]);

            }
            unset($update_arr);
            unset($update_annex_arr);
        }
        return $count;
    }

    /**
     * Notes:
     * User: lltyy
     * DateTime: 2023/6/6 8:52
     *
     */
    public function mateData($where,$limit=0,$offset=0){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','annex_type','sig_id','patient_id','annex_id','content'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->LocalService()->tmpCustom->fetchAll($cond);
        unset($cond);
        $last_id = 0;
        if(!empty($datas)){
            //删除原匹配数据
            $delete_mate_arr = [];
            foreach($datas as $data_info){
                $last_id = $data_info['id'];
                $delete_mate_arr[] = $data_info['id'];
            }
            $this->update(['is_del'=>1],['is_del'=>0,'custom_id'=>$delete_mate_arr]);
            unset($delete_mate_arr);

            foreach ($datas as $dataKey=>$data) {
                $save_data = [
                    'annex_type'=>$data['annex_type'],
                    'custom_id'=>$data['id'],
                    'itemsig_id'=>$data['sig_id'],
                    'patient_id'=>$data['patient_id'],
                    'annex_id'=>$data['annex_id'],
                    'ocr_date'=>'',
                    'raw_date'=>'',
                    'is_lock'=>0,
                    'mate_type'=>0,
                ];
                $content_arr = [];
                $ocr_content_arr = json_decode($data['content'],true);
                if(isset($ocr_content_arr['collect_date'])){
                    $save_data['ocr_date'] = $ocr_content_arr['collect_date'] != '' ? $ocr_content_arr['collect_date'] : '';
                    unset($ocr_content_arr['collect_date']);
                }
                $save_data['raw_date'] = $this->replaceRawdata($save_data['ocr_date'],1);
                $ocr_content_arr = isset($ocr_content_arr['table']) && !empty($ocr_content_arr['table']) ? $ocr_content_arr['table'] : [];
                if(!empty($ocr_content_arr)){
                    foreach($ocr_content_arr as $ocr_content_key=>$ocr_content){
                        if(isset($ocr_content['item_name'])){
                            $content_result = isset($ocr_content['result']) && $ocr_content['result'] != '' ? $ocr_content['result'] : '';
                            if(strpos($ocr_content['item_name'],'采样') !== false && $save_data['raw_date'] == ''){
                                $save_data['ocr_date'] = $this->replaceRawdata($ocr_content['item_name'],1);
                                $save_data['raw_date'] = $save_data['ocr_date'];
                            }else{
                                $content_arr[] = [
                                    'raw_name'=>$ocr_content['item_name'],
                                    'ocr_result'=>$content_result,
                                    'raw_result'=>$content_result,
                                    'raw_unit'=>isset($ocr_content['unit']) && $ocr_content['unit'] != '' ? $ocr_content['unit'] : '',
                                    'raw_range'=>isset($ocr_content['reference_range']) && $ocr_content['reference_range'] != '' ? $ocr_content['reference_range'] : '',
                                ];
                            }
                        }
                        unset($ocr_content_arr[$ocr_content_key]);
                    }
                }
                $save_data['raw_date'] = substr($save_data['raw_date'],0,8);
                unset($ocr_content_arr);

                if(!empty($content_arr)){
                    foreach($content_arr as $contentKey=>&$content){
                        $content = array_merge($save_data,$content);
                        $this->save($content);
                        unset($content_arr[$contentKey]);
                    }
                }
                unset($content_arr);
                unset($datas[$dataKey]);
            }
        }
        unset($datas);

        return $last_id;
    }

    /**
     * Notes:
     * User: lltyy
     * DateTime: 2023/6/6 8:52
     *
     */
    public function scanData($where='') {
        //信息匹配
        if(empty($where)){
            $where = ['is_del'=>0,'annex_type'=>[89234,89235]];
        }

        $sig_id_arr = [];
        if(!empty($sig_id_arr)){
            $where['sig_id'] = $sig_id_arr;
        }
        $bool = true;
        $page = 0;
        $limit = 100;
        $last_id = 0;
        while ($bool) {
            $page++;
            echo "rawPAGE {$page}：" . PHP_EOL;
            $mateDataWhere = $where;
            $mateDataWhere[] = new Operator('id',Operator::OP_GT,$last_id);
            $last_id = $this->mateData($mateDataWhere,$limit,0);
            unset($mateDataWhere);
            if(!$last_id) $bool = false;
        }
        unset($wordDatas);
    }

    /**
     * Notes: 去除无用字符串
     * User: lltyy
     * DateTime: 2023/6/8 15:07
     *
     * @param string $str
     * @param int $type 类型【0 结果 1 时间 2 识别项 3 识别项 4 识别项拆分末尾数字】
     * @return string|string[]|null
     */
    public function replaceRawdata($str='',$type=0){
        if($str != ''){
            if($type == 3){
                $str = preg_replace("/\\d+/",'', $str);
            }
            if($type == 0){
                $str = str_replace(',','.',$str);
                $str = str_replace(' 。','.',$str);
                $str = str_replace("'",'',$str);
                $str = str_replace('-','',$str);
                $str = str_replace('*','',$str);
                $str = str_replace(':','',$str);
                $str = str_replace('?','',$str);
            }
            $delete_result_arr = ["—","！","ㄧ","」","∠",":","·","/","；","‘","’","：","，","（","）","—","——","、","~","!","@","#","$","%","^","&","*","(",")","-","_","+","{","}",";","|",",","？","【","】","[","]","！","……"];
            $have_result_arr = ["—","！","ㄧ","」","∠",":","·","/","；","‘","’","：","，","（","）","—","——","、","~","!","@","#","$","%","^","&","*","(",")","-","_","+","=","{","}",";","|",",","<",">","《","》","？","【","】","[","]","！","……"];
            if(!in_array($type,[0,4])){
                $delete_result_arr[] = '=';
                $delete_result_arr[] = '.';
                $delete_result_arr[] = "<";
                $delete_result_arr[] = ">";
                $delete_result_arr[] = "《";
                $delete_result_arr[] = "》";
                $delete_result_arr[] = "↑";
                $delete_result_arr[] = "↓";
                $have_result_arr[] = '.';
                $have_result_arr[] = '↑';
                $have_result_arr[] = '↓';
            }
            $chinese_regular = '/([\x80-\xff]*)/i';//汉字正则
            $big_letter_regular = '/[A-Z]/';//大写字母正则
            $small_letter_regular = '/[a-z]/';//小写字母正则
            if($type == 4){
                $judge_str = '';
                if(strpos($str,'↑')){
                    $judge_str = '↑';
                }
                if(strpos($str,'↓')){
                    $judge_str = '↓';
                }
                $new_rawname_str = str_replace(['↑','↓'],'',$str);//替换字符串中的特殊字符
                $split_name_arr = mb_str_split($new_rawname_str);
                $end_chinese = '';//最后一个汉字
                $all_number = '';//最后一个汉字之后的数字
                $last_number = '';
                $chinese_regular = '/[\x7f-\xff]+/';//汉字正则
                $end_str_type = 0;
                if(!empty($split_name_arr)){
                    foreach($split_name_arr as $split_name){
                        //判断字符串类型
                        $str_type = 0;
                        if(is_numeric($split_name)){//是数字
                            $str_type = 1;
                        }else{
                            if($split_name == '.'){//是数字
                                $str_type = 1;
                            }else{
                                $new_split_name = str_replace($have_result_arr,'',$split_name);//替换字符串中的特殊字符
                                if($new_split_name == ''){
                                    $str_type = 3;
                                }else{
                                    $new_split_name = preg_replace($chinese_regular,'',$split_name);//去除字符串中的汉字
                                    $new_split_name = preg_replace($big_letter_regular,'',$new_split_name);//去除字符串中的大写字母
                                    $new_split_name = preg_replace($small_letter_regular,'',$new_split_name);//去除字符串中的小写字母
                                    if($new_split_name == ''){
                                        $str_type = 2;
                                    }
                                }
                            }
                        }
                        if($end_chinese != ''){
                            if($str_type == 1){
                                $all_number .= $split_name;
                            }elseif($str_type == 2){
                                $end_chinese = $split_name;
                                $all_number = '';
                            }elseif($str_type == 3){
                                if($end_str_type != 3 || $last_number == ''){
                                    $last_number = $all_number;
                                }
                                $end_chinese = $split_name;
                                $all_number = '';
                            }
                        }else{
                            if($str_type == 2){
                                $end_chinese = $split_name;
                                $all_number = '';
                            }elseif($str_type == 3){
                                if($end_str_type != 3 || $last_number == ''){
                                    $last_number = $all_number;
                                }
                                $end_chinese = $split_name;
                                $all_number = '';
                            }
                        }
                        $end_str_type = $str_type;
                    }
                }
                if($end_str_type == 3){
                    $all_number = $last_number;
                }
                if($all_number != ''){
                    $all_number .= $judge_str;
                }
                $str = $all_number;
            }else{
                if(!in_array($str,$have_result_arr)){
                    $str = str_replace($delete_result_arr,'',$str);//替换字符串中的特殊字符
                    if($type != 3){
                        $str = preg_replace($chinese_regular,'',$str);//去除字符串中的汉字
                    }
                    $str = preg_replace($big_letter_regular,'',$str);//去除字符串中的大写字母
                    $str = preg_replace($small_letter_regular,'',$str);//去除字符串中的小写字母
                }else{
                    $str = '';
                }
            }
        }
        $str = $str != '' ? $str : '';
        if($str != '' && $type == 1){
            if(in_array(substr($str,0,2),['21','22','23'])){
                $str = '20'.$str;
            }
            if(in_array(substr($str,0,3),['020','021','022','023'])){
                $str = '2'.$str;
            }
            if(in_array(substr($str,0,5),['22020','22021','22022','22023'])){
                $str = substr_replace($str,'2',0,2);
            }
            if(in_array(substr($str,0,6),['222020','222021','222022','222023'])){
                $str = substr_replace($str,'2',0,3);
            }
            if(in_array(substr($str,0,7),['2222020','2222021','2222022','2222023'])){
                $str = substr_replace($str,'2',0,4);
            }
        }
        unset($delete_result_arr);
        unset($have_result_arr);
        unset($chinese_regular);
        unset($big_letter_regular);
        unset($small_letter_regular);
        return $str;
    }

    /**
     * Notes:结果判断异常
     * User: lltyy
     * DateTime: 2023/7/21 13:20
     *
     * @param string $result //结果值
     * @param string $set_min //最小值
     * @param string $set_max //最大值
     * @return int
     * $set_judge
     *      0：正常
     *      1：低
     *      2：高
     *      3：超低【低于最小值的二分之一】
     *      4：超高【高于最大值的2倍】
     */
    public function getSetJudge($result='',$set_min='',$set_max=''){
        $result = is_null($result) || $result == '' ? '' : trim($result);
        $set_min = is_null($set_min) || $set_min == '' ? '' : trim($set_min);
        $set_max = is_null($set_max) || $set_max == '' ? '' : trim($set_max);
        $set_judge = 0;

        if($result != '' && is_numeric($result)){
            if($set_min != ''){
                if($result < $set_min){
                    $set_judge = 1;
                    //判断是否低于最小值2倍
                    $set_min_two = $set_min/2;
                    if($result <= $set_min_two){//超低
                        $set_judge = 3;
                    }
                }else{
                    if($set_max != ''){
                        if(strpos($set_max,'<') !== false){
                            $set_max_number = str_replace('<','',$set_max);
                            if($result >= $set_max_number){
                                $set_judge = 2;
                                //判断是否高于最大值2倍
                                $set_max_two = $set_max_number*2;
                                if($result >= $set_max_two){//超高
                                    $set_judge = 4;
                                }
                            }
                        }else{
                            if($result >= $set_max){
                                $set_judge = 2;
                                //判断是否高于最大值2倍
                                $set_max_two = $set_max*2;
                                if($result >= $set_max_two){//超高
                                    $set_judge = 4;
                                }
                            }
                        }
                    }
                }
            }else{
                if($set_max != ''){
                    if(strpos($set_max,'<') !== false){
                        $set_max_number = str_replace('<','',$set_max);
                        if($result >= $set_max_number){
                            $set_judge = 2;
                            //判断是否高于最大值2倍
                            $set_max_two = $set_max_number*2;
                            if($result >= $set_max_two){//超高
                                $set_judge = 4;
                            }
                        }
                    }else{
                        if($result >= $set_max){
                            $set_judge = 2;
                            //判断是否高于最大值2倍
                            $set_max_two = $set_max*2;
                            if($result >= $set_max_two){//超高
                                $set_judge = 4;
                            }
                        }
                    }
                }
            }
        }

        return $set_judge;
    }


    /**
     * Notes:化验单 - 结果异常判断
     * User: lltyy
     * DateTime: 2023/5/26 15:26
     *
     */
    public function scanJudgeData($where=[]){
        if(empty($where)) {
            $where = ['is_del'=>0,'mate_type'=>1];
        }
        $sig_id_arr = [];
        if(!empty($sig_id_arr)){
            $where['itemsig_id'] = $sig_id_arr;
        }

        $judge_name_arr = [1=>'低',2=>'高',3=>'超低',4=>'超高'];
        $bool = true;
        $page = 0;
        $limit = 1000;
        $last_raw_id = 0;
        while ($bool) {
            $page++;
            echo "rawJudgePAGE {$page}：" . PHP_EOL;
            $mateJudgeDataWhere = $where;
            $mateJudgeDataWhere[] = new Operator('id',Operator::OP_GT,$last_raw_id);
            $last_raw_id = $this->mateJudgeData($mateJudgeDataWhere, $limit,0,$judge_name_arr);
            if(!$last_raw_id) $bool = false;
        }
        unset($judge_name_arr);
    }

    /**
     * Notes: 获取指定条件下的结果数据  - 进行异常判断
     * User: lltyy
     * DateTime: 2023/4/25 10:16
     *
     * @param $where
     * @return array
     */
    public function mateJudgeData($where,$limit=0,$offset=0,&$judge_name_arr){
        //获取指定条件下的识别结果数据
        $rawCond = [
            'where'=>$where,
            'columns'=>['id','raw_result','edit_result','raw_min','raw_max'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $rawCond['limit'] = $limit;
            $rawCond['offset'] = $offset;
        }
        $rawDatas = $this->LocalService()->tmpRawdata->fetchAll($rawCond);
        $last_raw_id = 0;
        if(!empty($rawDatas)){
            foreach($rawDatas as $rawKey=>$rawData){
                $raw_id = $rawData['id'];
                $last_raw_id = $raw_id;
                $set_min = !is_null($rawData['raw_min']) && $rawData['raw_min'] != '' ? $rawData['raw_min'] : '';
                $set_max = !is_null($rawData['raw_max']) && $rawData['raw_max'] != '' ? $rawData['raw_max'] : '';

                //识别结果异常判断判断
                $raw_judge = $this->getSetJudge($rawData['raw_result'],$set_min,$set_max);
                $raw_judge_name = isset($judge_name_arr[$raw_judge]) && !empty($judge_name_arr[$raw_judge]) ? $judge_name_arr[$raw_judge] : '';

                //调整结果异常判断判断
                $edit_judge = $this->getSetJudge($rawData['edit_result'],$set_min,$set_max);
                $edit_judge_name = isset($judge_name_arr[$edit_judge]) && !empty($judge_name_arr[$edit_judge]) ? $judge_name_arr[$edit_judge] : '';

                $update_data = [
                    'raw_judge'=>$raw_judge,
                    'judge_name'=>$raw_judge_name,
                    'edit_judge'=>$edit_judge,
                    'edit_judge_name'=>$edit_judge_name
                ];
                $this->LocalService()->tmpRawdata->update($update_data,['id'=>$raw_id]);

                unset($rawDatas[$rawKey]);
            }
        }
        unset($rawDatas);

        return $last_raw_id;
    }



    /**
     * Notes:化验单 - 结果含上下箭头
     * User: lltyy
     * DateTime: 2023/5/26 15:26
     *
     */
    public function scanResultData($where=''){
        if(empty($where)) {
            $where = [
                'is_del'=>0,
                'mate_type'=>1,
                'raw_judge'=>4,
                'annex_type'=>89235,
                new Like('raw_result',"1%")
            ];
        }
        $sig_id_arr = [];
        if(!empty($sig_id_arr)){
            $where['itemsig_id'] = $sig_id_arr;
        }

        $bool = true;
        $page = 0;
        $limit = 1000;
        $last_raw_id = 0;
        while ($bool) {
            $page++;
            echo "rawResultPAGE {$page}：" . PHP_EOL;
            $mateResultDataWhere = $where;
            $mateResultDataWhere[] = new Operator('id',Operator::OP_GT,$last_raw_id);
            $last_raw_id = $this->mateResultData($mateResultDataWhere , $limit,0);
            unset($mateResultDataWhere);
            if(!$last_raw_id) $bool = false;
        }
        unset($judge_name_arr);
    }

    /**
     * Notes: 获取指定条件下的结果数据  - 结果含上下箭头
     * User: lltyy
     * DateTime: 2023/4/25 10:16
     *
     * @param $where
     * @return array
     */
    public function mateResultData($where,$limit=0,$offset=0){
        //获取指定条件下的识别结果数据
        $rawCond = [
            'where'=>$where,
            'columns'=>['id','raw_result','raw_min','raw_max'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $rawCond['limit'] = $limit;
            $rawCond['offset'] = $offset;
        }
        $rawDatas = $this->LocalService()->tmpRawdata->fetchAll($rawCond);
        $last_id = 0;
        if(!empty($rawDatas)){
            foreach($rawDatas as $rawKey=>$rawData){
                $raw_id = $rawData['id'];
                $last_id = $rawData['id'];
                $set_min = !is_null($rawData['raw_min']) && $rawData['raw_min'] != '' ? $rawData['raw_min'] : '';
                $set_max = !is_null($rawData['raw_max']) && $rawData['raw_max'] != '' ? $rawData['raw_max'] : '';

                //识别结果异常判断
                $new_raw_result = substr_replace($rawData['raw_result'],'',0,1);
                $new_raw_judge = $this->getSetJudge($new_raw_result,$set_min,$set_max);
                if(in_array($new_raw_judge,[2,4])){
                    $update_data = [
                        'raw_result'=>$new_raw_result
                    ];
                    $this->LocalService()->tmpRawdata->update($update_data,['id'=>$raw_id]);
                }
                unset($rawDatas[$rawKey]);
            }
        }
        unset($rawDatas);
        //exit;
        return $last_id;
    }



    /**
     * Notes: 患者基线指标数据去重
     * User: lltyy
     * DateTime: 2023/4/25 10:16
     *
     * @param $where
     * @return array
     */
    public function mateOtherDateData($where){
        if(empty($where)) {
            $where = ['is_del'=>0,'mate_type'=>1];
        }
        $patient_id_arr = [];
        if(!empty($patient_id_arr)){
            $where['patient_id'] = $patient_id_arr;
        }

        //获取指定条件下的识别结果数据
        $rawCond = [
            'where'=>$where,
            'columns'=>['id','annex_type','custom_id','itemsig_id','patient_id','annex_id','enter_date','ct_date','patient_name','annex_name','raw_date','raw_name','keyword_id','new_keyword','mate_name','keyword_name','mate_category','raw_result','edit_result','edit_judge','edit_judge_name','raw_max','raw_min','raw_judge','judge_name'],
            'order'=>['raw_date ASC','patient_name ASC','annex_name ASC','id ASC']
        ];
        $rawDatas = $this->LocalService()->tmpRawdata->fetchAll($rawCond);
        $patientKeywordDateArr = [];
        if(!empty($rawDatas)){
            foreach($rawDatas as $rawKey=>&$rawData){
                if($rawData['annex_type'] == 89234){
                    $rawData['keyword_id'] = $rawData['new_keyword'];
                    $rawData['mate_name'] = $rawData['keyword_name'];
                    unset($rawData['new_keyword']);
                    unset($rawData['keyword_name']);
                }
                $key_id = $rawData['annex_type'].'_'.$rawData['patient_id'].'_'.$rawData['keyword_id'];
                $first_id = isset($patientKeywordDateArr[$key_id]) && isset($patientKeywordDateArr[$key_id]['id']) && !empty($patientKeywordDateArr[$key_id]['id']) ? $patientKeywordDateArr[$key_id]['id'] : 0;
                if((empty($first_id) && $rawData['annex_type'] == 89234) || $rawData['annex_type'] == 89235){
                    $patientKeywordDateArr[$key_id] = $rawData;
                    $patientKeywordDateArr[$key_id]['other_date'] = [];
                    $patientKeywordDateArr[$key_id]['other_id'] = [];
                    $patientKeywordDateArr[$key_id]['other_raw_result'] = [];
                    $patientKeywordDateArr[$key_id]['other_edit_result'] = [];
                }else{
                    $patientKeywordDateArr[$key_id]['other_id'][] = $rawData['id'];

                    $first_date = trim($patientKeywordDateArr[$key_id]['raw_date']);
                    $other_date = trim($rawData['raw_date']);
                    if($other_date != '' && !in_array($other_date,$patientKeywordDateArr[$key_id]['other_date']) && $other_date != $first_date){
                        $patientKeywordDateArr[$key_id]['other_date'][] = $other_date;
                    }

                    $first_raw_result = trim($patientKeywordDateArr[$key_id]['raw_result']);
                    $other_raw_result = trim($rawData['raw_result']);
                    if($other_raw_result != '' && !in_array($other_raw_result,$patientKeywordDateArr[$key_id]['other_raw_result']) && $other_raw_result != $first_raw_result){
                        $patientKeywordDateArr[$key_id]['other_raw_result'][] = $other_raw_result;
                    }

                    $first_edit_result = trim($patientKeywordDateArr[$key_id]['edit_result']);
                    $other_edit_result = trim($rawData['edit_result']);
                    if($other_edit_result != '' && !in_array($other_edit_result,$patientKeywordDateArr[$key_id]['other_edit_result']) && $other_edit_result != $first_edit_result){
                        $patientKeywordDateArr[$key_id]['other_edit_result'][] = $other_edit_result;
                    }
                }
                unset($rawDatas[$rawKey]);
            }
        }
        unset($rawDatas);

        $insertSqlArr = [];
        if(!empty($patientKeywordDateArr)){
            foreach($patientKeywordDateArr as $patientKey=>$patientKeywordDateInfo){
                $other_date = !empty($patientKeywordDateInfo['other_date']) ? implode(',',$patientKeywordDateInfo['other_date']) : '';
                $other_id = !empty($patientKeywordDateInfo['other_id']) ? implode(',',$patientKeywordDateInfo['other_id']) : '';
                $other_raw_result = !empty($patientKeywordDateInfo['other_raw_result']) ? implode(',',$patientKeywordDateInfo['other_raw_result']) : '';
                $other_edit_result = !empty($patientKeywordDateInfo['other_edit_result']) ? implode(',',$patientKeywordDateInfo['other_edit_result']) : '';
                $insertSqlArr[] = '('.$patientKeywordDateInfo['id'].','.$patientKeywordDateInfo['annex_type'].','.$patientKeywordDateInfo['custom_id'].','.$patientKeywordDateInfo['itemsig_id'].','.$patientKeywordDateInfo['patient_id'].','.$patientKeywordDateInfo['annex_id'].',"'.$patientKeywordDateInfo['enter_date'].'","'.$patientKeywordDateInfo['ct_date'].'","'.$patientKeywordDateInfo['patient_name'].'","'.$patientKeywordDateInfo['annex_name'].'","'.$patientKeywordDateInfo['raw_date'].'","'.$patientKeywordDateInfo['raw_name'].'",'.$patientKeywordDateInfo['keyword_id'].',"'.$patientKeywordDateInfo['mate_name'].'","'.$patientKeywordDateInfo['mate_category'].'","'.$patientKeywordDateInfo['raw_result'].'","'.$patientKeywordDateInfo['edit_result'].'",'.$patientKeywordDateInfo['edit_judge'].',"'.$patientKeywordDateInfo['edit_judge_name'].'","'.$patientKeywordDateInfo['raw_max'].'","'.$patientKeywordDateInfo['raw_min'].'",'.$patientKeywordDateInfo['raw_judge'].',"'.$patientKeywordDateInfo['judge_name'].'","'.$other_date.'","'.$other_id.'","'.$other_raw_result.'","'.$other_edit_result.'")';
                unset($patientKeywordDateArr[$patientKey]);
            }
        }
        unset($patientKeywordDateArr);

        echo "/*共插入《".count($insertSqlArr)."》条数据！";
        echo "<br>*/";
        $insertSql = 'INSERT INTO `yikeen_tmp_rawdata_unique` (`id`,`annex_type`,`custom_id`,`itemsig_id`,`patient_id`,`annex_id`,`enter_date`,`ct_date`,`patient_name`,`annex_name`,`raw_date`,`raw_name`,`keyword_id`,`mate_name`,`mate_category`,`raw_result`,`edit_result`,`edit_judge`,`edit_judge_name`,`raw_max`,`raw_min`,`raw_judge`,`judge_name`,`other_date`,`other_id`,`other_raw_result`,`other_edit_result`) VALUES ';
        if(!empty($insertSqlArr)){
            $insertSql .= implode(',',$insertSqlArr);
        }else{
            $insertSql = '';
        }
        echo $insertSql;
        exit;
    }

}