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

namespace Application\Service\DB\Collect;
use Interop\Container\ContainerInterface;
use Laminas\Stdlib\ArrayUtils;
use Application\Common\Com;

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

    /**
     * Notes: 添加新药物
     * User: llbjj
     * DateTime: 2023/6/9 13:54
     *
     * @param array $params
     */
    public function addNewMateDrugData(array $params) {

        // 删除之前匹配上的药物
        $this->upDelState([
            'medical_id' => $params['medical_id'],
            'is_mate' => 1
        ]);

        $medicalData = $this->LocalService()->collectPatientmedical->fetchOne([
            'where' => [
                'id' => $params['medical_id'],
                'is_del' => 0
            ],
            'columns' => ['annex_id', 'itemsig_id', 'patient_id', 'medical_name']
        ]);

        $drugName = $this->LocalService()->collectItemdrug->getOneFieldVal('name','id = '.$params['drug_id']);

        $addData = [
            'annex_id' => $medicalData['annex_id'],
            'itemsig_id' => $medicalData['itemsig_id'],
            'patient_id' => $medicalData['patient_id'],
            'medical_id' => $params['medical_id'],
            'medical_name' => $medicalData['medical_name'],
            'drug_id' => $params['drug_id'],
            'drug_name' => $drugName,
            'mate_keyword' => json_encode([$drugName]),
            'is_mate' => 1,
            'mate_num' => 1,
            'mate_rate' => 100,
            'name_rate' => 100,
            'is_del' => 0
        ];

        $this->save($addData);
    }

    public function mateDrugdata(array $medicalData, array $drugDatas) {
        $mateDrugId = 0;
        $mateDrugName = '';
        if(!$medicalData['id']) return $mateDrugId;
        // 删除原匹配数据
        $this->upDelState([
            'is_del' => 0,
            'medical_id' => $medicalData['id']
        ], 1);

        foreach($drugDatas as &$drugData) {
            $mateKeywordData = &$drugData['mate_keyword_arr'];
            $mateKeywordData[] = $drugData['mate_drug_name'];

            $isMate = false;
            foreach($mateKeywordData as $keyword) {
                if($isMate = $this->mateStr($medicalData['mate_medical_name'], $keyword)) {
                    $save_data = [
                        'annex_id'=>$medicalData['annex_id'],
                        'itemsig_id'=>$medicalData['itemsig_id'],
                        'patient_id'=>$medicalData['patient_id'],
                        'medical_id'=>$medicalData['id'],
                        'medical_name'=>$medicalData['mate_medical_name'],
                        'drug_id'=>$drugData['id'],
                        'drug_name'=>$drugData['name'],
                        'mate_keyword'=>json_encode([$keyword]),
                        'mate_num'=>1,
                        'mate_rate'=>100,
                        'name_rate'=>100,
                        'is_mate'=>1
                    ];
                    $this->save($save_data);
                    $mateDrugId = $drugData['id'];
                    $mateDrugName = $drugData['name'];
                    break;
                }
            }

            // 关键字、全词未匹配，则进行单词匹配
            if(!$isMate) {
                foreach($mateKeywordData as $keyword) {
                    if(mb_strlen($keyword) <= 3) continue;
                    for ($i = 1; $i < mb_strlen($keyword) - 2; $i++) {
                        $searhWord = mb_substr($keyword, $i);
                        if($isMate = $this->mateStr($medicalData['mate_medical_name'], $searhWord)) {
                            $save_data = [
                                'annex_id'=>$medicalData['annex_id'],
                                'itemsig_id'=>$medicalData['itemsig_id'],
                                'patient_id'=>$medicalData['patient_id'],
                                'medical_id'=>$medicalData['id'],
                                'medical_name'=>$medicalData['mate_medical_name'],
                                'drug_id'=>$drugData['id'],
                                'drug_name'=>$drugData['name'],
                                'mate_keyword'=>json_encode([$searhWord]),
                                'mate_num'=>1,
                                'mate_rate'=>100,
                                'name_rate'=>100,
                                'is_mate'=>1
                            ];
                            $this->save($save_data);
                            $mateDrugId = $drugData['id'];
                            $mateDrugName = $drugData['name'];
                            break;
                        }
                    }
                    if($isMate) break;
                }
            }

            if($isMate) break;

        }
        return ['drug_id'=>$mateDrugId,'drug_name'=>$mateDrugName];
    }

    private function mateStr(string $str, string $searchStr) {
        return stripos($str, $searchStr) !== false;
    }

    /**
     * Notes: 获取指定条件下的识别结果匹配的数据【按照匹配度降序排列】
     * User: lltyy
     * DateTime: 2023/5/18 8:56
     *
     * @param $where
     * @param int $return_type 【0 所有数据 1 默认为匹配数据】
     * @return array[]
     */
    public function fetchMedicalMatedata($where,$return_type=0){
        $datas = [
            'mate'=>[],
            'no_mate'=>[]
        ];

        if($return_type == 1){
            $datas = [];
        }
        //获取指定条件下的识别结果数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','itemsig_id','patient_id','medical_name','medical_id','drug_id','drug_name','mate_keyword','mate_num','name_rate','mate_rate'],
            'order'=>['medical_id','is_mate desc','mate_num desc','mate_rate desc']
        ];
        $matedatas = $this->fetchAll($cond);
        if(!empty($matedatas)){
            foreach($matedatas as &$matedata) {
                //获取匹配上的数据
                $drug_id = $matedata['drug_id'];
                $mate_keyword = !empty($matedata['mate_keyword']) ? json_decode($matedata['mate_keyword'], true) : [];
                $matedata['mate_keyword'] = implode('、', $mate_keyword);

                $medical_id = $matedata['medical_id'];
                if($return_type == 1){
                    $datas[$medical_id] = $matedata;
                }else{
                    if($matedata['mate_rate'] > 10 && $matedata['name_rate'] > 15){
                        $datas['mate'][$medical_id][] = $matedata;
                    }else{
                        $datas['no_mate'][$medical_id][] = $matedata;
                    }
                }
            }
        }
        unset($cond);
        unset($matedatas);
        return $datas;
    }


    /**
     * Notes: 获取指定条件下的识别结果匹配的数据【按照匹配度降序排列】
     * User: lltyy
     * DateTime: 2023/5/18 8:56
     *
     * @param $where
     * @return array[]
     */
    public function fetchMateDrugByMedical($where,$columns){
        $datas = [];
        //获取指定条件下的识别结果数据
        $cond = [
            'where'=>$where,
            'columns'=>$columns,
            'order'=>['medical_id']
        ];
        $matedatas = $this->fetchAll($cond);
        if(!empty($matedatas)){
            foreach($matedatas as &$matedata) {
                //获取匹配上的数据
                $medical_id = $matedata['medical_id'];
                $drug_id = $matedata['drug_id'];
                $datas[$medical_id][$drug_id] = $matedata;
            }
        }
        unset($cond);
        unset($matedatas);
        return $datas;
    }

}