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

namespace Application\Service\DB\Ocr;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Store\Store;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\Like;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Stdlib\ArrayUtils;

class Rawdata extends \Application\Service\DB\AbstractDb
{
    public function __construct($dbAdapter, ContainerInterface $container)
    {
        $this->tableName = 'yikeen_ocr_rawdata';
        //$this->tableName = 'yikeen_ocr_rawlock_unique';
        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'],
            'sig_id'=>$content['sig_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->LocalService()->ocrRawdata->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()->ocrMatedata->update(['is_mate'=>0],[
                    'is_del' => 0,
                    'is_mate' => 1,
                    'raw_id' => $ocrContentId,
                ]);
                if(!empty($oldMateInfo)){
                    $this->LocalService()->ocrMatedata->update(['is_mate'=>1],[
                        'id' => $oldMateInfo['id'],
                    ]);
                }else{
                    $save_mate = [
                        'annex_id'=>$content['annex_id'],
                        'sig_id'=>$content['sig_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()->ocrMatedata->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['or'][] = new Like('raw_name', "%{$delete_name}%");
            }
            $where[] = $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' => StringHelper::toArray($delete_arr)
                ],1);
                $this->LocalService()->ocrMatedata->upDelState([
                    'is_del' => 0,
                    'raw_id' => StringHelper::toArray($delete_arr)
                ],1);
                $this->LocalService()->ocrRawblack->upDelState([
                    'is_del' => 0,
                    'raw_id' => StringHelper::toArray($delete_arr)
                ],1);
                $this->LocalService()->ocrRawlock->upDelState([
                    'is_del' => 0,
                    'raw_id' => StringHelper::toArray($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' => StringHelper::toArray($annex_arr)
                ]);
                $medical_annex_count_arr = $this->LocalService()->ocrMedical->fetchAnnexData('id < 0');
                $ct_annex_count_arr = $this->LocalService()->ocrCt->fetchAnnexData('id < 0');
                $this->LocalService()->ocrOcrannex->updateAnnexCount([
                    'id' => StringHelper::toArray($annex_arr)
                ],0,0,$annex_count_arr,$medical_annex_count_arr,$ct_annex_count_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['or'][] = new Like('raw_name', "%{$replace['replace_pre']}%");
                }
                if ($replace['info_type'] == 1) {
                    $where_arr['or'][] = new Like('raw_result', "%{$replace['replace_pre']}%");
                }
            }
            unset($replace_arr);

            $where[] = $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()->ocrRawlock->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()->ocrMatedata->upDelState([
                    'is_del' => 0,
                    'raw_id' => StringHelper::toArray($update_arr),
                ],1);
                $this->LocalService()->ocrRawblack->upDelState([
                    'is_del' => 0,
                    'raw_id' => StringHelper::toArray($update_arr),
                ],1);

                //获取指标关键字信息
                $keywordCond = [
                    'where'=>'is_del = 0 and keyword_name is not null and keyword_name != ""',
                    'columns'=>['id','category_name','keyword_code','keyword_name'],
                    'order'=>['category_name','parent_id','id']
                ];
                $keywordDatas = $this->LocalService()->ocrKeyword->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()->ocrRawword->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()->ocrMatedata->mateRawdata([
                    'id' => StringHelper::toArray($update_arr),
                ],0,0,$keywordDatas,$black_word_arr);

                //更新附件信息
                $raw_annex_arr = $this->fetchAnnexData([
                    'is_del' => 0,
                    'annex_id' => StringHelper::toArray($update_annex_arr)
                ]);
                $medical_annex_count_arr = $this->LocalService()->ocrMedical->fetchAnnexData('id < 0');
                $ct_annex_count_arr = $this->LocalService()->ocrCt->fetchAnnexData('id < 0');
                $annex_where = [
                    'is_del' => 0,
                    'annex_type' => 1,
                    'id' => StringHelper::toArray($update_annex_arr)
                ];
                $this->LocalService()->ocrOcrannex->updateAnnexCount($annex_where,0,0,$raw_annex_arr,$medical_annex_count_arr,$ct_annex_count_arr);

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

    /**
     * Notes:
     * User: lltyy
     * DateTime: 2023/6/6 8:52
     *
     */
    public function updateRawData($where,$limit=0,$offset=0){
        $cond = [
            'where'=>$where,
            'columns'=>['id','raw_result','raw_date','raw_judge'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->fetchAll($cond);
        $count = 0;
        if(!empty($datas)){
            $count = 1;
            foreach($datas as $data){
                //更新识别结果
                $raw_result = trim($data['raw_result']);
                $raw_result = $this->replaceRawdata($raw_result,0);
                $raw_result = $raw_result != '' ? $raw_result : '';

                //更新识别判断
                $raw_judge = $data['raw_judge'];
                if($raw_result != '' && strpos($raw_result,'↑')){
                    $raw_judge = 1;
                }
                if($raw_result != '' && strpos($raw_result,'↓')){
                    $raw_judge = 2;
                }
                $raw_result = str_replace(['↑','↓'],'',$raw_result);//替换字符串中的特殊字符
                $raw_result = $raw_result != '' ? $raw_result : '';

                //更新日期
                $raw_date = trim($data['raw_date']);
                $raw_date = $this->replaceRawdata($raw_date,1);
                $raw_date = $raw_date != '' ? $raw_date : '';
                if($raw_date != ''){
                    if(strpos('020',$raw_date) == 0 || strpos('021',$raw_date) == 0 || strpos('022',$raw_date) == 0 || strpos('023',$raw_date) == 0){
                        $raw_date = '2'.$raw_date;
                    }
                }

                $this->update(['raw_result'=>$raw_result,'raw_judge'=>$raw_judge,'raw_date'=>$raw_date],'id = '.$data['id']);

            }
        }
        unset($datas);
        unset($cond);
        return $count;
    }

    /**
     * Notes:
     * User: lltyy
     * DateTime: 2023/6/6 8:52
     *
     */
    public function scanRawdata($where){
        $bool = true;
        $page = 0;
        $limit = 1000;
        while ($bool) {
            $page++;
            echo "ResultPage {$page}：" . PHP_EOL;
            $offset = intval(($page - 1) * $limit);
            $dataCount = $this->updateRawData($where,$limit,$offset);
            if(!$dataCount) $bool = false;
        }
    }

    /**
     * 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 $raw_result //识别结果
     * @param string $set_min //最小值
     * @param string $set_max //最大值
     * @return int
     * $set_judge
     *      0：正常
     *      3：为空 或 为 0 值
     *      4：异常偏低【超过最小值的二分之一】
     *      2：偏低
     *      5：异常偏高【超过最大值的2倍】 或 非数字
     *      1：偏高
     */
    public function getSetJudge($raw_result='',$set_min='',$set_max=''){
        $raw_result = is_null($raw_result) || $raw_result == '' ? '' : $raw_result;
        $set_min = is_null($set_min) || $set_min == '' ? '' : $set_min;
        $set_max = is_null($set_max) || $set_max == '' ? '' : $set_max;
        $set_judge = 0;
        if($raw_result == '' || empty($raw_result)){
            $set_judge = 3;
        }else{
            if(in_array($raw_result,['>','<'])){
                if(in_array($raw_result,['<'])){
                    $raw_result = str_replace('<','',$raw_result);
                }elseif(in_array($raw_result,['>'])){
                    $raw_result = str_replace('>','',$raw_result);
                }
            }

            $other_result = str_replace('.','',$raw_result);
            $other_result = preg_replace('/\\d+/','',$other_result);
            if($other_result != ''){
                $set_judge = 5;
            }else{
                if(is_numeric($raw_result)){
                    $raw_result = floatval($raw_result);
                    //判断结果是否偏低
                    if ($set_min != '' && $raw_result < $set_min) {
                        $two_set_min = $set_min/2;
                        if($raw_result < $two_set_min){
                            $set_judge = 4;
                        }else{
                            $set_judge = 2;
                        }
                    }
                    //判断结果是否偏高
                    if ($set_max != '' && $raw_result > $set_max) {
                        $two_set_max = $set_max*2;
                        if($raw_result > $two_set_max){
                            $set_judge = 5;
                        }else{
                            $set_judge = 1;
                        }
                    }
                }else{
                    $set_judge = 5;
                }
            }
        }

        return $set_judge;
    }


    /**
     * Notes:异常判断【更改表为 yikeen_ocr_rawlock_unique】
     * User: lltyy
     * DateTime: 2023/6/6 8:52
     *
     */
    public function scanJudge($where=''){
        if(empty($where)){
            $where = ['is_del' => 0];
        }
        $bool = true;
        $page = 0;
        $limit = 1000;
        $last_id = 0;
        while ($bool) {
            $page++;
            echo "JudgePage {$page}：" . PHP_EOL;
            $last_id = $this->updateJudgeData(ArrayUtils::merge($where, [
                new Operator('id', Operator::OP_GT, $last_id)
            ]),$limit,0);
            if(!$last_id) $bool = false;
        }
    }

    /**
     * Notes:
     * User: lltyy
     * DateTime: 2023/6/6 8:52
     * $set_judge
     *      0：正常
     *      3：为空 或 为 0 值
     *      4：异常偏低【超过最小值的二分之一】
     *      2：偏低
     *      5：异常偏高【超过最大值的2倍】 或 非数字
     *      1：偏高
     */
    public function updateJudgeData($where,$limit=0,$offset=0){
        $cond = [
            'where'=>$where,
            'columns'=>['id','raw_result','raw_max','raw_min'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->fetchAll($cond);
        unset($cond);
        $last_id = 0;
        if(!empty($datas)){
            $judge_arr = [0=>'',1=>'高',2=>'低',3=>'为空或为0',4=>'超低',5=>'超高'];
            foreach($datas as $key=>$data){
                $last_id = $data['id'];
                //依据设置判断数据
                $set_judge = 0;
                $raw_result = $data['raw_result'] != '' ? $data['raw_result'] : '';
                $set_min = isset($data['raw_min']) && $data['raw_min'] != '' ? floatval($data['raw_min']) : '';
                $set_max = isset($data['raw_max']) && $data['raw_max'] != '' ? floatval($data['raw_max']) : '';
                $set_judge = $this->getSetJudge($raw_result,$set_min,$set_max);
                $set_judge = empty($set_judge) ? 0 : $set_judge;
                $judge_name = isset($judge_arr[$set_judge]) && !empty($judge_arr[$set_judge]) ? $judge_arr[$set_judge] : '';
                $this->update(['raw_judge'=>$set_judge,'judge_name'=>$judge_name],'id = '.$data['id']);
                unset($datas[$key]);
            }
        }
        unset($datas);
        return $last_id;
    }
}