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

namespace Application\Service\DB\Tmp;

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

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


    /**
     * Notes: 获取指定条件下的数据
     * User: lltyy
     * DateTime: 2023/4/25 10:16
     *
     * @param $where
     * @param $where
     * @return array
     */
    public function fetchDataById($where,$columns){
        $datas = [];
        $cond = [
            'where'=>$where,
            'columns'=>$columns
        ];
        $infoDatas = $this->fetchAll($cond);
        if(!empty($infoDatas)){
            foreach($infoDatas as $infoData){
                $id = $infoData['id'];
                $datas[$id] = $infoData;
            }
        }
        unset($cond);
        unset($infoDatas);
        return $datas;
    }


    /**
     * Notes:获取指定的入院记录数据 与 入院记录关键字匹配，存入匹配信息表
     * User: lltyy
     * DateTime: 2023/5/26 15:00
     *
     * @param $where//条件
     * @param int $limit
     * @param int $offset
     * @param $word_arr//入院记录
     * @return int
     */
    public function mateData($where,$limit=0,$offset=0,&$wordDatas=[],$select_type=0){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','itemsig_id','patient_id','ocr_content','category_type'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->fetchAll($cond);

        $last_id = 0;
        if(!empty($datas)){
            $patient_sex_arr = $this->LocalService()->tmpPatient->fetchCol('sex',['is_del'=>0,'select_type'=>$select_type,new Operator('pid',Operator::OP_GT,0)]);
            $delete_mate_arr = [];
            foreach($datas as $data_info){
                $last_id = $data_info['id'];
                $delete_mate_arr[] = $data_info['id'];
            }

            //删除原匹配数据
            //$this->update(['mate_type'=>0,'is_lock'=>0,'content'=>json_encode([])],['is_del'=>0,'id'=>$delete_mate_arr]);
            unset($delete_mate_arr);

            $delete_str_arr = [":",",",".","·"];
            foreach ($datas as $dataKey=>$data) {
                $info_id = $data['id'];
                $ocr_content_str = implode("",json_decode($data['ocr_content'],true));
                $ocr_content_str = str_replace(' ','',$ocr_content_str);
                if(strpos($ocr_content_str,"：") !== false){
                    $ocr_content_str = str_replace("：",':',$ocr_content_str);
                }
                if(strpos($ocr_content_str,"，") !== false){
                    $ocr_content_str = str_replace("，",',',$ocr_content_str);
                }
                if(strpos($ocr_content_str,"。") !== false){
                    $ocr_content_str = str_replace("。",'.',$ocr_content_str);
                }

                foreach($delete_str_arr as $delete_str){
                    if(mb_substr($ocr_content_str,0,1) === $delete_str){
                        $ocr_content_str = ltrim($ocr_content_str,$delete_str);
                    }
                    if(mb_substr($ocr_content_str,-1,1) === $delete_str){
                        $ocr_content_str = rtrim($ocr_content_str,$delete_str);
                    }
                }

                $data_patient = $data['patient_id'];
                $patient_sex = isset($patient_sex_arr[$data_patient]) && !empty($patient_sex_arr[$data_patient]) ? $patient_sex_arr[$data_patient] : 0;
                $category_type = $mate_type = 0;
                $content_arr = [];
                if($select_type == 1){
                    $category_type = $data['category_type'];
                    $data_sig = $data['itemsig_id'];
                    if(isset($wordDatas[$data_sig]) && !empty($wordDatas[$data_sig])){
                        foreach($wordDatas[$data_sig] as $wordData){
                            $filed_value = '';
                            $data_category_type = $wordData['category_type'];
                            if($data_category_type == $category_type && strpos($ocr_content_str,$wordData['english']) !== false) {
                                $cut_str = '';//该信息截取的字符串
                                //判断是否含前置顶信息
                                if(!empty($wordData['cut_start'])){
                                    if(strpos($ocr_content_str,$wordData['cut_start']) !== false){
                                        $cut_str_arr = explode($wordData['cut_start'], $ocr_content_str);
                                        if(count($cut_str_arr) > 1){
                                            unset($cut_str_arr[0]);
                                            $cut_str_arr = array_values($cut_str_arr);
                                            if(count($cut_str_arr) > 1){
                                                $cut_str = implode($wordData['cut_start'],$cut_str_arr);
                                            }else{
                                                $cut_str = implode('',$cut_str_arr);
                                            }
                                        }else{
                                            $cut_str = implode('',$cut_str_arr);
                                        }
                                    }else{
                                        $cut_str = $ocr_content_str;
                                    }
                                }else{
                                    $cut_str = $ocr_content_str;
                                }
                                if((!empty($wordData['cut_pre']) && strpos($cut_str,$wordData['cut_pre']) !== false) || (!empty($wordData['cut_after']) && strpos($cut_str,$wordData['cut_after']) !== false)) {
                                    $filed_value = $cut_str;
                                    if ($filed_value != '' && !empty($wordData['cut_pre']) && strpos($cut_str, $wordData['cut_pre']) !== false) {
                                        $cut_pre_arr = explode($wordData['cut_pre'], $filed_value);
                                        if(count($cut_pre_arr) > 1){
                                            unset($cut_pre_arr[0]);
                                            $cut_pre_arr = array_values($cut_pre_arr);
                                            if(count($cut_pre_arr) > 1){
                                                $filed_value = implode($wordData['cut_pre'],$cut_pre_arr);
                                            }else{
                                                $filed_value = implode('',$cut_pre_arr);
                                            }
                                        }else{
                                            $filed_value = implode('',$cut_pre_arr);
                                        }
                                    }
                                    if ($filed_value != '' && !empty($wordData['cut_after']) && strpos($cut_str, $wordData['cut_after']) !== false) {
                                        $cut_after_arr = explode($wordData['cut_after'], $filed_value);
                                        $filed_value = $cut_after_arr[0];
                                    }
                                    if($filed_value != ''){
                                        foreach ($delete_str_arr as $delete_str1) {
                                            if (mb_substr($filed_value, 0, 1) === $delete_str1) {
                                                $filed_value = ltrim($filed_value, $delete_str1);
                                            }
                                            if (mb_substr($filed_value, -1, 1) === $delete_str1) {
                                                $filed_value = rtrim($filed_value, $delete_str1);
                                            }
                                        }
                                    }
                                    //截取长度
                                    if(!empty($wordData['cut_length']) && strlen($filed_value) > $wordData['cut_length']){
                                        $filed_value = substr($filed_value,0,$wordData['cut_length']);
                                    }
                                    //更新患者性别
                                    if ($wordData['name'] == '性别' && $wordData['category_type'] == 4 && !empty($filed_value)) {
                                        if (empty($patient_sex)) {
                                            if (strpos($filed_value, '男') !== false) {
                                                $patient_sex = 1;
                                            }
                                            if (strpos($filed_value, '女') !== false) {
                                                $patient_sex = 2;
                                            }
                                        }
                                    }
                                }
                            }

                            if($filed_value != ''){
                                $wordData_id = $wordData['id'];
                                $content_arr[$wordData_id] = [
                                    'id'=>$wordData_id,
                                    'name'=>$wordData['name'],
                                    'category_id'=>$wordData['category_id'],
                                    'result'=>$filed_value,
                                    'children'=>[]
                                ];
                                $mate_type = 1;
                            }
                        }
                    }
                }else{
                    $ocr_content_arr = [
                        1=>$ocr_content_str,
                        2=>$ocr_content_str,
                        3=>$ocr_content_str
                    ];
                    //判断是否为病史小结体格检查
                    $all_content_arr = [];
                    $num_arr = [
                        1=>0,
                        2=>0,
                        3=>0
                    ];
                    if(!empty($wordDatas)){
                        foreach($wordDatas as $wordData){
                            $parent_data = [];
                            $end_parent_str = '';
                            $data_category_type = $wordData['category_type'];
                            if(strpos($ocr_content_str,$wordData['name']) !== false || ($wordData['name'] == '腹部' && $wordData['category_type'] == 2)) {
                                $cut_pre_str_arr = !empty($wordData['cut_pre']) ? explode($wordData['cut_pre'], $ocr_content_arr[$data_category_type]) : [];
                                unset($cut_pre_str_arr[0]);
                                $cut_pre_str = implode($wordData['cut_pre'],$cut_pre_str_arr);
                                if($wordData['name'] == '腹部' && $wordData['category_type'] == 2 && strpos($ocr_content_str,$wordData['name']) === false){
                                    $cut_pre_str_arr = !empty('视诊') ? explode('视诊', $ocr_content_arr[$data_category_type]) : [];
                                    $cut_pre_str_num = count($cut_pre_str_arr)-1;
                                    $cut_pre_str = $cut_pre_str_num > 0 ? $cut_pre_str_arr[$cut_pre_str_num] : [];
                                }
                                $cut_after_str_arr = !empty($wordData['cut_after']) && !empty($cut_pre_str) ? explode($wordData['cut_after'], $cut_pre_str) : [];
                                if(empty($cut_after_str_arr) && !empty($cut_pre_str)){
                                    $cut_after_str_arr = [$cut_pre_str];
                                }
                                $parent_str = !empty($cut_after_str_arr) ? $cut_after_str_arr[0] : '';
                                /*if($wordData['name'] == '病史小结' && $wordData['category_type'] == 3){
                                    echo "ocr_content_str = ".$ocr_content_str."<br>";
                                    echo "cut_pre = ".$wordData['cut_pre']."<br>";
                                    echo "cut_pre_str_arr = ";
                                    print_R($cut_pre_str_arr);
                                    echo "<br>";
                                    echo "cut_pre_str = ".$cut_pre_str."<br>";
                                    echo "cut_after = ".$wordData['cut_after']."<br>";
                                    echo "cut_after_str_arr = ";
                                    print_R($cut_after_str_arr);
                                    echo "<br>";
                                    echo "parent_str = ".$parent_str."<br>";
                                    exit;
                                }*/
                                if(!empty($parent_str) && $wordData['category_type'] == 2){
                                    $cutkey_str = $wordData['cut_pre'].$parent_str;
                                    if($wordData['name'] == '腹部' && $wordData['category_type'] == 2 && strpos($ocr_content_str,$wordData['name']) === false){
                                        $cutkey_str = '视诊'.$parent_str;
                                    }
                                    $ocr_content_str_arr = explode($cutkey_str,$ocr_content_arr[$data_category_type]);
                                    $ocr_content_arr[$data_category_type] = !empty($ocr_content_str_arr[1]) ? $ocr_content_str_arr[1] : $ocr_content_str;
                                }
                                foreach($delete_str_arr as $delete_str1){
                                    if(mb_substr($parent_str,0,1) === $delete_str1){
                                        $parent_str = ltrim($parent_str,$delete_str1);
                                    }
                                    if(mb_substr($parent_str,-1,1) === $delete_str1){
                                        $parent_str = rtrim($parent_str,$delete_str1);
                                    }
                                }
                                if($wordData['name'] == '腹部' && $wordData['category_type'] == 2 && strpos($ocr_content_str,$wordData['name']) === false){
                                    $parent_str = '视诊:'.$parent_str;
                                }
                                if($wordData['name'] == '入院日期' && $wordData['category_type'] == 1 && !empty($parent_str)){
                                    $parent_str = str_replace('-','',$parent_str);
                                    $parent_str = substr($parent_str,0,8);
                                }
                                //更新患者性别
                                if($wordData['name'] == '性别' && $wordData['category_type'] == 1 && !empty($parent_str)){
                                    if(empty($patient_sex)){
                                        if(strpos($parent_str,'男') !== false){
                                            $patient_sex = 1;
                                        }
                                        if(strpos($parent_str,'女') !== false){
                                            $patient_sex = 2;
                                        }
                                    }
                                }
                                $parent_data = [
                                    'id' => $wordData['id'],
                                    'name' => $wordData['name'],
                                    'category_id' => $wordData['category_id'],
                                    'result' => $parent_str
                                ];
                                $end_parent_str = (!empty($wordData['cut_pre'] || !empty($wordData['cut_after']))) && !empty($parent_str) ? $parent_str.$wordData['cut_after'] : '';

                            }
                            $child_data = [];
                            if(!empty($wordData['children'])) {
                                $child_cut_str = !empty($end_parent_str) ? $end_parent_str : $ocr_content_arr[$data_category_type];
                                foreach ($wordData['children'] as $childWordData) {
                                    if (strpos($child_cut_str, $childWordData['name']) !== false) {
                                        $child_cut_pre_str_arr = !empty($childWordData['cut_pre']) ? explode($childWordData['cut_pre'], $child_cut_str) : [];
                                        unset($child_cut_pre_str_arr[0]);
                                        $child_cut_pre_str = implode($childWordData['cut_pre'],$child_cut_pre_str_arr);
                                        $child_cut_after_str_arr = !empty($childWordData['cut_after']) && !empty($child_cut_pre_str) ? explode($childWordData['cut_after'], $child_cut_pre_str) : [];
                                        if($childWordData['name'] == '血液系统症状'  && $childWordData['category_type'] == 1 && count($child_cut_after_str_arr) == 1){
                                            $child_cut_after_str_arr = !empty($child_cut_pre_str) ? explode('内分泌代谢症状', $child_cut_pre_str) : [];
                                        }
                                        if(empty($child_cut_after_str_arr) && !empty($child_cut_pre_str)){
                                            $child_cut_after_str_arr = [$child_cut_pre_str];
                                        }
                                        $child_str = !empty($child_cut_after_str_arr) ? $child_cut_after_str_arr[0] : '';
                                        if(!empty($child_str) && $childWordData['category_type'] == 2){
                                            $child_keycut_str = $childWordData['cut_pre'].$child_str;
                                            $child_cut_str_arr = explode($child_keycut_str,$child_cut_str);
                                            $child_cut_str = !empty($child_cut_str_arr[1]) ? $child_cut_str_arr[1] : $child_cut_str;
                                        }
                                        foreach($delete_str_arr as $delete_str2){
                                            if(mb_substr($child_str,0,1) == $delete_str2){
                                                $child_str = ltrim($child_str,$delete_str2);
                                            }
                                            if(mb_substr($child_str,-1,1) == $delete_str2){
                                                $child_str = rtrim($child_str,$delete_str2);
                                            }
                                        }
                                        $childData_id = $childWordData['id'];
                                        $child_data[$childData_id] = [
                                            'id' => $childData_id,
                                            'name' => $childWordData['name'],
                                            'category_id' => $childWordData['category_id'],
                                            'result' => $child_str
                                        ];
                                    }
                                }
                            }
                            if(!empty($parent_data) || !empty($child_data)){
                                $wordData_id = $wordData['id'];
                                $all_content_arr[$data_category_type][$wordData_id] = [
                                    'id'=>$wordData_id,
                                    'name'=>$wordData['name'],
                                    'category_id'=>$wordData['category_id'],
                                    'result'=>isset($parent_data['result']) && !empty($parent_data['result']) ? $parent_data['result'] : '',
                                    'children'=>$child_data
                                ];
                                $num_arr[$data_category_type]++;
                                $mate_type = 1;
                            }
                        }
                    }
                    if($num_arr[3] > 0){
                        $category_type = 3;
                        $content_arr = isset($all_content_arr[3]) && !empty($all_content_arr[3]) ? $all_content_arr[3] : [];
                    }else{
                        if($num_arr[1] >= $num_arr[2]){
                            $category_type = 1;
                            $content_arr = isset($all_content_arr[1]) && !empty($all_content_arr[1]) ? $all_content_arr[1] : [];
                        }else{
                            $category_type = 2;
                            $content_arr = isset($all_content_arr[2]) && !empty($all_content_arr[2]) ? $all_content_arr[2] : [];
                        }
                    }
                }
                $up_data = [
                    'mate_type'=>$mate_type,
                    'category_type'=>$category_type,
                    'content'=>json_encode($content_arr,true),
                    'is_lock'=>0
                ];
                $this->update($up_data, 'id = ' . $info_id);
                if(!empty($patient_sex)){
                    $patient_sex_arr[$data_patient] = $patient_sex;
                    $this->LocalService()->tmpPatient->update(['sex'=>$patient_sex],['id'=>$data_patient]);
                }
                unset($datas[$dataKey]);
            }
        }
        unset($cond);
        unset($datas);

        return $last_id;
    }


    /**
     * Notes:识别入院记录数据 - 匹配
     * User: lltyy
     * DateTime: 2023/5/12 14:51
     *
     */
    public function scanData($where='',$select_type=0) {
        $sig_id_arr = [];
        //$sig_id_arr = [6959,6960,6963];
        //获取入院记录数据
        $wordDatas = [];
        if(in_array($select_type,[1])){
            $wordWhere = ['is_del'=>0,'category_type'=>[4,5,6]];
            if(!empty($sig_id_arr)){
                $wordWhere['sig_id'] = $sig_id_arr;
            }
            $wordDatas = $this->LocalService()->tmpHospital->fetchDataByKey($wordWhere,['id','sig_id','name','english','cut_pre','cut_after','cut_start','cut_length','category_type','category_id'],['sig_id','category_type','info_order'],'sig_id',1);
        }else{
            $wordDatas = $this->LocalService()->tmpHospital->fetchAllDataAndChild(['is_del'=>0,new NotIn('category_type',[4,5,6])],['id','pid','name','cut_pre','cut_after','category_type','category_id']);
        }

        //信息匹配
        if(empty($where)){
            $where = ['is_del'=>0,'is_lock'=>0];
        }

        if($select_type == 1){
            $where[] = new Operator('itemsig_id',Operator::OP_GT,2620);
        }

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


    /**
     * Notes: 获取指定条件下的数据
     * User: lltyy
     * DateTime: 2023/4/25 10:16
     *
     * @param $where
     * @param $where
     * @return array
     */
    public function fetchDataByKey($key,$is_more=0,$where,$columns){
        $datas = [];
        $cond = [
            'where'=>$where,
            'columns'=>$columns
        ];
        $infoDatas = $this->fetchAll($cond);
        if(!empty($infoDatas)){
            foreach($infoDatas as $infoData){
                $key_str = $infoData[$key];
                if($is_more == 1){
                    $datas[$key_str][] = $infoData;
                }else{
                    $datas[$key_str] = $infoData;
                }
            }
        }
        unset($cond);
        unset($infoDatas);
        return $datas;
    }

    /**
     * Notes: 将数据明细拆分存入新表
     * User: lltyy
     * DateTime: 2023/4/25 10:16
     *
     * @param $where
     * @return array
     */
    public function splitDetailData($where){
        if(empty($where)) {
            $where = ['is_del'=>0];
        }
        //$patient_id_arr = [6667,6668,6669,6677,6686,6688,6692,6700,6702,6728,6729,6730,6731,6732,6733,6734,6735,6736,6737,6739];
        //$patient_id_arr = [6740,6743,6744,6746,6747,6748,6749,6750,6751,6752,6753,6754,6755,6756,6757,6758,6759,6760,6761,6762];
        //$patient_id_arr = [6763,6764,6765,6766,6767,6768,6770,6772,6773,6775,6776,6777,6778,6779,6780,6781,6783,6784,6785,6786];
        //$patient_id_arr = [6787,6788,6789,6791,6792,6793,6794,6795,6796,6797,6798,6799,6800,6801,6804,6806,6807,6808,6809,6810];
        //$patient_id_arr = [6811,6812,6814,6815,6816,6817,6818,6819,6820,6821,6823,6824,6825,6826,6827,6828,6829,6830,6832,6833];
        //$patient_id_arr = [6834,6835,6836,6837,6838,6842,6865,6866,6867,6868,6869,6870,6871,6872,6873,6874,6875,6876,6877,6878];
        //$patient_id_arr = [6879,6880,6881,6882,6883,6884,6885,6886,6887,6888,6889,6890,6891,6892,6893,6894,6895,6896,6897,6898];
        //$patient_id_arr = [6899,6900,6901,6902,6903,6904,6905,6906,6907,6908,6909,6910,6911,6912,6913,6914,6915,6916,6917,6918];
        //$patient_id_arr = [6919,6920,6921,6922,6923,6924,6925,6926,6927,6928,6929,6930,6931,6932,6933,6934,6935,6936,6937,6938];
        //$patient_id_arr = [6939,6940,6941,6942,6943,6944,6945,6946,6947,6948,6949,6950,6951,6952,6953,6954,6955,6956,6957,6958];
        $patient_id_arr = [];
        if(!empty($patient_id_arr)){
            $where['patient_id'] = $patient_id_arr;
        }

        //获取指定条件下的识别结果数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','itemsig_id','patient_id','annex_id','category_type','content'],
            'order'=>['id ASC']
        ];
        $datas = $this->fetchAll($cond);
        if(!empty($datas)){
            $haveChildArr = $this->LocalService()->tmpHospital->fetchCol('pid',['is_del'=>0,new Operator('pid',Operator::OP_GT,0)]);
            $haveChildArr = array_values($haveChildArr);
            $haveChildArr = array_unique($haveChildArr);
            $haveChildArr = array_values($haveChildArr);
            foreach($datas as $key=>$data){
                $content_arr = json_decode($data['content'],true);
                if(!empty($content_arr)){
                    foreach($content_arr as $content_key=>$content){
                        $category_id = isset($content['category_id']) && !empty($content['category_id']) ? $content['category_id'] : 0;
                        $is_havechild = in_array($content_key,$haveChildArr) ? 1 : 0;
                        $insertSqlArr[] = '('.$data['id'].','.$data['itemsig_id'].','.$data['patient_id'].','.$data['annex_id'].','.$data['category_type'].','.$category_id.','.$content_key.',"'.$content['name'].'","'.$content['result'].'",0,'.$is_havechild.')';
                        if(isset($content['children']) && !empty($content['children'])){
                            foreach($content['children'] as $child_key=>$childContent){
                                $child_category_id = isset($childContent['category_id']) && !empty($childContent['category_id']) ? $childContent['category_id'] : 0;
                                $insertSqlArr[] = '('.$data['id'].','.$data['itemsig_id'].','.$data['patient_id'].','.$data['annex_id'].','.$data['category_type'].','.$child_category_id.','.$child_key.',"'.$childContent['name'].'","'.$childContent['result'].'",'.$content_key.',0)';
                                unset($content['children'][$child_key]);
                                unset($content_arr[$content_key]['children'][$child_key]);
                            }
                        }
                        unset($content_arr[$content_key]);
                    }
                }
                unset($content_arr);
                unset($datas[$key]);
            }
        }
        unset($datas);

        echo "共插入《".count($insertSqlArr)."》条数据！";
        echo "<br>";
        $insertSql = 'INSERT INTO `yikeen_tmp_patienthospital_detail` (`patienthospital_id`,`itemsig_id`,`patient_id`,`annex_id`,`category_type`,`category_id`,`hospital_id`,`hospital_name`,`hospital_result`,`parent_hospital_id`,`is_havechild`) VALUES ';
        if(!empty($insertSqlArr)){
            $insertSql .= implode(',',$insertSqlArr);
        }else{
            $insertSql = '';
        }
        echo $insertSql;
        exit;
    }
    
}