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

namespace Application\Service\DB\Collect;

use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Stdlib\ArrayUtils;

class Patienthospital extends \Application\Service\DB\AbstractDb
{
    public function __construct($dbAdapter, ContainerInterface $container)
    {
        $this->tableName = 'yikeen_collect_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=[]){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['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()->patient->fetchCol('patient_sex','is_del = 0 and pid > 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);
                    }
                }
                $ocr_content_arr = [
                    1=>$ocr_content_str,
                    2=>$ocr_content_str,
                    3=>$ocr_content_str
                ];
                $mate_type = 0;
                $category_type = 0;
                $content_arr = [];

                //判断是否为病史小结体格检查
                $all_content_arr = [];
                $num_arr = [
                    1=>0,
                    2=>0,
                    3=>0
                ];
                $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;
                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(!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()->patient->update(['patient_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='',$item_id=0) {
        //获取入院记录数据
        $wordDatas = $this->LocalService()->collectItemhospital->fetchAllDataAndChild([
            'is_del' => 0,
            'item_id' => $item_id,
        ],['id','pid','name','cut_pre','cut_after','category_type','category_id']);

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

        if(!empty($item_id)){
            $where['item_id'] = $item_id;
        }
        $sig_id_arr = [];
        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;
            $last_id = $this->mateData(ArrayUtils::merge($where, [
                new Operator('id', Operator::OP_GT, $last_id),
            ]),$limit,0,$wordDatas);
            if(!$last_id) $bool = false;
        }
        unset($wordDatas);
    }


    /**
     * 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,$item_id=0){
        if(empty($where)) {
            $where = [
                'is_del' => 0,
            ];
        }
        if(!empty($item_id)){
            $where['item_id'] = $item_id;
        }
        $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()->collectItemhospital->fetchCol('pid',[
                'is_del' => 0,
                'item_id' => $item_id,
                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_collect_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;
    }

}