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

namespace Application\Service\DB\Tmp;
use Interop\Container\ContainerInterface;

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

    private $matchRatio = 90;


    /**
     * Notes : 匹配药物
     * @param array $medicalData
     * @param array $drugDatas
     * @return int|mixed
     * Author:唐伯虎不虎
     * Date:2024/2/1 10:43
     */
    public function mateDrugdata(array $medicalData, array $drugDatas) {
        $mateDrugId = 0;
        if(isset($drugDatas[$medicalData['medical_name_reduce']])) return $drugDatas[$medicalData['medical_name_reduce']]['id'];

        // 删除原匹配数据
        $this->upDelState(['is_del'=>0,'medical_id'=>$medicalData['id']], 1);

        if(isset($drugDatas[$medicalData['medical_name_reduce']])) return $drugDatas['id'];

        $firstArr = [];
        foreach($drugDatas as &$drugData) {

            if($isMate = $this->mateStr($medicalData['medical_name_reduce'], $drugData['name'])) {
                $matchRate = $this->stringdistance($drugData['name'],$medicalData['medical_name_reduce']);
                if(isset($firstArr['matchRate']) && $matchRate > $firstArr['matchRate']){
                    $firstArr['id'] = $drugData['id'];
                    $firstArr['name'] = $drugData['name'];
                    $firstArr['matchRate'] =$matchRate;
                }elseif(!isset($firstArr['matchRate'])){
                    $firstArr['id'] = $drugData['id'];
                    $firstArr['name'] = $drugData['name'];
                    $firstArr['matchRate'] =$matchRate;
                }
                if($matchRate >= $this->matchRatio) break;

            }
        }

        if(!empty($firstArr)){
            $mateDrugId = $this->savedata($medicalData,$firstArr);
            $isMate = true;
        }

        if(!$isMate) {

            $arr = [];

            $number = mb_strlen($medicalData['medical_name_reduce']);

            for ($i = 0; $i < $number; $i++) {
                $searhWord = mb_substr($medicalData['medical_name_reduce'],$i,3,'UTF-8');
                if(mb_strlen($searhWord) < 3) continue;

                foreach($drugDatas as $drugvalue) {
                    if(!is_string($drugvalue['name'])) continue;
                    if($this->mateStr($drugvalue['name'], $searhWord)) {

                        $matchRate = $this->stringdistance($drugvalue['name'],$medicalData['medical_name_reduce']);

                        if(isset($arr['matchRate']) && $matchRate >= $arr['matchRate']){
                            $arr['id'] = $drugvalue['id'];
                            $arr['name'] = $drugvalue['name'];
                            $arr['matchRate'] =$matchRate;
                        }elseif(!isset($arr['matchRate'])){
                            $arr['id'] = $drugvalue['id'];
                            $arr['name'] = $drugvalue['name'];
                            $arr['matchRate'] =$matchRate;
                        }
                        if($matchRate >= $this->matchRatio) break 2;
                    }
                }
            }

            if(!empty($arr)){
                $mateDrugId = $this->savedata($medicalData,$arr);
            }
        }

        return $mateDrugId;
    }

    public function savedata($medicalData,$firstArr)
    {
        $save_data = [
            'annex_id'=>$medicalData['annex_id'],
            'itemsig_id'=>$medicalData['sig_id'],
            'patient_id'=>$medicalData['patient_id'],
            'medical_id'=>$medicalData['id'],
            'medical_name'=>$medicalData['medical_name_reduce'],
            'drug_id'=>$firstArr['id'],
            'drug_name'=>$firstArr['name'],
            'mate_keyword'=>json_encode([$firstArr['name']]),
            'mate_num'=>1,
            'mate_rate'=>100,
            'name_rate'=>100,
            'is_mate'=>1
        ];
        $this->save($save_data);
        return $firstArr['id'];
    }


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

    public function stringdistance($string1,$string2)
    {
        $distance = levenshtein($string1, $string2);

        $maxLength = max(strlen($string1), strlen($string2));
        return  round((1 - ($distance / $maxLength)) * 100, 2);
    }


    /**
     * Notes : 添加新药物
     * @param array $params
     * Author:唐伯虎不虎
     * Date:2024/1/30 13:39
     */
    public function addNewMateDrugData(array $params) {

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

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

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

        $addData = [
            'annex_id' => $medicalData['annex_id'],
            'itemsig_id' => $medicalData['sig_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);
    }
}