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

namespace Application\Service\DB\Tmp;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\Operator;

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

    /**
     * Notes:识别医嘱数据 - 匹配
     * User: lltyy
     * DateTime: 2023/5/12 14:51
     *
     */
    public function scanMedical($where='') {
        //获取黑/白名单数据
        $wordDatas = $this->LocalService()->dictionaryMedicalword->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'] : [];
        $black_white_word_arr = isset($wordDatas['black_white_word']) && !empty($wordDatas['black_white_word']) ? $wordDatas['black_white_word'] : [];
        unset($wordDatas);

        //获取药物数据
        $drug = $this->LocalService()->dictionaryDrug->fetchAll(['where'=>['is_del'=>0],'columns'=>['id','name'],'order'=>['category_type','drug_order']]);

        $drugDatas = [];
        if(!empty($drug)){
            $delete_str_arr = ["↑","↓","#","！","~","*","☑","★","◆","。",".","(",")","（","）","?",":","：","√","？","^","<",">","|","、","《","》","，",",","{","}","[","]","【","】","+","--","=","～"];

            foreach($drug as  &$drugData){
                $mate_drug_name = $drugData['name'];

                $mate_drug_name = mb_substr($mate_drug_name,0,8);

                if(strpos($mate_drug_name,'(') !== false){
                    $delete_index = strpos($mate_drug_name,'(');
                    $mate_drug_name = substr_replace($mate_drug_name,'',$delete_index);
                    unset($delete_index);
                }
                if(strpos($mate_drug_name,'（') !== false){
                    $delete_index = strpos($mate_drug_name,'（');
                    $mate_drug_name = substr_replace($mate_drug_name,'',$delete_index);
                    unset($delete_index);
                }
                $mate_drug_name = str_replace($delete_str_arr,'',$mate_drug_name);

                $drugData['name'] = $mate_drug_name;

                $drugDatas[$drugData['name']] = $drugData;
            }
            unset($delete_str_arr,$drug);
        }


        //获取剂量单位数据
        $takeDatas = $this->LocalService()->dictionaryMedicaltake->fetchAll(['where'=>['is_del'=>0],'columns'=>['id','name','english','take_type','take_number'],'order'=>['take_order']]);


        if(empty($where)){
            $where = ['is_del'=>0,'is_lock'=>0];

        }

        $bool = true;
        $page = 0;
        $limit = 1000;
        $last_medical_id = 0;
        while ($bool) {
            $page++;
            echo "medicalPAGE {$page}：" . PHP_EOL;
            $mate_where = $where;
            $mate_where[] = new Operator('id',Operator::OP_GT,$last_medical_id);
            $last_medical_id = $this->mateWordData($mate_where,$limit,0,$white_word_arr,$black_word_arr,$black_white_word_arr,$drugDatas,$takeDatas);
            if(!$last_medical_id) $bool = false;
            unset($mate_where);
        }

        unset($white_word_arr);
        unset($black_word_arr);
        unset($black_white_word_arr);
        unset($drugDatas);
        unset($takeDatas);
    }


    /**
     * Notes:获取指定的医嘱名称数据 与 黑/白名单关键字匹配，存入匹配信息表
     * User: lltyy  COPY
     * DateTime: 2023/1/29
     *
     * @param $where//条件
     * @param int $limit
     * @param int $offset
     * @param $white_word_arr//白名单
     * @param array $black_word_arr//黑名单
     * @param array $black_white_word_arr//黑名单下白名单
     * @return int
     */
    public function mateWordData($where,$limit=0,$offset=0,&$white_word_arr,&$black_word_arr=[],&$black_white_word_arr=[],&$drug_arr=[],&$takeDatas=[]){
        //获取指定条件下的医嘱数据
        $medicalCond = [
            'where'=>$where,
            'columns'=>['id','annex_id','itemsig_id','patient_id','medical_name','ocr_start_date','ocr_end_date','medical_name_reduce'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $medicalCond['limit'] = $limit;
            $medicalCond['offset'] = $offset;
        }
        $medicalDatas = $this->LocalService()->TmpDoctoradviceoriginal->fetchAll($medicalCond);


        $last_medical_id = 0;
        if(!empty($medicalDatas)){
            if(!empty($medicalDatas)) {
                $delete_str_arr = ["↑","↓","#","！","~","*","☑","★","◆","。",".","(",")","（","）","?",":","：","√","？","^","<",">","|","、","《","》","，",",","{","}","[","]","【","】","+","--","=","～"];

                foreach ($medicalDatas as $medicalDataKey=>&$medicalData) {
                    //医嘱源数据ID
                    $medical_id = $medicalData['id'];
                    if($medical_id != 1631) continue;

                    //去除左右空格
                    $medical_name = trim($medicalData['medical_name']);

                    //识别时间拼接医嘱名称
                    $mate_medical_name = trim($medicalData['ocr_start_date']).$medical_name;

                    //字符串替换
                    $mate_medical_name = str_replace($delete_str_arr,'',$mate_medical_name);

                    $medicalData['mate_medical_name'] = $mate_medical_name;

                    $mate_type = 0;
                    //已匹配上白名单的词
                    $white_word = [];
                    if(!empty($white_word_arr)){
                        foreach($white_word_arr as $white_word_str){
                            if(strpos($mate_medical_name,$white_word_str) !== false){
                                $white_word[] = $white_word_str;
                            }
                        }
                    }

                    if (!empty($white_word)) {

                        //保存匹配白名单数据
                        $save_data = [
                            'annex_id' => $medicalData['annex_id'],
                            'itemsig_id' => $medicalData['itemsig_id'],
                            'patient_id' => $medicalData['patient_id'],
                            'medical_id' => $medical_id,
                            'medical_name' => $medical_name,
                            'white_word' => json_encode($white_word_arr),
                            'mate_white' => json_encode($white_word)
                        ];
                        $matewhite_id = $this->save($save_data);
                        unset($save_data);

                        //已匹配上黑名单的词
                        $black_word = [];
                        if(!empty($black_word_arr)){
                            foreach($black_word_arr as $black_word_str){
                                if(strpos($mate_medical_name,$black_word_str) !== false){
                                    $black_word[] = $black_word_str;
                                }
                            }
                        }

                        if (!empty($black_word)) {
                            //已匹配上黑名单下的白名单词
                            $black_white_word = [];
                            if(!empty($black_white_word_arr)){
                                foreach($black_white_word_arr as $black_white_word_str){
                                    if(strpos($mate_medical_name,$black_white_word_str) !== false){
                                        $black_white_word[] = $black_white_word_str;
                                    }
                                }
                            }
                            if (empty($black_white_word)) {
                                $mate_type = 2;
                                //保存匹配白名单与黑名单匹配数据
                                $save_black = [
                                    'annex_id' => $medicalData['annex_id'],
                                    'itemsig_id' => $medicalData['itemsig_id'],
                                    'patient_id' => $medicalData['patient_id'],
                                    'medical_id' => $medical_id,
                                    'white_id' => $matewhite_id,
                                    'medical_name' => $medical_name,
                                    'black_word' => json_encode($black_word_arr),
                                    'mate_black' => json_encode($black_word)
                                ];
                                $this->LocalService()->tmpDoctoradvicemateblack->save($save_black);
                                unset($save_black);
                            } else {
                                $mate_type = 1;
                            }
                            unset($black_white_word);
                        } else {
                            $mate_type = 1;
                        }
                        unset($black_word);
                    }
                    unset($white_word);
                    unset($medical_name_arr);

                    //更新日期
                    $medical_date = trim($medicalData['ocr_start_date']);

                    $medical_date = $this->LocalService()->ocrRawdata->replaceRawdata($medical_date,1);

                    $medical_date = $medical_date != '' ? $medical_date : '';
                    //更新日期
                    $end_date = trim($medicalData['ocr_end_date']);
                    $end_date = $this->LocalService()->ocrRawdata->replaceRawdata($end_date,1);
                    $end_date = $end_date != '' ? $end_date : '';

                    //获取匹配的药物名称

                    $drug_id = 0;
                    $dosage_id = $dosage_unit = $dosage_way = $dosage_times = $is_dispensary = $take_number = $dosage_medication = 0;

                    if($mate_type == 1){
//var_dump($medicalData);die;
                        $drug_id = $this->LocalService()->tmpDoctoradvicematedrug->mateDrugdata($medicalData,$drug_arr);

                        //如果符合白名单并且没有匹配上药物则默认未匹配
//                        if(!$drug_id && $mate_type == 1) $mate_type = 0;
                        if(!empty($takeDatas)){

                            foreach($takeDatas as $takeDataType=>$takeData){

                                $takeData_id = $takeData['id'];
                                $takeData_name = $takeData['name'];
                                $takeData_english = $takeData['english'];
                                $takeData_type = $takeData['take_type'];

                                //规格
                                if($takeData_type == 1){
                                    if(empty($dosage_id) && strpos($medical_name,$takeData_name) !== false){
                                        $dosage_id = $takeData_id;
                                        continue;
                                    }
                                    if(empty($dosage_id) && !empty($takeData_english) && strpos($medical_name,$takeData_english) !== false){
                                        $dosage_id = $takeData_id;
                                        continue;
                                    }
                                }

                                //剂量单位
                                if($takeData_type == 2){
                                    if(empty($dosage_unit) && strpos($medical_name,$takeData_name) !== false){
                                        $dosage_unit = $takeData_id;
                                        continue;
                                    }
                                    if(empty($dosage_unit) && !empty($takeData_english) && strpos($medical_name,$takeData_english) !== false){
                                        $dosage_unit = $takeData_id;
                                        continue;
                                    }

                                }

                                //服用方式
                                if($takeData_type == 3){
                                    if(empty($dosage_way) && strpos($medical_name,$takeData_name) !== false){
                                        $dosage_way = $takeData_id;
                                        continue;
                                    }
                                    if(empty($dosage_way) && !empty($takeData_english) && strpos($medical_name,$takeData_english) !== false){
                                        $dosage_way = $takeData_id;
                                        continue;
                                    }
                                }

                                //服用频次
                                if($takeData_type == 4){
                                    if(empty($dosage_times) && strpos($medical_name,$takeData_name) !== false){
                                        $dosage_times = $takeData_id;
                                        $take_number = $takeData['take_number'];
                                        continue;
                                    }
                                    if(empty($dosage_times) && !empty($takeData_english) && strpos($medical_name,$takeData_english) !== false){
                                        $dosage_times = $takeData_id;
                                        $take_number = $takeData['take_number'];
                                        continue;
                                    }
                                }

                                //出院带药
                                if($takeData_type == 5){
                                    if(empty($is_dispensary) && strpos($medical_name,$takeData_name) !== false){
                                        $is_dispensary = $takeData_id;
                                        continue;
                                    }
                                    if(empty($is_dispensary) && !empty($takeData_english) && strpos($medical_name,$takeData_english) !== false){
                                        $is_dispensary = $takeData_id;
                                        continue;
                                    }
                                }
                                //服用频次
                                if($takeData_type == 6){
                                    if(empty($dosage_medication) && strpos($medical_name,$takeData_name) !== false){
                                        $dosage_medication = $takeData_id;
                                        continue;
                                    }
                                    if(empty($dosage_medication) && !empty($takeData_english) && strpos($medical_name,$takeData_english) !== false){
                                        $dosage_medication = $takeData_id;
                                        continue;
                                    }
                                }
                            }
                        }

                    }

                    $this->LocalService()->TmpDoctoradviceoriginal->update(['dosage_medication'=>$dosage_medication,'mate_type' => $mate_type,'is_lock'=>0,'medical_date'=>$medical_date,'end_date'=>$end_date,'drug_id'=>$drug_id,'dosage_id'=>$dosage_id,'dosage_unit'=>$dosage_unit,'dosage_way'=>$dosage_way,'dosage_times'=>$dosage_times,'is_dispensary'=>$is_dispensary,'mate_times'=>$take_number], 'id = ' . $medical_id);
                    unset($medicalDatas[$medicalDataKey]);
                }
            }
        }
        unset($medicalCond);
        unset($medicalDatas);

        return $last_medical_id;
    }


}