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

namespace Application\Service\DB\Tmp;

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

class Medical extends \Application\Service\DB\AbstractDb
{
    public function __construct($dbAdapter, ContainerInterface $container)
    {
        $this->tableName = 'yikeen_tmp_medical';
        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','sig_id','patient_id','annex_id','content'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->LocalService()->tmpTable->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,'table_id'=>$delete_mate_arr]);
            unset($delete_mate_arr);

            foreach ($datas as $dataKey=>$data) {
                $save_data = [
                    'table_id'=>$data['id'],
                    'itemsig_id'=>$data['sig_id'],
                    'patient_id'=>$data['patient_id'],
                    'annex_id'=>$data['annex_id'],
                    'is_lock'=>0,
                    'mate_type'=>0,
                ];
                $content_arr = [];
                $ocr_content_datas = json_decode($data['content'],true);
                if(!empty($ocr_content_datas)){
                    foreach($ocr_content_datas as $ocr_content_data_key=>$ocr_content_arr){
                        foreach($ocr_content_arr as $ocr_content_key=>$ocr_content){
                            if(isset($ocr_content[0]) && strpos($ocr_content[0],'日期') === false  && strpos($ocr_content[0],'时间') === false && strpos($ocr_content[0],'开始') === false){
                                $content_arr[] = [
                                    'ocr_start_date'=>isset($ocr_content[0]) && $ocr_content[0] != '' ? $ocr_content[0] : '',
                                    'ocr_end_date'=>isset($ocr_content[5]) && $ocr_content[5] != '' ? $ocr_content[5] : '',
                                    'medical_name'=>isset($ocr_content[2]) && $ocr_content[2] != '' ? $ocr_content[2] : ''
                                ];
                            }
                            unset($ocr_content_arr[$ocr_content_key]);
                        }
                    }
                }
                unset($ocr_content_arr);

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

        return $last_id;
    }

    /**
     * Notes:医嘱 - 信息【调用此方法时修改表名为：yikeen_tmp_medical】
     * User: lltyy
     * DateTime: 2023/6/6 8:52
     *
     */
    public function scanData($where=[]) {
        //信息匹配
        if(empty($where)){
            $where = ['is_del'=>0,'annex_type'=>89230];
        }

        $sig_id_arr = [];
        if(!empty($sig_id_arr)){
            $where['sig_id'] = $sig_id_arr;
        }
        $bool = true;
        $page = 0;
        $limit = 100;
        $last_id = 0;
        while ($bool) {
            $page++;
            echo "medicalPAGE {$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);
    }

    /**
     * 删除含"1盒"字样信息【调用此方法时修改表名为：yikeen_tmp_medical_alldrug】
     * 同一患者、同一药物 既含“自备”，又含“1盒”，把 只含“1盒”字样的 数据删除
     * 同一患者、同一药物 既含“自备”，又含“1瓶”，把 只含“1瓶”字样的 数据删除
     */
    public function deleteOneData(){
        $cond = [
            'where'=>[
                'is_del'=>0,
                'info_type'=>1,
                'or'=>[
                    new Like('medical_name',"%1瓶%"),
                    new Like('medical_name',"%1盒%"),
                    new Like('medical_name',"%自备%"),
                ]
            ],
            //'is_del = 0 and info_type = 1 and (medical_name like "%1瓶%" or medical_name like "%1盒%" or medical_name like "%自备%")',
            'columns'=>['id','info_id','medical_name','patient_id','drug_id'],
            'order'=>['id']
        ];
        $datas = $this->fetchAll($cond);
        unset($cond);
        $arr = [];
        if(!empty($datas)){
            foreach($datas as $key=>$data){
                $patient_id = $data['patient_id'];
                $drug_id = $data['drug_id'];
                $arr_key = $patient_id.'_'.$drug_id;
                //含“自备”字样的数据
                if(strpos($data['medical_name'],'自备') !== false){
                    $arr[$arr_key]['need'][] = $data['id'];
                }
                //含“1盒” 或 “1瓶”字样的数据
                if(strpos($data['medical_name'],'自备') === false && (strpos($data['medical_name'],'1盒') !== false || strpos($data['medical_name'],'1瓶') !== false)){
                    $arr[$arr_key]['one'][] = $data['id'];
                    $arr[$arr_key]['info'][] = $data['info_id'];
                }
                unset($datas[$key]);
            }
        }
        unset($datas);
        $delete_arr = $delete_info_arr = [];
        if(!empty($arr)){
            foreach($arr as $arrKey=>$arrInfo){
                $need_arr = isset($arrInfo['need']) && !empty($arrInfo['need']) ? $arrInfo['need'] : [];
                $one_arr = isset($arrInfo['one']) && !empty($arrInfo['one']) ? $arrInfo['one'] : [];
                $info_arr = isset($arrInfo['info']) && !empty($arrInfo['info']) ? $arrInfo['info'] : [];
                if(!empty($need_arr) && !empty($one_arr)){
                    $delete_arr = array_merge($delete_arr,$one_arr);
                    $delete_info_arr = array_merge($delete_info_arr,$info_arr);
                }
                unset($arr[$arrKey]);
            }
        }
        unset($arr);
        $sql = [];
        if(!empty($delete_arr)){
            $sql[] = "UPDATE `yikeen_tmp_medical_alldrug` SET `is_del` = 11,`update_user_id` = 788,`update_time` = 1706232480 WHERE `id` in (".implode(',',$delete_arr).")";
        }
        if(!empty($delete_info_arr)){
            $sql[] = "UPDATE `yikeen_tmp_medical` SET `is_del` = 11,`update_user_id` = 788,`update_time` = 1706232480 WHERE `id` in (".implode(',',$delete_info_arr).")";
        }
        //echo "<pre>";
        //print_R($arr);exit;
        $insertSql = '';
        if(!empty($sql)){
            $insertSql = implode(';',$sql);
        }
        echo "共插入《".count($sql)."》条数据！<br>";
        echo $insertSql;exit;
    }

    /**
     * 患者用药去重【调用此方法时修改表名为：yikeen_tmp_medical_alldrug】
     */
    public function scanPatientDrugData(){
        $arr = [];
        //获取患者所有用药数据
        $cond = [
            'where'=>['is_del'=>0,'info_type'=>1],
            'columns'=>['id','patient_id','patient_name','annex_name','drug_id','mate_drug','dosage_unit','medical_date','end_date','medical_type','dosage_num','mate_unit','mate_times','mate_way'],
            'order'=>['patient_id','info_type','medical_date','annex_name','end_date desc']
        ];
        $datas = $this->fetchAll($cond);
        unset($cond);
        if(!empty($datas)){
            $have_long_key = [];
            foreach($datas as $key=>&$data){
                $data_id = $data['id'];
                $data_patient = $data['patient_id'];
                $data_drug = $data['drug_id'];
                $data_num_unit = $data['dosage_num'].'【'.$data['mate_unit'].'】';
                $data_start = !empty($data['medical_date']) ? $data['medical_date'] : '';
                $data_end = !empty($data['end_date']) ? $data['end_date'] : '';
                if($data_end == ''){
                    $data_end = $data_start;
                }

                //判断患者用药最早日期
                $start_date = isset($arr[$data_patient]) && isset($arr[$data_patient][$data_drug]) && isset($arr[$data_patient][$data_drug]['start_date']) && !empty($arr[$data_patient][$data_drug]['start_date']) ? $arr[$data_patient][$data_drug]['start_date'] : '';
                if($data_start != '' && ((intval($data_start) < intval($start_date) && $start_date != '') || $start_date == '')){
                    $arr[$data_patient][$data_drug] = [
                        'patient_name'=>$data['patient_name'],
                        'mate_drug'=>$data['mate_drug'],
                        'start_date'=>$data_start,
                        'start_id'=>$data_id,
                        'start_num'=>$data_num_unit,
                    ];
                }

                //判断患者用药最晚日期
                $end_date = isset($arr[$data_patient]) && isset($arr[$data_patient][$data_drug]) && isset($arr[$data_patient][$data_drug]['end_date']) && !empty($arr[$data_patient][$data_drug]['end_date']) ? $arr[$data_patient][$data_drug]['end_date'] : '';
                if($data_end != '' && ((intval($data_end) > intval($end_date) && $end_date != '') || $end_date == '')){
                    $arr[$data_patient][$data_drug]['end_date'] = $data_end;
                    $arr[$data_patient][$data_drug]['end_id'] = $data_id;
                }

                if($data['medical_type'] == 2){
                    $data['dosage_num'] = !empty($data['dosage_num']) ? $data['dosage_num'] : 0;
                    $data['dosage_unit'] = !empty($data['dosage_unit']) ? $data['dosage_unit'] : 0;
                    $long_key_str = $data_start.'_'.$data_end.'_'.$data['dosage_num'].'_'.$data['dosage_unit'];
                    $arr[$data_patient][$data_drug]['long_info'][$long_key_str]['num_unit'] = $data_num_unit;
                    $arr[$data_patient][$data_drug]['long_info'][$long_key_str]['annex_name'][] = $data['annex_name'];
                    $arr[$data_patient][$data_drug]['long_info'][$long_key_str]['mate_ways'][] = $data['mate_way'];
                    $arr[$data_patient][$data_drug]['long_info'][$long_key_str]['mate_times'][] = $data['mate_times'];
                }
                unset($datas[$key]);
            }
            unset($have_long_key);
        }
        unset($datas);

        $sql = [];
        if(!empty($arr)){
            foreach($arr as $arrPatient=>$arrInfos){
                foreach($arrInfos as $arrDrug=>$arrInfo){
                    $long_info_arr = isset($arrInfo['long_info']) && !empty($arrInfo['long_info']) ? $arrInfo['long_info'] : [];
                    $new_arr = [];
                    $is_true = 0;
                    if(!empty($long_info_arr)){
                        $all_num_unit = [];
                        if(count($long_info_arr) > 1){
                            $is_true = 3;
                        }else{
                            $is_true = 2;
                        }
                        foreach($long_info_arr as $long_info_key=>$long_info){
                            $long_info_str = explode('_',$long_info_key);
                            //附件
                            $long_info_annex_name = array_unique($long_info['annex_name']);
                            $long_info_annex_name = array_values($long_info_annex_name);
                            //服用频率
                            $long_info_times = array_unique($long_info['mate_times']);
                            $long_info_times = array_values($long_info_times);
                            //服用方式
                            $long_info_ways = array_unique($long_info['mate_ways']);
                            $long_info_ways = array_values($long_info_ways);
                            $new_arr[] = $long_info_str[0].'--'.$long_info_str[1].'_'.$long_info['num_unit'].'（'.implode('，',$long_info_annex_name).'）['.implode('，',$long_info_times).']<'.implode('，',$long_info_ways).'>';
                            if(!in_array($long_info['num_unit'],$all_num_unit)){
                                $all_num_unit[] = $long_info['num_unit'];
                            }
                            unset($long_info_arr[$long_info_key]);
                        }
                        if(count($all_num_unit) != 1){
                            $is_true = 0;
                        }
                    }else{
                        $is_true = 1;
                    }
                    unset($long_info_arr);
                    $patient_name = isset($arrInfo['patient_name']) && !empty($arrInfo['patient_name']) ? $arrInfo['patient_name'] : '';
                    $mate_drug = isset($arrInfo['mate_drug']) && !empty($arrInfo['mate_drug']) ? $arrInfo['mate_drug'] : '';
                    $start_date = isset($arrInfo['start_date']) && !empty($arrInfo['start_date']) ? $arrInfo['start_date'] : '';
                    $start_id = isset($arrInfo['start_id']) && !empty($arrInfo['start_id']) ? $arrInfo['start_id'] : 0;
                    $start_num = isset($arrInfo['start_num']) && !empty($arrInfo['start_num']) ? $arrInfo['start_num'] : '';
                    $end_date = isset($arrInfo['end_date']) && !empty($arrInfo['end_date']) ? $arrInfo['end_date'] : '';
                    $end_id = isset($arrInfo['end_id']) && !empty($arrInfo['end_id']) ? $arrInfo['end_id'] : 0;
                    $long_info = !empty($new_arr) ? implode('、',$new_arr) : '';

                    $sql[] = "(1,2620,".$arrPatient.",'".$patient_name."',".$arrDrug.",'".$mate_drug."','".$start_date."',".$start_id.",'".$start_num."','".$end_date."',".$end_id.",'".$long_info."',".$is_true.")";

                    unset($arrInfos[$arrDrug]);
                    unset($arr[$arrPatient][$arrDrug]);
                }
                unset($arr[$arrPatient]);
            }
        }
        unset($arr);

        $insertSql = '';
        if(!empty($sql)){
            $insertSql = 'INSERT INTO `yikeen_tmp_medical_alldrug_info` (`info_type`,`itemsig_id`,`patient_id`,`patient_name`,`drug_id`,`mate_drug`,`medical_date`,`start_id`,`start_num`,`end_date`,`end_id`,`long_info`,`is_true`) VALUES '.implode(',',$sql);
        }
        echo "共插入《".count($sql)."》条数据！<br>";
        echo $insertSql;exit;
        return $arr;
    }

    /**
     * 患者长遗嘱用药排序整理【调用此方法时修改表名为：yikeen_tmp_medical_alldrug_info】
     * 1、先按照 开始日期、结束日期排序
     *      1》分段的排序，开始日期早的放前面，开始日期晚的放后面，结束日期早的放前面，结束日期晚的放后面：两个分别日期为A1-A2剂量a；B1-B2剂量b
     *      2》排在前面的剂量a对应的日期为A1到B1日期的，排在后面剂量b对应的日期为B1到结束。
     */
    public function sortData(){
        $sql = [];
        $insertSql = '';
        //获取患者所有用药数据
        $cond = [
            'where'=>[
                'is_del'=>0,
                'info_type'=>1,
                new IsNotNull('long_info'),
                new Operator('long_info',Operator::OP_NE,"")
            ],
            'columns'=>['id','itemsig_id','patient_id','patient_name','drug_id','mate_drug','medical_date','end_date','long_info'],
            'order'=>['id']
        ];
        $datas = $this->fetchAll($cond);
        unset($cond);
        if(!empty($datas)){
            foreach($datas as $key=>$data){
                $long_info_arr = explode('、',$data['long_info']);
                foreach($long_info_arr as $long_key=>$long_info){
                    $long_infos = explode('_',$long_info);
                    $num_unit_annex_arr = explode('（',$long_infos[1]);
                    $num_unit = $num_unit_annex_arr[0];
                    $num_unit_arr = explode('【',$num_unit);
                    $data_num = $num_unit_arr[0];
                    $data_unit = trim($num_unit_arr[1],'】');
                    $annex_name_time_way_arr = explode('[',$num_unit_annex_arr[1]);
                    $annex_name = trim($annex_name_time_way_arr[0],'）');
                    $times_ways_arr = explode('<',$annex_name_time_way_arr[1]);
                    $mate_times = trim($times_ways_arr[0],']');
                    $mate_ways = trim($times_ways_arr[1],'>');
                    $date_arr = explode('--',$long_infos[0]);
                    $start_int = intval($date_arr[0]);
                    $end_int = intval($date_arr[1]);
                    $sql[] = "(2,".$data['id'].",".$data['itemsig_id'].",".$data['patient_id'].",'".$data['patient_name']."',".$data['drug_id'].",'".$data['mate_drug']."','".$data['medical_date']."','".$data['end_date']."',".$start_int.",".$end_int.",'".$num_unit."','".$data_num."','".$data_unit."','".$annex_name."','".$mate_times."','".$mate_ways."')";
                    unset($long_info_arr[$long_key]);
                }
                unset($long_info_arr);
                unset($datas[$key]);
            }
        }
        unset($datas);

        if(!empty($sql)){
            $insertSql = 'INSERT INTO `yikeen_tmp_medical_alldrug_infodetail` (`data_type`,`info_id`,`itemsig_id`,`patient_id`,`patient_name`,`drug_id`,`drug_name`,`first_start`,`first_end`,`start_date`,`end_date`,`num_unit`,`data_num`,`data_unit`,`annex_names`,`mate_times`,`mate_ways`) VALUES '.implode(',',$sql);
        }
        echo "共插入《".count($sql)."》条数据！<br>";
        echo $insertSql;exit;
        return $arr;
    }

    /**
     * 患者长遗嘱用药排序整理【调用此方法时修改表名为：yikeen_tmp_medical_alldrug_infodetail】
     * 多长嘱融合
     *      1》1-2两段是剂量一致的，且日期有衔接，则融为一段【1-2一致，那么就就取1和2的最小值为起点，最大为终点】
     *      2》2-3两段是剂量一致的，且日期有衔接，则融为一段【2-3一致，那么就就取2和3的最小值为起点，最大为终点】
     *      3》1和3一致，则不融为一段
     */
    public function mergeData(){
        $sql = [];
        $insertSql = '';
        $cond = [
            'where'=>['is_del'=>0,'data_type'=>2],
            'columns'=>['info_id','start_date','end_date','num_unit','annex_names','mate_times','mate_ways'],
            'order'=>['info_id','start_date','end_date','num_unit']
        ];
        $datas = $this->fetchAll($cond);
        unset($cond);
        $infoLongArr = [];
        if(!empty($datas)){
            foreach($datas as $key=>$data){
                $data_info = $data['info_id'];
                $infoLongArr[$data_info][] = $data['start_date'].'--'.$data['end_date'].'_'.$data['num_unit'].'（'.$data['annex_names'].'）['.$data['mate_times'].']<'.$data['mate_ways'].'>';
                unset($datas[$key]);
            }
        }
        unset($datas);
        if(!empty($infoLongArr)){
            foreach($infoLongArr as $infoId=>$infoLongs){
                //更新排序
                $sql[] = "UPDATE `yikeen_tmp_medical_alldrug_info` SET `long_info` = '".implode('、',$infoLongs)."' WHERE `id` = ".$infoId;

                //长遗嘱融合
                $merage_long_arr = [];
                $key = 0;
                foreach($infoLongs as $infoLongKey=>$infoLong){
                    $long_infos = explode('_',$infoLong);
                    $num_unit_annex_arr = explode('（',$long_infos[1]);
                    $num_unit = $num_unit_annex_arr[0];
                    $annex_name_time_way_arr = explode('[',$num_unit_annex_arr[1]);
                    $annex_name = trim($annex_name_time_way_arr[0],'）');
                    $times_ways_arr = explode('<',$annex_name_time_way_arr[1]);
                    $mate_times = trim($times_ways_arr[0],']');
                    $mate_ways = trim($times_ways_arr[1],'>');
                    $date_arr = explode('--',$long_infos[0]);
                    $start_int = intval($date_arr[0]);
                    $end_int = intval($date_arr[1]);
                    if($infoLongKey == 0){
                        $merage_long_arr[$key] = [
                            'start_date'=>$start_int,
                            'end_date'=>$end_int,
                            'num_unit'=>$num_unit,
                            'annex_names'=>$annex_name,
                            'mate_times'=>$mate_times,
                            'mate_ways'=>$mate_ways
                        ];
                        $key++;
                    }else{
                        $pre_key = $key-1;
                        $is_merge = 0;
                        if($num_unit == $merage_long_arr[$pre_key]['num_unit']){
                            if($start_int == $merage_long_arr[$pre_key]['start_date']){
                                $is_merge = 1;
                            }elseif($start_int > $merage_long_arr[$pre_key]['start_date']){
                                if($start_int <= $merage_long_arr[$pre_key]['end_date']){
                                    $is_merge = 1;
                                }else{
                                    $now_start_date = substr($start_int,0,4).'-'.substr($start_int,4,2).'-'.substr($start_int,6,2).' 00:00:00';
                                    $pre_end_date = substr($merage_long_arr[$pre_key]['end_date'],0,4).'-'.substr($merage_long_arr[$pre_key]['end_date'],4,2).'-'.substr($merage_long_arr[$pre_key]['end_date'],6,2).' 00:00:00';
                                    $cha_day = (strtotime($now_start_date)-strtotime($pre_end_date))/(24*60*60);
                                    if($cha_day <= 1){
                                        $is_merge = 1;
                                    }
                                }
                            }
                        }
                        if($is_merge == 1){
                            $merage_long_arr[$pre_key]['annex_names'] .= '，'.$annex_name;
                            $merage_long_arr[$pre_key]['mate_times'] .= '，'.$mate_times;
                            $merage_long_arr[$pre_key]['mate_ways'] .= '，'.$mate_ways;
                            if($merage_long_arr[$pre_key]['end_date'] < $end_int){
                                $merage_long_arr[$pre_key]['end_date'] = $end_int;
                            }
                        }else{
                            $merage_long_arr[$key] = [
                                'start_date'=>$start_int,
                                'end_date'=>$end_int,
                                'num_unit'=>$num_unit,
                                'annex_names'=>$annex_name,
                                'mate_times'=>$mate_times,
                                'mate_ways'=>$mate_ways
                            ];
                            $key++;
                        }

                    }
                }
                unset($key);

                $new_long_arr = [];
                foreach($merage_long_arr as $merage_long_key=>$merage_long){
                    //附件去重
                    $annex_names_arr = explode('，',$merage_long['annex_names']);
                    $annex_names_arr = array_unique($annex_names_arr);
                    $annex_names_arr = array_values($annex_names_arr);
                    //服用频次去重
                    $mate_times_arr = explode('，',$merage_long['mate_times']);
                    $mate_times_arr = array_unique($mate_times_arr);
                    $mate_times_arr = array_values($mate_times_arr);
                    //服用方式去重
                    $mate_ways_arr = explode('，',$merage_long['mate_ways']);
                    $mate_ways_arr = array_unique($mate_ways_arr);
                    $mate_ways_arr = array_values($mate_ways_arr);
                    $new_long_arr[] = $merage_long['start_date'].'--'.$merage_long['end_date'].'_'.$merage_long['num_unit'].'（'.implode('，',$annex_names_arr).'）['.implode('，',$mate_times_arr).']<'.implode('，',$mate_ways_arr).'>';
                    unset($merage_long_arr[$merage_long_key]);
                }
                unset($merage_long_arr);
                $sql[] = "UPDATE `yikeen_tmp_medical_alldrug_info` SET `merge_info` = '".implode('、',$new_long_arr)."' WHERE `id` = ".$infoId;
                unset($infoLongArr[$infoId]);
            }
        }
        unset($infoLongArr);
        if(!empty($sql)){
            $insertSql = implode(';',$sql);
        }
        echo "共插入《".count($sql)."》条数据！<br>";
        echo $insertSql;exit;
        return $arr;
    }

    /**
     * 拆分患者长遗嘱用药【调用此方法时修改表名为：yikeen_tmp_medical_alldrug_info】
     */
    public function splitData(){
        $sql = [];
        $insertSql = '';
        $cond = [
            'where'=>[
                'is_del'=>0,
                'info_type'=>1,
                new IsNotNull('merge_info'),
                new Operator('merge_info',Operator::OP_NE,"")
            ],
            'columns'=>['id','itemsig_id','patient_id','patient_name','drug_id','mate_drug','medical_date','end_date','merge_info'],
            'order'=>['id']
        ];
        $datas = $this->fetchAll($cond);
        unset($cond);
        if(!empty($datas)){
            foreach($datas as $key=>$data){
                $long_info_arr = explode('、',$data['merge_info']);
                foreach($long_info_arr as $long_key=>$long_info){
                    $long_infos = explode('_',$long_info);
                    $num_unit_annex_arr = explode('（',$long_infos[1]);
                    $num_unit = $num_unit_annex_arr[0];
                    $num_unit_arr = explode('【',$num_unit);
                    $data_num = $num_unit_arr[0];
                    $data_unit = trim($num_unit_arr[1],'】');
                    $annex_name_time_way_arr = explode('[',$num_unit_annex_arr[1]);
                    $annex_name = trim($annex_name_time_way_arr[0],'）');
                    $times_ways_arr = explode('<',$annex_name_time_way_arr[1]);
                    $mate_times = trim($times_ways_arr[0],']');
                    $mate_ways = trim($times_ways_arr[1],'>');
                    $date_arr = explode('--',$long_infos[0]);
                    $start_int = intval($date_arr[0]);
                    $end_int = intval($date_arr[1]);
                    $sql[] = "(1,".$data['id'].",".$data['itemsig_id'].",".$data['patient_id'].",'".$data['patient_name']."',".$data['drug_id'].",'".$data['mate_drug']."','".$data['medical_date']."','".$data['end_date']."',".$start_int.",".$end_int.",'".$num_unit."','".$data_num."','".$data_unit."','".$annex_name."','".$mate_times."','".$mate_ways."')";
                    unset($long_info_arr[$long_key]);
                }
                unset($long_info_arr);
                unset($datas[$key]);
            }
        }
        unset($datas);
        if(!empty($sql)){
            $insertSql = 'INSERT INTO `yikeen_tmp_medical_alldrug_infodetail` (`data_type`,`info_id`,`itemsig_id`,`patient_id`,`patient_name`,`drug_id`,`drug_name`,`first_start`,`first_end`,`start_date`,`end_date`,`num_unit`,`data_num`,`data_unit`,`annex_names`,`mate_times`,`mate_ways`) VALUES '.implode(',',$sql);
        }
        echo "共插入《".count($sql)."》条数据！<br>";
        echo $insertSql;
        exit;

    }

    /**
     * 合并出院用药数据【调用此方法时修改表名为：yikeen_tmp_medical_alldrug_infodetail】
     * 如果长嘱结束日期与出院日期一致，且剂量单位一致，则融合，长嘱标识为研究结束仍在使用，导出时结束日期清空
     * INSERT INTO `yikeen_tmp_medical_alldrug_infodetail` (`data_type`,`info_id`,`itemsig_id`,`patient_id`,`patient_name`,`drug_id`,`drug_name`,`start_date`,`data_num`,`data_unit`,`num_unit`,`annex_names`,`mate_times`,`mate_ways`,`is_dispensary`) SELECT `info_type`,`id`,`itemsig_id`,`patient_id`,`patient_name`,`drug_id`,`mate_drug`,`medical_date`,`dosage_num`,`mate_unit`,CONCAT(`dosage_num`,'【',`mate_unit`,'】'),`annex_name`,`mate_times`,`mate_way`,`is_dispensary` FROM `yikeen_tmp_medical_alldrug` where `yikeen_tmp_medical_alldrug`.`info_type` = 3 and `yikeen_tmp_medical_alldrug`.`is_del` = 0;
     * UPDATE `yikeen_tmp_medical_alldrug_infodetail` SET `end_date` = `start_date` where `data_type` = 3
     */
    public function mergeOutData(){
        $sql = [];
        $insertSql = '';
        $cond = [
            'where'=>['is_del'=>0,'data_type'=>[1,3]],
            'columns'=>['id','info_id','patient_id','drug_id','start_date','end_date','num_unit','annex_names','mate_times','mate_ways','data_type'],
            'order'=>['data_type desc','start_date','end_date']
        ];
        $datas = $this->fetchAll($cond);
        unset($cond);
        $outDatas = $longDatas = [];
        if(!empty($datas)){
            foreach($datas as $key=>$data){
                if($data['data_type'] == 3){
                    $out_data_key = $data['patient_id'].'_'.$data['drug_id'].'_'.$data['start_date'].'_'.$data['num_unit'];
                    $outDatas[$out_data_key]['out_id'][] = $data['info_id'];
                    if(isset($outDatas[$out_data_key]) && isset($outDatas[$out_data_key]['out_annex_name']) && !empty($outDatas[$out_data_key]['out_annex_name'])){
                        $outDatas[$out_data_key]['out_annex_name'] .= '，'.$data['annex_names'];
                    }else{
                        $outDatas[$out_data_key]['out_annex_name'] = $data['annex_names'];
                    }
                    if(isset($outDatas[$out_data_key]) && isset($outDatas[$out_data_key]['out_times']) && !empty($outDatas[$out_data_key]['out_times'])){
                        $outDatas[$out_data_key]['out_times'] .= '，'.$data['mate_times'];
                    }else{
                        $outDatas[$out_data_key]['out_times'] = $data['mate_times'];
                    }
                    if(isset($outDatas[$out_data_key]) && isset($outDatas[$out_data_key]['out_ways']) && !empty($outDatas[$out_data_key]['out_ways'])){
                        $outDatas[$out_data_key]['out_ways'] .= '，'.$data['mate_ways'];
                    }else{
                        $outDatas[$out_data_key]['out_ways'] = $data['mate_ways'];
                    }
                    $outDatas[$out_data_key]['id'][] = $data['id'];
                }else{
                    $data_key = $data['patient_id'].'_'.$data['drug_id'].'_'.$data['end_date'].'_'.$data['num_unit'];
                    $longDatas[$data_key] = $data['id'];
                }
                unset($datas[$key]);
            }
        }
        unset($datas);
       if(!empty($longDatas)){
           foreach($longDatas as $longKey=>$longDataId){
               $long_out_data = isset($outDatas[$longKey]) && !empty($outDatas[$longKey]) ? $outDatas[$longKey] : [];
               if(!empty($long_out_data)){
                    //附件去重
                    $annex_names_arr = explode('，',$long_out_data['out_annex_name']);
                    $annex_names_arr = array_unique($annex_names_arr);
                    $annex_names_arr = array_values($annex_names_arr);
                    //服用频次去重
                    $mate_times_arr = explode('，',$long_out_data['out_times']);
                    $mate_times_arr = array_unique($mate_times_arr);
                    $mate_times_arr = array_values($mate_times_arr);
                    //服用方式去重
                    $mate_ways_arr = explode('，',$long_out_data['out_ways']);
                    $mate_ways_arr = array_unique($mate_ways_arr);
                    $mate_ways_arr = array_values($mate_ways_arr);

                   $sql[] = "UPDATE `yikeen_tmp_medical_alldrug_infodetail` SET `is_dispensary` = 1,`out_ids` = '".implode(',',$long_out_data['out_id'])."',`out_annex_names` = '".implode('，',$annex_names_arr)."',`out_times` = '".implode('，',$mate_times_arr)."',`out_ways` = '".implode('，',$mate_ways_arr)."' WHERE `id` = ".$longDataId;
                   $sql[] = "UPDATE `yikeen_tmp_medical_alldrug_infodetail` SET `is_del` = 1 WHERE `id` in (".implode(',',$long_out_data['id']).")";
               }
               unset($longDatas[$longKey]);
           }
       }
        unset($longDatas);
        if(!empty($sql)){
            $insertSql = implode(';',$sql);
        }
        echo "共更新《".count($sql)."》条数据！<br>";
        echo $insertSql;exit;
    }


    /**
     * 获取患者所有临时医嘱用药【调用此方法时修改表名为：yikeen_tmp_medical_alldrug_infodetail】
     * 生成前先把临嘱插入【插入SQL如下】
     * INSERT INTO `yikeen_tmp_medical_alldrug_infodetail` (`info_id`,`itemsig_id`,`patient_id`,`patient_name`,`drug_id`,`drug_name`,`start_date`,`end_date`,`data_num`,`data_unit`,`num_unit`,`annex_names`,`mate_times`,`mate_ways`) SELECT `id`,`itemsig_id`,`patient_id`,`patient_name`,`drug_id`,`mate_drug`,`medical_date`,`end_date`,`dosage_num`,`mate_unit`,CONCAT(`dosage_num`,'【',`mate_unit`,'】'),`annex_name`,`mate_times`,`mate_way` FROM `yikeen_tmp_medical_alldrug` where `yikeen_tmp_medical_alldrug`.`info_type` = 1 and `yikeen_tmp_medical_alldrug`.`medical_type` = 1 and `yikeen_tmp_medical_alldrug`.`is_del` = 0;
     * UPDATE `yikeen_tmp_medical_alldrug_infodetail`,`yikeen_tmp_medical_alldrug_unique` SET `yikeen_tmp_medical_alldrug_infodetail`.`use_reason` = `yikeen_tmp_medical_alldrug_unique`.`other_info` WHERE `yikeen_tmp_medical_alldrug_infodetail`.`patient_id` = `yikeen_tmp_medical_alldrug_unique`.`patient_id` and `yikeen_tmp_medical_alldrug_infodetail`.`drug_id` = `yikeen_tmp_medical_alldrug_unique`.`drug_id`;
     */
    public function tmpData(){
        $cond = [
            'where'=>['is_del'=>0,'data_type'=>[0,1,3]],
            'columns'=>['id','patient_name','drug_name','start_date','end_date','data_num','data_unit','mate_times','mate_ways','out_times','out_ways','use_reason','is_dispensary','data_type'],
            'order'=>['patient_name','drug_name','start_date','end_date']
        ];
        $datas = $this->fetchAll($cond);
        unset($cond);
        $arr = [];
        if(!empty($datas)){
            foreach($datas as $key=>$data){
                $patient_id = $data['patient_name'];
                $drug_id = $data['drug_name'];
                $start_int = $data['start_date'];
                $end_int = $data['end_date'];
                $mate_times = $data['mate_times'];
                $mate_ways = $data['mate_ways'];
                $use_reason = $data['use_reason'];
                $is_dispensary = 0;
                if(($data['data_type'] == 1 && $data['is_dispensary'] == 1) || $data['data_type'] == 3){
                    $is_dispensary = 1;
                    if($data['data_type'] == 1 && $data['is_dispensary'] == 1){
                        $mate_times .= '，'.$data['out_times'];
                        $mate_ways .= '，'.$data['out_ways'];

                        //服用频次去重
                        $mate_times_arr = explode('，',$mate_times);
                        $mate_times_arr = array_unique($mate_times_arr);
                        $mate_times_arr = array_values($mate_times_arr);
                        $mate_times = implode('，',$mate_times_arr);

                        //服用方式去重
                        $mate_ways_arr = explode('，',$mate_ways);
                        $mate_ways_arr = array_unique($mate_ways_arr);
                        $mate_ways_arr = array_values($mate_ways_arr);
                        $mate_ways = implode('，',$mate_ways_arr);

                    }
                }
                $data_num = $data['data_num'];
                $data_unit = $data['data_unit'];
                $arr[$patient_id][$drug_id][] = [
                    'patient_name'=>$patient_id,
                    'drug_name'=>$drug_id,
                    'start_date'=>$start_int,
                    'end_date'=>$end_int,
                    'data_num'=>$data_num,
                    'data_unit'=>$data_unit,
                    'data_times'=>explode('，',$mate_times),//服用频次
                    'data_ways'=>explode('，',$mate_ways),//服用方式
                    'use_reason'=>$use_reason,//用药原因
                    'is_dispensary'=>$is_dispensary//研究结束是否仍在使用
                ];
                unset($datas[$key]);
            }
        }
        unset($datas);
        Factory::toFile(APP_PATH . '/public/data/arr.php', $arr);
        echo "<pre>";
        print_R($arr);exit;
    }

}