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

namespace Application\Service\DB\Tmp;

use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\Like;
use Laminas\Db\Sql\Predicate\Operator;

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

    /**
     * Notes: 更新数据
     * User: lltyy
     * DateTime: 2023/5/24 9:48
     *
     * @param $content //更新内容
     * @param $setWordDatas //设置的白名单数据
     * @param $oldMateDatas //历史已匹配信息
     * @param $oldLockDatas //历史已锁定信息
     * @return int
     */
    public function saveMedicalData($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'],
            'medical_date'=>$content['annex_date'],
            'medical_name'=>empty($content['raw_name']) ? '' : trim($content['raw_name']),
            'mate_type'=>1
        ];
        $result = $this->save($save_data);
        if($result){
            $ocrContentId = empty($ocrContentId) ? $result : $ocrContentId;

            //更新匹配信息
            $mate_data = [];
            if(!empty($content['mate_data'])){
                if(is_array($content['mate_data'])){
                    $mate_data = $content['mate_data'];
                }else{
                    $mate_data = explode(',',$content['mate_data']);
                }

            }
            $mate_data = array_values($mate_data);
            $save_mate = [
                'id'=>isset($oldMateDatas[$ocrContentId]) && !empty($oldMateDatas[$ocrContentId]) ? $oldMateDatas[$ocrContentId] : 0,
                'annex_id'=>$content['annex_id'],
                'itemsig_id'=>$content['itemsig_id'],
                'patient_id'=>$content['patient_id'],
                'medical_id'=>$ocrContentId,
                'medical_name'=>$save_data['medical_name'],
                'white_word'=>json_encode($setWordDatas),
                'mate_white'=>json_encode($mate_data)
            ];
            $this->LocalService()->tmpMedicalwhite->save($save_mate);
            unset($save_mate);

        }
        unset($save_data);
        unset($content);

        return $ocrContentId;
    }

    /**
     * Notes:获取附件下未匹配、已匹配、黑名单信息数据
     * User: lltyy
     * DateTime: 2023/5/18 8:31
     *
     * @param $where
     */
    public function fetchAnnexData($where){
        $arr = [
            'mate_id'=>[],//已匹配附件ID
            'mate_count'=>[],//附件下的已匹配数量
            'act_count'=>[],//附件下的已匹配有效数量
            'no_mate_id'=>[],//未匹配附件ID
            'no_mate_count'=>[],//附件下的未匹配数量
            'black_id'=>[],//黑名单附件ID
            'black_count'=>[],//附件下的黑名单数量
            'annex_date'=>[]//附件的采集时间
        ];
        $cond = [
            'where'=>$where,
            'columns'=>['annex_id','mate_type','is_lock','medical_date','drug_id']
        ];
        $datas = $this->fetchAll($cond);
        if(!empty($datas)){
            foreach($datas as $data){
                $mate_type = $data['mate_type'];
                $annex_id = $data['annex_id'];

                //附件时间
                $arr['annex_date'][$annex_id] = isset($arr['annex_date'][$annex_id]) && $arr['annex_date'][$annex_id] != '' ? $arr['annex_date'][$annex_id] : [];
                if($arr['annex_date'][$annex_id] == '' && $data['medical_date'] != '' && !in_array($data['medical_date'],$arr['annex_date'][$annex_id])){
                    $arr['annex_date'][$annex_id][] = $data['medical_date'];
                }

                //未匹配
                if(empty($mate_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){
                    $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;
                    if(!empty($data['drug_id'])){
                        $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($mate_type == 2){
                    $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(!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('medical_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()->tmpMedicalwhite->upDelState(['is_del'=>0,'medical_id'=>$delete_arr],1);
                $this->LocalService()->tmpMedicalblack->upDelState(['is_del'=>0,'medical_id'=>$delete_arr],1);
                $this->LocalService()->tmpMedicallock->upDelState(['is_del'=>0,'medical_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) {
                $where_arr[] = new Like('medical_name',"%{$replace['replace_pre']}%");
            }
            unset($replace_arr);

            $where['or'] = $where_arr;
            $cond = [
                'where' => $where,
                'columns' => ['id', 'annex_id', 'medical_name']
            ];
            $update_arr = $update_annex_arr = [];
            $datas = $this->fetchAll($cond);
            if (!empty($datas)) {
                foreach ($datas as $data) {
                    $medical_id = $data['id'];
                    $medical_name = $data['medical_name'];
                    foreach ($replace_datas as $replace_info) {
                        $medical_name = str_replace($replace_info['replace_pre'], $replace_info['replace_after'], $medical_name);
                    }

                    $update_data = [];
                    if ($medical_name != $data['medical_name']) {
                        $update_data['medical_name'] = $medical_name;
                    }
                    if (!empty($update_data)) {
                        if ($update_ocr == 0) {//更新明细信息
                            $this->LocalService()->tmpMedicallock->update($update_data, ['is_del'=>0,'medical_id'=>$medical_id]);
                        }

                        if ($update_ocr == 1) {//重新匹配
                            $update_arr[] = $medical_id;
                            $update_annex_arr[] = $data['annex_id'];
                            $update_data['mate_type'] = 0;
                        }
                        $this->update($update_data, ['id'=>$medical_id]);
                    }

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

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

                //获取黑/白名单数据
                $wordDatas = $this->LocalService()->tmpMedicalword->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'] : [];
                unset($wordDatas);

                //重新跑匹配
                $this->LocalService()->tmpMedicalwhite->mateWordData(['id'=>$update_arr],0,0,$white_word_arr,$black_word_arr);

                //更新附件信息
                $medical_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/5/26 14:42
     *
     * @param $where
     * @param $word_name
     */
    public function mateWordData($where,$word_name){
        $count = 0;
        $where['mate_type'] = 2;
        $where[] = new Like('medical_name',"%{$word_name}%");
        $cond = [
            'where' => $where,
            'columns' => ['id', 'annex_id']
        ];
        $update_arr = $update_annex_arr = [];
        $datas = $this->fetchAll($cond);
        if (!empty($datas)) {
            $count = 1;
            foreach ($datas as $data) {
                $update_arr[] = $data['id'];
                $update_annex_arr[] = $data['annex_id'];
            }
            $update_annex_arr = array_unique($update_annex_arr);
            $update_annex_arr = array_values($update_annex_arr);
        }
        unset($where_arr);
        unset($cond);
        unset($datas);

        //重新更新数据
        if(!empty($update_arr)){
            //删除已匹配数据
            $this->update(['mate_type'=>1],['id'=>$update_arr]);
            $this->LocalService()->tmpMedicalblack->upDelState(['is_del'=>0,'medical_id'=>$update_arr],1);

            //更新附件信息
            $medical_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','pid','out_date','out_result','out_drug'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->LocalService()->tmpPatient->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,'patient_id'=>$delete_mate_arr]);
            unset($delete_mate_arr);
            foreach ($datas as $dataKey=>$data) {
                $save_data = [
                    'table_id'=>0,
                    'itemsig_id'=>$data['pid'],
                    'patient_id'=>$data['id'],
                    'ocr_start_date'=>$data['out_date'],
                    'ocr_end_date'=>'',
                    'medical_date'=>$data['out_date'],
                    'out_result'=>$data['out_result'],
                    'is_lock'=>0,
                    'mate_type'=>0,
                ];
                $content_arr = [];
                $ocr_content_datas = json_decode($data['out_drug'],true);
                if(!empty($ocr_content_datas)){
                    foreach($ocr_content_datas as $ocr_content_data_key=>$ocr_content_arr){
                        $content_drug_arr = isset($ocr_content_arr['drug']) && !empty($ocr_content_arr['drug']) ? $ocr_content_arr['drug'] : [];
                        if(!empty($content_drug_arr)){
                            foreach($content_drug_arr as $content_drug_key=>$content_drug){
                                if(strpos($content_drug,'出院记录') === false){
                                    $content_arr[] = [
                                        'text_id'=>$ocr_content_arr['text_id'],
                                        'annex_id'=>$ocr_content_arr['annex_id'],
                                        'medical_name'=>$content_drug
                                    ];
                                }
                                unset($content_drug_arr[$content_drug_key]);
                            }
                        }
                        unset($content_drug_arr);
                        unset($ocr_content_datas[$ocr_content_data_key]);
                    }
                }
                unset($ocr_content_datas);

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

        return $last_id;
    }

    /**
     * Notes:出院记录 - 信息【调用此方法时修改表名为：yikeen_tmp_outmedical】
     * User: lltyy
     * DateTime: 2023/6/6 8:52
     *
     */
    public function scanData($where=[]) {
        //信息匹配
        if(empty($where)){
            $where = ['is_del'=>0,new Operator('pid',Operator::OP_GT,0)];
        }

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

    /**
     * Notes:更新出院日期及出院诊断
     * User: lltyy
     * DateTime: 2024/1/4 9:31
     *
     * @param string $where
     */
    public function updateOutData($where='',$type=1){
        //信息匹配
        if(empty($where)){
            $where = ['is_del'=>0,'annex_type'=>89226];
        }

        $sig_id_arr = [];
        if(!empty($sig_id_arr)){
            $where['sig_id'] = $sig_id_arr;
        }

        $updateSqlArr = [];

        //更新出院日期
        if($type == 1){
            $update_where = $where;
            //更新出院日期
            $where['or'] = [
                new Like('content',"%出院日期%"),
                new Like('content',"%出院记录时间%")
            ];
            $textCond = [
                'where'=>$where,
                'columns'=>['patient_id','content'],
                'order'=>['id']
            ];
            $textDatas = $this->LocalService()->tmpText->fetchAll($textCond);
            //echo "<pre>";
            //print_R($textDatas);exit;
            if(!empty($textDatas)){
                $patient_outdate_arr = [];
                foreach($textDatas as $textKey=>$textData){
                    $text_patient = $textData['patient_id'];
                    //echo $text_patient;exit;
                    $patient_outdate = isset($patient_outdate_arr[$text_patient]) && !empty($patient_outdate_arr[$text_patient]) ? $patient_outdate_arr[$text_patient] : '';
                    $text_content_arr = json_decode($textData['content'],true);
                    if(!empty($text_content_arr)){
                        foreach($text_content_arr as $text_content_key=>$text_content){
                            if($patient_outdate == ''){
                                $sub_arr = [];
                                if(strpos($text_content,'出院日期') !== false){
                                    $sub_arr = explode('出院日期',$text_content);
                                }
                                if(strpos($text_content,'出院记录时间') !== false){
                                    $sub_arr = explode('出院记录时间',$text_content);
                                }
                                if(isset($sub_arr[1]) && !empty($sub_arr[1])){
                                    $sub_str = str_replace(["：",":"],'',$sub_arr[1]);
                                    $outdate_arr = explode('日',$sub_str);
                                    $patient_outdate = isset($outdate_arr[0]) && !empty($outdate_arr[0]) ? $outdate_arr[0] : '';
                                    if($patient_outdate != ''){
                                        $outdate_str = str_replace(["年","月"],'-',$patient_outdate);
                                        $outdate_arr = explode('-',$outdate_str);
                                        $outdate = $outdate_arr[0];
                                        if(strlen($outdate_arr[1]) < 2){
                                            $outdate .= '0'.$outdate_arr[1];
                                            if(strlen($outdate_arr[2]) < 2){
                                                $outdate .= '0'.$outdate_arr[2];
                                            }else{
                                                $outdate .= $outdate_arr[2];
                                            }
                                        }else{
                                            $outdate .= $outdate_arr[1];
                                            if(strlen($outdate_arr[2]) < 2){
                                                $outdate .= '0'.$outdate_arr[2];
                                            }else{
                                                $outdate .= $outdate_arr[2];
                                            }
                                        }
                                        $patient_outdate_arr[$text_patient] = $outdate;
                                    }
                                }
                            }
                            unset($text_content_arr[$text_content_key]);
                        }
                        unset($text_content_arr);
                    }
                    unset($textDatas[$textKey]);
                }
                //echo "共《".count($patient_outdate_arr)."》患者！";
                //echo "<br><pre>";
                //print_R($patient_outdate_arr);exit;
                if(!empty($patient_outdate_arr)){
                    foreach($patient_outdate_arr as $patient_id=>$outdate){
                        $updateSqlArr[] = "UPDATE `yikeen_tmp_patient` SET `out_date` = '".$outdate."' WHERE id = ".$patient_id;
                        unset($patient_outdate_arr[$patient_id]);
                    }
                }
                unset($patient_outdate_arr);
            }
            unset($textDatas);
            echo "共更新《".count($updateSqlArr)."》位患者！";
        }

        //更新出院诊断
        if($type == 2){
            $updateData = [];
            //更新出院日期
            $where['or'] = [
                new Like('content',"%出院诊断%"),
                new Like('content',"%出院情况%"),
                new Like('content',"%出院医嘱%")
            ];
            $textCond = [
                'where'=>$where,
                'columns'=>['patient_id','content'],
                'order'=>['id']
            ];
            $textDatas = $this->LocalService()->tmpText->fetchAll($textCond);
            //echo "<pre>";
            //print_R($textDatas);exit;
            if(!empty($textDatas)){
                foreach($textDatas as $textKey=>$textData){
                    $text_patient = $textData['patient_id'];
                    $out_result = '';
                    $text_content_arr = json_decode($textData['content'],true);
                    $text_content = implode("",$text_content_arr);
                    if(strpos($text_content,'出院诊断') !== false){
                        $sub_arr = explode('出院诊断',$text_content);
                        unset($text_content);
                        unset($sub_arr[0]);
                        $out_result = implode('出院诊断',$sub_arr);
                        if(strpos($out_result,'出院情况') !== false){
                            $out_result_arr = explode('出院情况',$out_result);
                            $out_result = $out_result_arr[0];
                            $is_end = 1;
                        }else{
                            if(strpos($out_result,'出院医嘱') !== false){
                                $out_result_arr = explode('出院医嘱',$out_result);
                                $out_result = $out_result_arr[0];
                                $is_end = 1;
                            }
                        }
                    }else{
                        $start_index = $end_index = -1;
                        if(strpos($text_content,'出院情况') !== false){
                            foreach($text_content_arr as $text_content_index=>$text_content_str){
                                if($start_index == -1 && strpos($text_content_str,'住院病历号') !== false){
                                    $start_index = $text_content_index;
                                }
                                if($end_index == -1 && strpos($text_content_str,'出院情况') !== false){
                                    $end_index = $text_content_index;
                                    $is_end = 1;
                                }
                            }
                        }else{
                            foreach($text_content_arr as $text_content_index1=>$text_content_str1){
                                if($end_index == -1 && strpos($text_content_str1,'出院医嘱') !== false){
                                    $end_index = $text_content_index1;
                                    $is_end = 1;
                                }
                            }
                        }
                        if($start_index != -1){
                            foreach($text_content_arr as $text_content_index2=>$text_content_str2){
                                if($start_index < $text_content_index2 && (($end_index != -1 && $end_index > $text_content_index2) || $end_index == -1)){
                                    $out_result .= $text_content_str2;
                                }
                            }
                        }
                    }

                    $out_result = trim($out_result,"：");
                    $out_result = trim($out_result,":");
                    if(strpos($out_result,'初步诊断') === false){
                        if(strpos($out_result,'第') !== false){
                            $out_result_arr1 = explode('第',$out_result);
                            $out_result = $out_result_arr1[0];
                            $is_end = 0;
                        }
                        //if($out_result != ''){
                        $updateData[$text_patient]['result'] .= $out_result;
                        $updateData[$text_patient]['is_end'] = $is_end;
                        //$updateSqlArr[] = "UPDATE `yikeen_tmp_text` SET `out_result` = '".$out_result."' WHERE id = ".$textData['id'];
                        //}
                    }
                    unset($textDatas[$textKey]);
                }
            }
            unset($textDatas);

            if(!empty($updateData)){
                foreach($updateData as $patient_id=>$update_info){
                    $updateSqlArr[] = "UPDATE `yikeen_tmp_patient` SET `out_result` = '".$update_info['result']."' WHERE id = ".$patient_id;
                    unset($updateData[$patient_id]);
                }
            }
            unset($updateData);
            echo "共更新《".count($updateSqlArr)."》条数据！";
            //echo "<br><pre>";
            //print_R($updateData);exit;
        }

        //更新出院用药
        if($type == 3){
            $updateData = [];
            //更新出院日期
            $textCond = [
                'where'=>$where,
                'columns'=>['id','sig_id','patient_id','annex_id','content'],
                'order'=>['id']
            ];
            $textDatas = $this->LocalService()->tmpText->fetchAll($textCond);
            //echo "<pre>";
            //print_R($textDatas);exit;
            if(!empty($textDatas)){
                $subword_arr = ["医嘱服药","口服药物","口服用药","出院服药","医嘱长期服药","用药方案","药物治疗"];
                foreach($textDatas as $textKey=>$textData){
                    $text_patient = $textData['patient_id'];
                    $text_content_arr = json_decode($textData['content'],true);
                    $text_content = implode("",$text_content_arr);
                    if(strpos($text_content,'出院医嘱') !== false){
                        $start_medical_index = -1;
                        $start_drug_index = -1;
                        $medical_content_arr = [];
                        $start_medical_page = 0;
                        foreach($text_content_arr as $text_content_index=>$text_content){
                            if($start_medical_index == -1){
                                if(strpos($text_content,'出院医嘱') !== false){
                                    $start_medical_index = $text_content_index;
                                }
                            }else{
                                if($text_content_index > $start_medical_index){
                                    if($start_drug_index == -1){
                                        if(strpos($text_content,'医嘱服药') !== false){
                                            $start_drug_index = $text_content_index;
                                        }
                                        if(strpos($text_content,'口服药物') !== false){
                                            $start_drug_index = $text_content_index;
                                        }
                                        if(strpos($text_content,'口服用药') !== false){
                                            $start_drug_index = $text_content_index;
                                        }
                                        if(strpos($text_content,'出院服药') !== false){
                                            $start_drug_index = $text_content_index;
                                        }
                                        if(strpos($text_content,'医嘱长期服药') !== false){
                                            $start_drug_index = $text_content_index;
                                        }
                                        if(strpos($text_content,'用药方案') !== false){
                                            $start_drug_index = $text_content_index;
                                        }
                                        if(strpos($text_content,'药物治疗') !== false){
                                            $start_drug_index = $text_content_index;
                                        }
                                    }else{
                                        if($text_content_index > $start_drug_index){
                                            if(strpos($text_content,'第') !== false){
                                                $medical_page_arr = explode("第",trim($text_content));
                                                $medical_page_arr = array_values(array_filter($medical_page_arr));
                                                $medical_pageend_arr = explode("页",$medical_page_arr[0]);
                                                $medical_pageend_arr = array_values(array_filter($medical_pageend_arr));
                                                $start_medical_page = intval($medical_pageend_arr[0]);
                                            }else{
                                                $medical_content_arr[] = $text_content;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if($start_medical_index > 0 && $start_drug_index == -1 && empty($start_medical_page)){
                            foreach($text_content_arr as $text_content_index1=>$text_content1){
                                if($text_content_index1 > $start_medical_index){
                                    if(strpos($text_content1,'第') !== false){
                                        $medical_page_arr1= explode("第",trim($text_content1));
                                        $medical_page_arr1 = array_values(array_filter($medical_page_arr1));
                                        $medical_pageend_arr1 = explode("页",$medical_page_arr1[0]);
                                        $medical_pageend_arr1 = array_values(array_filter($medical_pageend_arr1));
                                        $start_medical_page = intval($medical_pageend_arr1[0]);
                                    }
                                }
                            }
                        }
                        if($start_medical_page > 0 || !empty($medical_content_arr)){
                            if(!empty($medical_content_arr)){
                                $updateData[$text_patient]['content'][] = [
                                    'text_id'=>$textData['id'],
                                    'itemsig_id'=>$textData['sig_id'],
                                    'patient_id'=>$text_patient,
                                    'annex_id'=>$textData['annex_id'],
                                    'drug'=>$medical_content_arr
                                ];
                            }
                            if($start_medical_page > 0 && empty($updateData[$text_patient]['start_page'])){
                                $updateData[$text_patient]['start_page'] = $start_medical_page;
                                $updateData[$text_patient]['page'][] = $start_medical_page;
                            }
                        }
                        unset($textDatas[$textKey]);
                    }else{
                        $patient_start_page = isset($updateData[$text_patient]) && isset($updateData[$text_patient]['start_page']) && !empty($updateData[$text_patient]['start_page']) ? $updateData[$text_patient]['start_page'] : 0;
                        if($patient_start_page > 0){
                            $now_start_index = -1;
                            $text_content_num = count($text_content_arr);
                            $now_page_arr = explode('第',$text_content_arr[$text_content_num-1]);
                            $now_page_arr = array_values(array_filter($now_page_arr));
                            $now_pageend_arr = explode("页",$now_page_arr[0]);
                            $now_pageend_arr = array_values(array_filter($now_pageend_arr));
                            $now_page = intval($now_pageend_arr[0]);
                            if($now_page > $patient_start_page){
                                $now_content_arr = [];
                                foreach($text_content_arr as $text_content_index2=>$text_content2){
                                    if($now_start_index == -1){
                                        if(strpos($text_content2,'住院病历号') !== false){
                                            $now_start_index = $text_content_index2;
                                        }
                                    }else{
                                        if($text_content_index2 > $now_start_index){
                                            if(strpos($text_content2,'第') === false){
                                                $now_content_arr[] = $text_content2;
                                            }
                                        }
                                    }
                                }
                                if(!empty($now_content_arr)){
                                    $updateData[$text_patient]['content'][] = [
                                        'text_id'=>$textData['id'],
                                        'itemsig_id'=>$textData['sig_id'],
                                        'patient_id'=>$text_patient,
                                        'annex_id'=>$textData['annex_id'],
                                        'drug'=>$now_content_arr
                                    ];
                                }
                                $updateData[$text_patient]['page'][] = $now_page;
                                unset($textDatas[$textKey]);
                            }
                        }
                    }
                    unset($text_content_arr);
                    unset($text_content);
                }
            }

            if(!empty($textDatas)){
                foreach($textDatas as $textKey3=>$textData3){
                    $text_patient3 = $textData3['patient_id'];
                    $patient_start_page3 = isset($updateData[$text_patient3]) && isset($updateData[$text_patient3]['start_page']) && !empty($updateData[$text_patient3]['start_page']) ? $updateData[$text_patient3]['start_page'] : 0;
                    if($patient_start_page3 > 0){
                        $now_start_index3 = -1;
                        $text_content_arr3 = json_decode($textData3['content'],true);
                        $text_content_num3 = count($text_content_arr3);
                        $now_page_arr3 = explode('第',$text_content_arr3[$text_content_num3-1]);
                        $now_page_arr3 = array_values(array_filter($now_page_arr3));
                        $now_pageend_arr3 = explode("页",$now_page_arr3[0]);
                        $now_pageend_arr3 = array_values(array_filter($now_pageend_arr3));
                        $now_page3 = intval($now_pageend_arr3[0]);
                        $patient_page = isset($updateData[$text_patient3]) && isset($updateData[$text_patient3]['page']) && !empty($updateData[$text_patient3]['page']) ? $updateData[$text_patient3]['page'] : [];
                        if($now_page3 > $patient_start_page3 && !in_array($now_page3,$patient_page)){
                            $now_content_arr3 = [];
                            foreach($text_content_arr3 as $text_content_index3=>$text_content3){
                                if($now_start_index3 == -1){
                                    if(strpos($text_content3,'住院病历号') !== false){
                                        $now_start_index3 = $text_content_index3;
                                    }
                                }else{
                                    if($text_content_index3 > $now_start_index3){
                                        if(strpos($text_content3,'第') === false){
                                            $now_content_arr3[] = $text_content3;
                                        }
                                    }
                                }
                            }
                            if(!empty($now_content_arr3)){
                                $updateData[$text_patient3]['content'][] = [
                                    'text_id'=>$textData3['id'],
                                    'itemsig_id'=>$textData3['sig_id'],
                                    'patient_id'=>$text_patient3,
                                    'annex_id'=>$textData3['annex_id'],
                                    'drug'=>$now_content_arr3
                                ];
                            }
                            unset($now_content_arr3);
                            $updateData[$text_patient3]['page'][] = $now_page3;
                            unset($textDatas[$textKey3]);
                        }
                    }
                }
            }
            unset($textDatas);

            if(!empty($updateData)){
                foreach($updateData as $patient_id=>$update_info){
                    $content_json = isset($update_info['content']) && !empty($update_info['content']) ? json_encode($update_info['content']) : json_encode([]);
                    $this->LocalService()->tmpPatient->update(['out_drug'=>$content_json],['id'=>$patient_id]);
                    //$updateSqlArr[] = "UPDATE `yikeen_tmp_patient` SET `out_drug` = '".$content_json."' WHERE id = ".$patient_id;
                    unset($updateData[$patient_id]);
                }
            }
            //unset($updateData);
            echo "共更新《".count($updateSqlArr)."》条数据！";
            //echo "<br><pre>";
            //print_R($updateData);exit;
        }

        echo "<br><pre>";
        echo implode(";",$updateSqlArr);
    }

}