<?php
declare(strict_types=1);

namespace app\controller;

require_once app()->getRootPath() . 'vendor/autoload.php';

use app\model\Cases;
use app\model\CdssAdvisoryUserRecord;
use app\model\CdssDisease;
use app\model\CdssInspection;
use app\model\CdssMedicineMl;
use app\model\CdssMedicine;
use app\model\CdssXyDisease;
use app\model\ClinicalPathway;
use app\model\ClinicalTrial;
use app\model\Diagnosis;
use app\model\DrugOverdose;
use app\model\DrugAnswers;
use app\model\IpAccessLog;
use app\model\EssentialDrugs;
use app\model\LawRegulations;
use app\model\Ferri;
use app\model\GetGuide;
use app\model\GetGuideMent;
use app\model\GjybypmlEn;
use app\model\GjybypmlZh;
use app\model\Interact;
use app\model\Mission;
use app\model\XyPrescription;
use app\model\XySickNess;
use app\model\XyZskInspection;
use app\model\XyZskMedicine;
use app\model\ZyAcupoint;
use app\model\ZyChannelSymptom;
use app\model\ZyConstitution;
use app\model\ZyMedicinalCrop;
use app\model\ZyPatentMedicine;
use app\model\ZyPrescription;
use app\model\ZySickness;
use app\model\ZyTonicDiet;
use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use think\response\Json;
use app\model\Cdsss;
use app\model\CdssSelect;
use app\model\CdssAdvisory;
use app\model\Symptom;
use app\model\ZhSymptom;
use app\model\DiseasesKeyword;
use app\model\DiseaseCategoryProperties;
use app\model\XyZskDisease;
use app\model\Operation;
use app\model\Zyxdya;
use app\model\Zygdya;
use app\model\Xyhl;
use app\model\Zyjbbz;
use app\model\Zztz;
use app\model\Zyfywlf;
use app\model\GetZhGuide;
class Cdss extends CommonTwoController
{

    /**
     * Cdss Options List
     *
     * @return Json
     */
    public function index(): Json
    {
        $cdss = Cdsss::field(['category', 'options'])->select();
        foreach (array_filter($cdss->toArray()) as $key => $value) {
            $cdss[$key]['select_options'] = CdssSelect::field(['select_name', 'select_values'])->where(['category' => CdssSelect::getCategoryInt($value['category'])])->select();
        }
        return $this->_json_succ($cdss);
    }


    /**
     * 获取症状相关的疾病
     *
     * @param string $values 症状值
     * @param int $age 年龄
     * @param int $sex 性别(1:男,2:女)
     * @param string $tag 标签
     * @param int $page 页码
     * @param int $pagesize 每页数量
     * @return array
     */
    public function getSymptomAboutDisease($values, $age, $sex, $tag = 'symptom', $page = 1, $pagesize = 1000): array
    {
        switch ($tag) {
            case 'symptom':
                /**
                 * 从疾病的临床表现属性匹配症状
                 * 单个或多条件匹配
                 */
                if (stripos($values, ',') !== false) {
                    $symptoms = explode(',', $values);
                    $query = CdssXyDisease::where('1=1');
                    // 使用AND连接多个症状条件
                    foreach ($symptoms as $symptom) {
                        $query = $query->where('clinicalFeature', 'like', '%' . $symptom . '%');
                    }
                    $aboutDiseases = $query->limit(200)->select()->toArray();
                } else {
                    $aboutDiseases = CdssXyDisease::whereLike('clinicalFeature', '%' . $values . '%')
                        ->limit(200)
                        ->select()
                        ->toArray();
                }

                /**
                 * neo4j 查不到情况去mysql查询
                 */
                if (empty($aboutDiseases)) {
                    if (stripos($values, ',') !== false) {
                        $symptoms = explode(',', $values);
                        foreach ($symptoms as $key => $symptom) {
                            //$arr[$key] = $symptom . '%';
                            $diseases[] = Symptom::field('disease')->where('name', 'like', $symptom . '%')->select()->toArray();
                        }
                        //$diseases = Symptom::field('disease')->where('name', 'like', $arr, 'AND')->select()->toArray();
                    } else {
                        $diseases = Symptom::field('disease')->whereLike('name', $values . '%')->select()->toArray();
                    }

                    if (empty($diseases)) {
                        return [];
                    }

                    $diseases = array_column($diseases, 'disease');

                    foreach ($diseases as $k => $disease) {
                        $diseases[$k] = str_replace('||', ',', $disease);
                    }
                    $diseases = implode(',', $diseases);
                    $diseasesArr = explode(',', $diseases);

                    $count = count($diseasesArr);
                    for ($i = 0; $i < $count; $i++) {
                        $aboutDiseases[$i]['name'] = $diseasesArr[$i];
                        $aboutDiseases[$i]['pathogenesis'] = '';
                        $aboutDiseases[$i]['clinicalFeature'] = '';
                    }
                }
                break;
        }



        /**
         * 剔除该性别不应该出现疾病
         */
        if (1 == $sex) {
            $tag = 3;
        } elseif (2 == $sex) {
            $tag = 4;
        }
        $sexDiseasesKeywords = DiseasesKeyword::where('tag', $tag)->value('keyword');
        if ($sexDiseasesKeywords) {
            if (stripos($sexDiseasesKeywords, ',') !== false) {
                $sexDiseasesKeywords = explode(',', $sexDiseasesKeywords);
                foreach ($aboutDiseases as $k => $v) {
                    foreach ($sexDiseasesKeywords as $sexDiseasesKeyword) {
                        if (stripos($v['name'], $sexDiseasesKeyword) !== false) {
                            unset($aboutDiseases[$k]);
                        }
                    }
                }
            } else {
                foreach ($aboutDiseases as $k => $v) {
                    if (stripos($v['name'], $sexDiseasesKeywords) !== false) {
                        unset($aboutDiseases[$k]);
                    }
                }
            }
        }

        /**
         * 年龄筛选
         */
        $ageAboutDiseases = $this->getAboutDiseasesByAge($aboutDiseases, $age);
        return $this->getAboutDiseasesByKeywordCount($ageAboutDiseases, $values);
    }

    /**
     * 中医疾病症状匹配
     */
    public function getSymptomAboutZhDisease($values, $age, $sex, $sx, $mx, $tag = 'symptom', $page = 1, $pagesize = 1000): array
    {
        switch ($tag) {
            case 'symptom':
                /**
                 * 从疾病的临床表现属性匹配症状
                 * 单个或多条件匹配
                 */
                $query = zySickNess::where('1=1');
                if (stripos($values, ',') !== false) {
                    $symptoms = explode(',', $values);

                    // 使用AND连接多个症状条件
                    foreach ($symptoms as $symptom) {
                        $query = $query->where('symptom', 'like', '%' . $symptom . '%');
                    }

                } else {
                    $query = $query->whereLike('symptom', '%' . $values . '%');

                }
                //添加舌象和脉象的匹配
                if (!empty($sx)) {
                    if (stripos($sx, ',') !== false) {
                        $sx = explode(',', $sx);
                        foreach ($sx as $s) {
                            $query = $query->where('tongueCondition', 'like', '%' . $s . '%');
                        }
                    } else {
                        $query = $query->where('tongueCondition', 'like', '%' . $sx . '%');
                    }
                }
                if (!empty($mx)) {
                    if (stripos($mx, ',') !== false) {
                        $mx = explode(',', $mx);
                        foreach ($mx as $m) {
                            $query = $query->where('pulseCondition', 'like', '%' . $m . '%');
                        }
                    } else {
                        $query = $query->where('pulseCondition', 'like', '%' . $mx . '%');
                    }
                }
                $aboutDiseases = $query->limit(200)->select()->toArray();

        }



        /**
         * 剔除该性别不应该出现疾病
         */
        if (1 == $sex) {
            $tag = 3;
        } elseif (2 == $sex) {
            $tag = 4;
        }
        $sexDiseasesKeywords = DiseasesKeyword::where('tag', $tag)->value('keyword');
        if ($sexDiseasesKeywords) {
            if (stripos($sexDiseasesKeywords, ',') !== false) {
                $sexDiseasesKeywords = explode(',', $sexDiseasesKeywords);
                foreach ($aboutDiseases as $k => $v) {
                    foreach ($sexDiseasesKeywords as $sexDiseasesKeyword) {
                        if (stripos($v['name'], $sexDiseasesKeyword) !== false) {
                            unset($aboutDiseases[$k]);
                        }
                    }
                }
            } else {
                foreach ($aboutDiseases as $k => $v) {
                    if (stripos($v['name'], $sexDiseasesKeywords) !== false) {
                        unset($aboutDiseases[$k]);
                    }
                }
            }
        }

        /**
         * 年龄筛选
         */
        $ageAboutDiseases = $this->getAboutDiseasesByAge($aboutDiseases, $age);

        return $ageAboutDiseases;
    }


    /**
     * 根据年龄返回相关疾病
     *
     * @param  array $aboutDiseases
     * @param  int   $age
     * @return array
     */
    private function getAboutDiseasesByAge($aboutDiseases, $age): array
    {
        $age = (int) $age;
        $childDiseasesKeyword = DiseasesKeyword::where('tag', DiseasesKeyword::CHILDTAG)->find();
        $oldDiseasesKeyword = DiseasesKeyword::where('tag', DiseasesKeyword::OLDTAG)->find();

        $childAboutDiseasesKeyword = $childDiseasesKeyword['keyword'];
        $oldAboutDiseasesKeyword = $oldDiseasesKeyword['keyword'];

        $ageAboutDiseases = [];
        foreach ($aboutDiseases as $k => $v) {
            if ($age <= 14) {
                $count = count($childAboutDiseasesKeyword);
                for ($i = 0; $i < $count; $i++) {
                    if (stripos($v['name'], $childAboutDiseasesKeyword[$i]) !== false) {
                        $ageAboutDiseases[] = $v;
                    }
                }
            } elseif ($age >= 60) {
                $count = count($oldAboutDiseasesKeyword);
                for ($i = 0; $i < $count; $i++) {
                    if (stripos($v['name'], $oldAboutDiseasesKeyword[$i]) !== false) {
                        $ageAboutDiseases[] = $v;
                    }
                }
            } else {
                $merge = (array) array_merge($childAboutDiseasesKeyword, $oldAboutDiseasesKeyword);
                $count = count($merge);
                for ($i = 0; $i < $count; $i++) {
                    if (stripos($v['name'], $merge[$i]) !== false) {
                        unset($aboutDiseases[$k]);
                    }
                }
                $ageAboutDiseases = array_values($aboutDiseases);
            }
        }
        return $ageAboutDiseases ?? [];
    }


    /**
     * 根据关键字出现频率排序
     *
     * @param  array   $aboutDiseases
     * @param  string  $keyword
     * @return array
     */
    private function getAboutDiseasesByKeywordCount($aboutDiseases, $keyword): array
    {
        if (empty($aboutDiseases)) {
            return [];
        }

        if (stripos($keyword, ',') !== false) {
            foreach ($aboutDiseases as $key => $value) {
                $aboutDiseases[$key]['keyword_count'] = $this->getKeywordTotalCount($value['clinicalFeature'], $keyword);
            }
        } else {
            foreach ($aboutDiseases as $key => $value) {
                $aboutDiseases[$key]['keyword_count'] = substr_count($value['clinicalFeature'], $keyword);
            }
        }

        if (count($aboutDiseases) > 1) {
            $keyword_count = array_column($aboutDiseases, 'keyword_count');
            array_multisort($keyword_count, SORT_DESC, $aboutDiseases);
        }
        return $aboutDiseases ?? [];
    }


    /**
     * 获取多个关键字出现频率总次数
     *
     * @param string $clinicalFeature
     * @param string $keyword
     * @return int
     */
    private function getKeywordTotalCount($clinicalFeature, $keyword): int
    {
        $keywordArray = array_values(array_filter(explode(',', $keyword)));
        $keywordArrayCount = count($keywordArray);

        $totalCount = 0;
        for ($i = 0; $i < $keywordArrayCount; $i++) {
            if ($clinicalFeature) {
                $totalCount += substr_count($clinicalFeature, $keywordArray[$i]);
            }
        }
        return $totalCount;
    }


    /**
     * deal str add ''
     *
     * @param  $str string
     * @return string
     */
    private function strSet($str): string
    {
        $symptoms = explode(',', $str);
        foreach ($symptoms as $key => $val) {
            $symptoms[$key] = "'" . $val . "'";
        }
        return implode(',', $symptoms);
    }

    public function getInspection()
    {
        //参数
        $str = Request::param('str');
        $sex = Request::param('sex');
        $age = Request::param('age');

        $query = Db::table('jm_cdss_xy_disease');
        if ($age < 14) {
            $where[] = ['name', 'like', '%小儿%'];
            $where[] = ['name', 'like', '%儿童%'];
            $where[] = ['name', 'like', '%婴儿%'];
            $where[] = ['alias', 'like', '%小儿%'];
            $where[] = ['alias', 'like', '%儿童%'];
            $where[] = ['alias', 'like', '%婴儿%'];
        } elseif ($age <= 14 && $age < 60) {
            $where[] = ['name', 'not like', '%小%'];
            $where[] = ['name', 'not like', '%儿童%'];
            $where[] = ['name', 'not like', '%婴儿%'];
            $where[] = ['name', 'not like', '%老年%'];
            $where[] = ['alias', 'not like', '%小儿%'];
            $where[] = ['alias', 'not like', '%儿童%'];
            $where[] = ['alias', 'not like', '%婴儿%'];
            $where[] = ['alias', 'not like', '%老年%'];
        } elseif ($age >= 60) {
            $where[] = ['name', 'like', '%老年%'];
            $where[] = ['alias', 'like', '%老年%'];
        }
        //判断性别
        if ($sex == '男') {
            $where[] = ['alias', 'not like', '%女%'];
            $where[] = ['alias', 'not like', '%阴道%'];
            $where[] = ['alias', 'not like', '%外阴%'];
            $where[] = ['alias', 'not like', '%阴唇%'];
        }
        if ($sex == '女') {
            $where[] = ['alias', 'not like', '%男%'];
            $where[] = ['alias', 'not like', '%睾丸%'];
        }

        //处理主诉
        $sys = config('inspec.sys');
        $symptomsArray = explode(',', $sys);
        $matchedSymptoms = [];
        foreach ($symptomsArray as $symptom) {
            if (strpos($str, $symptom) !== false) {
                $matchedSymptoms[] = $symptom;
            }
        }
        if (!$matchedSymptoms) {
            return $this->_json_error('没有匹配到相关疾病症状');
        }
        $matchedSymptoms = array_unique($matchedSymptoms);
        //查询症状
        foreach ($matchedSymptoms as $v) {
            $where[] = ['symptom', 'like', "%$v%"];
        }


        $result = Db::table('jm_cdss_xy_disease') // 替换为你的表名
            ->where($where)->page(1)->limit(10)
            ->select();
        //var_dump(DB::getLastSql());

        return $this->_json_succ($result);
    }

    /**
     * Get Disease About Inspection | Medicine
     *
     * @param $diseaseName string
     * @param $page        int
     * @param $pagesize    int
     * @return Json
     */
    public function getInspectionOrMedicineByDisease(): Json
    {
        $diseaseName = Request::param('disease_name');
        if (!$diseaseName) {
            return $this->_json_error('请求参数有误！');
        }

        $page = Request::param('page') ?? 1;
        $pagesize = Request::param('pagesize') ?? 20;
        $limit = ($page - 1) * $pagesize;

        $disease = CdssXyDisease::where('name', $diseaseName)->find();

        /**
         * 检查
         */
        $inspection = $disease->inspection;
        $inspectionList = explode(',', $inspection);

        $list = [];

        $newInspectionList = [];
        if (empty($inspectionList)) {
            $newInspectionList = [];
        } else {
            foreach ($inspectionList as $key => $value) {
                $newInspectionList[$key]['name'] = $value;
            }
        }
        $list['inspection_list'] = $newInspectionList;


        /**
         * 药品
         */
        $medicine = $disease->regularMedication;
        $medicineList = explode(',', $medicine);
        $newMedicineList = [];

        if (empty($medicineList)) {
            $newMedicineList = [];
        } else {
            foreach ($medicineList as $k => $v) {
                $newMedicineList[$k]['name'] = $v;
            }
        }
        $list['medicine_list'] = $newMedicineList;



        /**
         * 并发症
         */
        $complicationsOverview = $disease->complicationsOverview;
        $complicationsOverviewList = explode(',', $complicationsOverview);
        $newComplicationsOverviewList = [];

        if (empty($complicationsOverviewList)) {
            $newComplicationsOverviewList = [];
        } else {
            foreach ($complicationsOverviewList as $kk => $vv) {
                $newComplicationsOverviewList[$kk]['name'] = $vv;
            }
        }

        $list['complication_list'] = $newComplicationsOverviewList;

        //相关症状
        $symptom = $disease->symptom;
        $symptomList = explode(',', $symptom);
        $newsymptomList = [];

        if (empty($symptomList)) {
            $newsymptomList = [];
        } else {
            foreach ($symptomList as $k => $v) {
                $newsymptomList[$k]['name'] = $v;
            }
        }
        $list['symptom_list'] = $newsymptomList;

        //查体
        $examination = $disease->examination;
        $examinationList = explode(',', $examination);
        $newexaminationList = [];

        if (empty($examinationList)) {
            $newexaminationList = [];
        } else {
            foreach ($examinationList as $k => $v) {
                $newexaminationList[$k]['name'] = $v;
            }
        }
        $list['examination_list'] = $newexaminationList;
        //治疗方案
        $treatment = $disease->treatment;
        $list['treatment_list'] = $treatment;

        //相关手术
        $relevantOperation = $disease->relevantOperation;
        $relevantOperationList = explode(',', $relevantOperation);
        $newrelevantOperationList = [];

        if (empty($relevantOperationList)) {
            $newrelevantOperationList = [];
        } else {
            foreach ($relevantOperationList as $k => $v) {
                $newexaminationList[$k]['name'] = $v;
            }
        }
        $list['relevantOperation_list'] = $newrelevantOperationList;

        $list['identity_list'] = [];
        $list['graph'] = [];

        return $this->_json_succ(
            $list
        );
    }


    /**
     * Disease Graph
     *
     * @param $name string
     * @return array
     */
    private function graph($name): array
    {
        $query = "match p  = (n:Disease)-[r:DiseaseComplication]-(m:Thing) where n.name= " . "'" . $name . "'" . " return p";
        $query1 = "match p1 = (n:Disease)-[r:LinkMedicineDisease]-(m:Thing) where n.name= " . "'" . $name . "'" . " return p1";
        $query2 = "match p2 = (n:Disease)-[r:LinkInspection]-(m:Thing) where n.name= " . "'" . $name . "'" . " return p2";
        $data = $this->getXyR($query, $query1, $query2);
        $list = [];
        foreach ($data as $key => $value) {
            $list['icd'] = ['name' => 'ICD', 'text' => $data[$key]['start']['properties']['icd'] ?? ''];
            $list['name'] = ['name' => '名称', 'text' => $data[$key]['start']['properties']['name'] ?? ''];
            $list['alias'] = ['name' => '疾病别名', 'text' => $data[$key]['start']['properties']['alias'] ?? ''];
            $list['department'] = ['name' => '疾病类别', 'text' => $data[$key]['start']['properties']['department'] ?? ''];
            $list['complication'] = ['name' => '并发症', 'text' => $data[$key]['start']['properties']['complication'] ?? ''];
            $list['epidemiology'] = ['name' => '流行病学', 'text' => $data[$key]['start']['properties']['epidemiology'] ?? ''];
            $list['nameEn'] = ['name' => '英文名称', 'text' => $data[$key]['start']['properties']['nameEn'] ?? ''];
            $list['sickOverview'] = ['name' => '疾病概述', 'text' => $data[$key]['start']['properties']['sickOverview'] ?? ''];
            $list['clinicalFeature'] = ['name' => '临床表现', 'text' => $data[$key]['start']['properties']['clinicalFeature'] ?? ''];
            $list['diagnosis'] = ['name' => '诊断', 'text' => $data[$key]['start']['properties']['diagnosis'] ?? ''];
            $list['treatment'] = ['name' => '治疗', 'text' => $data[$key]['start']['properties']['treatment'] ?? ''];
            $list['regularMedication'] = ['name' => '相关药品', 'text' => $data[$key]['start']['properties']['regularMedication'] ?? ''];
            $list['pathogenesis'] = ['name' => '发病机制', 'text' => $data[$key]['start']['properties']['pathogenesis'] ?? ''];
            $list['inspection'] = ['name' => '相关检查', 'text' => $data[$key]['start']['properties']['inspection'] ?? ''];
            $list['laboratoryInspection'] = ['name' => '实验室检查', 'text' => $data[$key]['start']['properties']['laboratoryInspection'] ?? ''];
            $list['etiology'] = ['name' => '病因', 'text' => $data[$key]['start']['properties']['etiology'] ?? ''];
            $list['auxiliaryExamination'] = ['name' => '其他辅助检查', 'text' => $data[$key]['start']['properties']['auxiliaryExamination'] ?? ''];
            $list['prognosis'] = ['name' => '预后', 'text' => $data[$key]['start']['properties']['prognosis'] ?? ''];
            $list['complicationsOverview'] = ['name' => '并发症概述', 'text' => $data[$key]['start']['properties']['complicationsOverview'] ?? ''];
            $list['precaution'] = ['name' => '预防', 'text' => $data[$key]['start']['properties']['precaution'] ?? ''];
            $data[$key]['start']['properties'] = $list;
            //$data[$key]['start']['tag']		   = $tag;

            if ($value['relationship']['type'] === 'DISEASECOMPLICATION') {
                $listEnd = [
                    'name' => ['name' => '疾病名称', 'text' => $data[$key]['end']['properties']['name']],
                ];
                $data[$key]['end']['properties'] = $listEnd;
                //$data[$key]['end']['tag']		 = $tag;
            }

            if ($value['relationship']['type'] === 'LINKMEDICINEDISEASE') {
                $listEnd = [
                    'name' => ['name' => '名称', 'text' => $data[$key]['end']['properties']['name'] ?? ''],
                    'pinyi' => ['name' => '汉语拼音', 'text' => $data[$key]['end']['properties']['pinyin'] ?? ''],
                    'oldUse' => ['name' => '老人用药', 'text' => $data[$key]['end']['properties']['oldUse'] ?? ''],
                    'chilldUse' => ['name' => '儿童用药', 'text' => $data[$key]['end']['properties']['chilldUse'] ?? ''],
                    'medicinePregnant' => ['name' => '孕妇及哺乳期妇女用药', 'text' => $data[$key]['end']['properties']['medicinePregnant'] ?? ''],
                    'usageDosage' => ['name' => '用法用量', 'text' => $data[$key]['end']['properties']['usageDosage'] ?? ''],
                    'notes' => ['name' => '注意事项', 'text' => $data[$key]['end']['properties']['notes'] ?? ''],
                    'periodValidity' => ['name' => '有效期', 'text' => $data[$key]['end']['properties']['periodValidity'] ?? ''],
                    'indication' => ['name' => '适应症', 'text' => $data[$key]['end']['properties']['indication'] ?? ''],
                    'storage' => ['name' => '贮藏', 'text' => $data[$key]['end']['properties']['storage'] ?? ''],
                    'character' => ['name' => '性状', 'text' => $data[$key]['end']['properties']['character'] ?? ''],
                    'contraindication' => ['name' => '禁忌', 'text' => $data[$key]['end']['properties']['contraindication'] ?? ''],
                    'pharmacologyToxicology' => ['name' => '药理毒理', 'text' => $data[$key]['end']['properties']['pharmacologyToxicology'] ?? ''],
                    'specification' => ['name' => '规格', 'text' => $data[$key]['end']['properties']['specification'] ?? ''],
                    'approvalNumber' => ['name' => '批准号', 'text' => $data[$key]['end']['properties']['approvalNumber'] ?? ''],
                    'productionEnterprise' => ['name' => '生产企业', 'text' => $data[$key]['end']['properties']['productionEnterprise'] ?? ''],
                    'relateSick' => ['name' => '相关疾病', 'text' => $data[$key]['end']['properties']['relateSick'] ?? ''],
                    'untowardEffect' => ['name' => '不良反应', 'text' => $data[$key]['end']['properties']['untowardEffect'] ?? ''],
                    'majorConstituent' => ['name' => '主要成分', 'text' => $data[$key]['end']['properties']['majorConstituent'] ?? ''],
                ];
                $data[$key]['end']['properties'] = $listEnd;
                $data[$key]['end']['tag'] = 'medicine';
            }

            if ($value['relationship']['type'] === 'LINKINSPECTION') {
                $listEnd = [
                    'name' => ['name' => '名称', 'text' => $data[$key]['end']['properties']['name'] ?? ''],
                    'overview' => ['name' => '概述', 'text' => $data[$key]['end']['properties']['overview'] ?? ''],
                    'annotation' => ['name' => '附注', 'text' => $data[$key]['end']['properties']['annotation'] ?? ''],
                    'principle' => ['name' => '原理', 'text' => $data[$key]['end']['properties']['principle'] ?? ''],
                    'normalValue' => ['name' => '正常值', 'text' => $data[$key]['end']['properties']['normalValue'] ?? ''],
                    'clinicalSignificance' => ['name' => '临床意义', 'text' => $data[$key]['end']['properties']['clinicalSignificance'] ?? ''],
                    'reagent' => ['name' => '试剂', 'text' => $data[$key]['end']['properties']['reagent'] ?? ''],
                    'operation' => ['name' => '操作方法', 'text' => $data[$key]['end']['properties']['operation'] ?? ''],
                ];
                $data[$key]['end']['properties'] = $listEnd;
                $data[$key]['end']['tag'] = 'inspection';
            }
        }
        return $data;
    }


    /**
     * Many Select Option list
     *
     * @return Json
     */
    public function manySelectOptionList(): Json
    {
        $options = (new CdssAdvisory())->getCategory();
        $manySelect = [];
        foreach ($options as $key => $value) {
            $manySelect[] = ['category' => $value, 'many_select_options' => CdssAdvisory::where('category', $key)->order('order', 'desc')->select()];
        }
        return $this->_json_succ($manySelect);
    }

    public function getDepartment()
    {
        $data = CdssXyDisease::field('department_1,department_2')->where('department_1', '<>', '')->group('department_1,department_2')->select();
        // 初始化结果数组
        $result = [];

        foreach ($data as $item) {
            $department1 = $item['department_1'];
            $department2 = $item['department_2'];

            if (!isset($result[$department1])) {
                $result[$department1] = [
                    'department_1' => $department1,
                    'department_2' => []
                ];
            }

            $result[$department1]['department_2'][] = $department2;
        }

        // 将结果转换为数组
        $resultArray = array_values($result);
        return $this->_json_succ($resultArray);
    }

    /**
     * Cdss Many Select Symptom Search
     *
     * @param $keyword string
     * @return Json
     */
    public function getSymptomBykeyword(): Json
    {
        if (!$keyword = Request::param('keyword')) {
            return $this->_json_error('请求参数有误！');
        }
        $query = "match(n:Symptom) where n.name =~'.*" . $keyword . ".*' return n.name as name limit 20";
        $symptomNameArr = $this->getAboutInfo($query) ?? [];
        return $this->_json_succ($symptomNameArr ? array_column($symptomNameArr, 'name') : []);
    }


    /**
     * store User Submit Advisory
     *
     * @param  $name string
     * @param  $age  int
     * @param  $sex  int
     * @param  $advisory_content  array
     * @return Json
     */
    public function storeUserSubmitAdvisory(): Json
    {
        try {
            $params = input('post.');
            $cdssAdvisoryUserRecord = new CdssAdvisoryUserRecord();
            $cdssAdvisoryUserRecord->save($params);
            $params['id'] = $cdssAdvisoryUserRecord->id;
        } catch (\Exception $e) {
            return $this->_json_error($e->getMessage());
        }

        if (!empty($params['sx']) && empty($params['mx'])) {
            $symptom_about_zh_disease = $this->getSymptomAboutZhDisease($params['symptoms'], $params['age'], $params['sex'], $params['sx'], '');
        } elseif (empty($params['sx']) && !empty($params['mx'])) {
            $symptom_about_zh_disease = $this->getSymptomAboutZhDisease($params['symptoms'], $params['age'], $params['sex'], '', $params['mx']);
        } elseif (!empty($params['sx']) && !empty($params['mx'])) {
            $symptom_about_zh_disease = $this->getSymptomAboutZhDisease($params['symptoms'], $params['age'], $params['sex'], $params['sx'], $params['mx']);
        } else {
            $symptom_about_zh_disease = $this->getSymptomAboutZhDisease($params['symptoms'], $params['age'], $params['sex'], '', '');
        }

        return $this->_json_succ(
            [
                'advisory_content' => $params,
                'symptom_about_sickness' => $this->getSymptomAboutDisease($params['symptoms'], $params['age'], $params['sex']),
                'symptom_about_zh_disease' => $symptom_about_zh_disease
            ]
        );
    }


    /**
     * get User Select Advisory
     *
     * @param  int $id
     * @return Json
     */
    public function getUserAdvisory(): Json
    {
        if (!$id = Request::param('id')) {
            return $this->_json_error('请求参数有误！');
        }

        $cdssAdvisoryUserRecord = CdssAdvisoryUserRecord::find($id);
        return $this->_json_succ(
            [
                'advisory_content' => $cdssAdvisoryUserRecord,
                'symptom_about_sickness' => $this->getSymptomAboutDisease($cdssAdvisoryUserRecord['symptoms'], $cdssAdvisoryUserRecord['age'], $cdssAdvisoryUserRecord['sex'])
            ]
        );
    }


    /**
     * 关键字检索知识库
     *
     * @param string   $tag
     * @param string   $keyword
     * @return Json
     */
    public function getMedicalKnowledgeByKeyword(): Json
    {
        //限制时间访问
        $expirationTime = strtotime("2026-01-01 00:00:00");
        $currentTimestamp = time();

        if ($currentTimestamp > $expirationTime) {
            return $this->_json_error('已过期，无法访问');
            // 当前时间已经超过有效期，拒绝访问
            http_response_code(403);
            exit('接口已过期，无法访问');
        }

        $tag = Request::param('tag') ?? '';
        $keyword = Request::param('keyword') ?? '';
        $type = Request::param('type') ?? '';

        $page = Request::param('page') ?? 1;
        $pagesize = Request::param('pagesize') ?? 10;
        $pagesize = (int) $pagesize;
        $limit = ($page - 1) * $pagesize;

        $department = Request::param('department') ?? '';
        $department2 = Request::param('department_2') ?? '';
        $where = [];

        $aa = ['zySickNess', 'Inspection', 'Disease', 'Ferri'];

        if ($department && (in_array($tag, $aa))) {
            $where['department'] = $department;
        }

        if ($department && $department2 && $tag === 'Disease') {
            $where = [
                'department_1' => $department,
                'department_2' => $department2,
            ];
        }

        //if($department && $tag === 'SickNess') {
        //    $where = ['department' => $department];
        //}

        if (!$tag) {
            return $this->_json_error('参数有误！');
        }

        if (stripos($tag, ',') !== false) {
            /**
             * 多个tag请求
             */
            $tags = explode(',', $tag);
            $data = [];

            $newCount = 0;
            foreach ($tags as $value) {
                switch ($value) {
                    /**
                     * 西医疾病
                     */
                    case 'Disease':
                        $data = CdssDisease::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = CdssDisease::field('name')
                            ->where("name", "like", "%$keyword%")

                            ->count();
                        break;

                    /**
                     * 检查
                     */
                    case 'Inspection':
                        $data = CdssInspection::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = CdssInspection::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->count();
                        break;
                    /**
                     * 药品
                     */
                    case 'MedicineProduction':
                        $data = CdssMedicine::field('name')
                            ->where("relateSick", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->limit(30)
                            ->select()
                            ->toArray();
                        $count = CdssMedicine::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->count();
                        break;
                    /**
                     * 症状
                     */
                    case 'Symptom':
                        $data = Symptom::field('name')
                            ->where("disease", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = Symptom::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->count();
                        break;
                    /**
                     * 手术操作
                     */
                    case 'Operation':
                        $data = Operation::field('operation_name as name')
                            ->where("operation_name", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = Operation::field('name')
                            ->where("operation_name", "like", "%$keyword%")
                            ->count();
                        break;
                    /**
                     * 诊疗指南
                     */
                    case "DiagnosisTreatment":
                        $data = GetGuide::field('title_trans as name,id')
                            ->where("keyword_cn", "like", "%$keyword%")
                            ->whereOr("keyword", "like", "%$keyword%")
                            ->whereOr("title", "like", "%$keyword%")
                            ->whereOr("title_trans", "like", "%$keyword%")
                            ->order('publish_time', 'DESC')
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = GetGuide::field('title_trans as name,id')
                            ->where("keyword_cn", "like", "%$keyword%")
                            ->whereOr("keyword", "like", "%$keyword%")
                            ->whereOr("title", "like", "%$keyword%")
                            ->whereOr("title_trans", "like", "%$keyword%")
                            ->count();
                        break;
                    case "GuideMap":
                        /**
                         * 指南脑图
                         */
                        $data = [
                            ['name' => 'csco食管癌诊疗指南2022脑图', 'tag' => 'zh'],
                            ['name' => 'nccn食管癌诊疗指南2022v2脑图（中文）', 'tag' => 'en']
                        ];
                        break;

                    case "GuideStructure":
                        /**
                         * 指南结构化
                         */
                        $data = [
                            ['name' => 'nccn食管癌诊疗指南2022v2（中文）']
                        ];
                        break;
                    case 'Antidiastole':
                        /**
                         * 误诊误治（鉴别诊断）
                         */
                        $data = CdssXyDisease::field('name')
                            //->where("name" , "like" , "%$keyword%" )
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = CdssXyDisease::field('name')
                            //->where("name" , "like" , "%$keyword%" )
                            ->limit($limit, $pagesize)
                            ->count();
                        break;
                    case "Acupoint":
                        $data = ZyAcupoint::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                        $count = ZyAcupoint::where('name', 'like', "%$keyword%")->count();
                        break;

                    case "CnMedicinalCrop":
                        $data = ZyMedicinalCrop::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                        $count = ZyMedicinalCrop::where('name', 'like', "%$keyword%")->count();
                        break;

                    case "CnPatentMedicine":
                        $data = ZyPatentMedicine::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                        $count = ZyPatentMedicine::where('name', 'like', "%$keyword%")->count();
                        break;

                    case "Prescription":
                        $data = ZyPrescription::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                        $count = ZyPrescription::where('name', 'like', "%$keyword%")->count();
                        break;

                    case "TonicDiet":
                        $data = ZyTonicDiet::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                        $count = ZyTonicDiet::where('name', 'like', "%$keyword%")->count();
                        break;

                    case "ChannelCollateral":
                        $data = ZyChannelSymptom::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                        $count = ZyChannelSymptom::where('name', 'like', "%$keyword%")->count();
                        break;
                    case "zySickNess":
                        return $this->_json_succ(333);
                        $data = ZySickness::where('name', 'like', "%$keyword%")->whereOr('dialecticalName', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                        $count = ZySickness::where('name', 'like', "%$keyword%")->whereOr('dialecticalName', 'like', "%$keyword%")->count();
                        break;
                    case "SickNess":
                        $data = XySickNess::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                        $count = XySickNess::where('name', 'like', "%$keyword%")->count();
                        break;
                    case "Constitution":
                        $data = ZyConstitution::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                        $count = ZyConstitution::where('name', 'like', "%$keyword%")->count();
                        break;
                    case "zyfywlf":
                        try {


                            // 执行查询
                            $data = Zyfywlf::where('name', 'like', "%$keyword%")
                                ->limit($limit, $pagesize)
                                ->select()
                                ->toArray();



                            $count = Zyfywlf::where('name', 'like', "%$keyword%")->count();


                        } catch (\Exception $e) {
                            trace("Error in zyfywlf case: " . $e->getMessage());
                            throw $e;
                        }
                        break;

                    case 'ZhSymptom':
                        $data = ZhSymptom::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = ZhSymptom::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->count();
                        break;

                }

                foreach ($data as $key => $val) {
                    $data[$key]['description'] = DiseaseCategoryProperties::getValueByTag($value, $type);
                    if ('ClinicalPathway' === $tag) {
                        $data[$key]['file'] = $this->checkDocPdfIsExist('http://jm.jiankangche.cn/lcljpdf/' . $val['name'] . '.pdf');
                    } elseif ('ClinicalTrial' === $tag) {
                        $data[$key]['file'] = $this->checkDocPdfIsExist('http://jm.jiankangche.cn/lcsyword/' . $val['register_number'] . '详细信息.pdf');
                    } else {
                        $data[$key]['file'] = '';
                    }
                }
                $lists[$value] = $data;
            }

        } else {

            /**
             * 单个tag请求
             */
            //return $this->_json_succ($tag);
            switch ($tag) {
                case "ClinicalPathway":
                    if ($keyword) {
                        /**
                         * 临床路径查询mysql
                         */
                        $data = ClinicalPathway::field('clinical_pathway as name')
                            ->where("clinical_pathway", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = ClinicalPathway::field('clinical_pathway as name')->where('clinical_pathway', 'like', "%$keyword%")->count();
                    } else {
                        $data = ClinicalPathway::field('clinical_pathway as name')
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = ClinicalPathway::field('clinical_pathway as name')->count();
                    }
                    break;
                case "ClinicalTrial":
                    if ($keyword) {
                        /**
                         * 临床试验查询mysql
                         */
                        $data = ClinicalTrial::field('adaptation_disease as name , register_number')
                            ->where("drug_name", "like", "%$keyword%")
                            ->whereOr("adaptation_disease", "like", "%$keyword%")
                            ->whereOr("experimental_popular_topic", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = ClinicalTrial::field('adaptation_disease as name , register_number')
                            ->where("drug_name", "like", "%$keyword%")
                            ->whereOr("adaptation_disease", "like", "%$keyword%")
                            ->whereOr("experimental_popular_topic", "like", "%$keyword%")
                            ->count();
                    } else {
                        /**
                         * 临床试验查询mysql
                         */
                        $data = ClinicalTrial::field('adaptation_disease as name , register_number')->limit($limit, $pagesize)->select()->toArray();
                        $count = ClinicalTrial::field('adaptation_disease as name , register_number')->count();
                    }
                    break;
                case "Mission":
                    $data = Mission::where($where)->where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = Mission::where($where)->where('name', 'like', "%$keyword%")->count();
                    break;
                case "XyPrescription":  //西医处方
                    $data = XyPrescription::where($where)->where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = XyPrescription::where($where)->where('name', 'like', "%$keyword%")->count();
                    break;
                case "Xyhl":  //西医护理
                    $data = Xyhl::where($where)->where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = Xyhl::where($where)->where('name', 'like', "%$keyword%")->count();
                    break;
                case "Zztz": //症状体征
                    $data = Zztz::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = Zztz::where('name', 'like', "%$keyword%")->count();
                    break;
                case "LawRegulations": //法律法规
                    $data = LawRegulations::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = LawRegulations::where('name', 'like', "%$keyword%")->count();
                    break;
                case "Disease":
                    if ($keyword) {
                        /**
                         * 西医科室疾病
                         */
                        $data = CdssDisease::field('name,department_1,department_2')
                            ->where($where)
                            ->where("name", "like", "%$keyword%")
                            ->whereOr("alias", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = CdssDisease::field('name,department_1,department_2')
                            ->where($where)
                            ->where("name", "like", "%$keyword%")
                            ->whereOr("alias", "like", "%$keyword%")->count();
                    } else {
                        /**
                         * 西医科室疾病
                         */
                        $data = CdssDisease::field('name,department_1,department_2')->where($where)->limit($limit, $pagesize)->select()->toArray();
                        $count = CdssDisease::field('name,department_1,department_2')->where($where)->count();
                    }
                    break;
                case "Ferri":
                    $data = Ferri::field('name')->where($where)->where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = Ferri::field('name')->where($where)->where('name', 'like', "%$keyword%")->count();
                    break;
                case "cases":
                    $data = Cases::field('disease_name as name,document_name')->where('disease_name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = Cases::field('disease_name as name,document_name')->where('disease_name', 'like', "%$keyword%")->count();
                    break;
                case "MedicineProduction":
                    if ($keyword) {
                        /**
                         * 西医药品
                         */
                        $data = CdssMedicine::field('id,name,productionEnterprise')
                            ->where("relateSick", "like", "%$keyword%")
                            ->whereOr("name", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->group('name,productionEnterprise')
                            ->select()
                            ->toArray();
                        $count = CdssMedicine::field('id,name,productionEnterprise')
                            ->where("relateSick", "like", "%$keyword%")
                            ->whereOr("name", "like", "%$keyword%")
                            ->group('name,productionEnterprise')
                            ->count();
                    } else {
                        /**
                         * 西医药品
                         */
                        $data = CdssMedicine::field('id,name,productionEnterprise')
                            ->limit($limit, $pagesize)
                            ->group('name,productionEnterprise')
                            ->select()
                            ->toArray();
                        $count = CdssMedicine::field('id,name,productionEnterprise')->group('name,productionEnterprise')->count();
                    }
                    break;
                case "MedicalInsuranceDrugEn":
                    $data = GjybypmlEn::field('name')->where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = GjybypmlEn::field('name')->where('name', 'like', "%$keyword%")->count();
                    break;
                case "essentialDrugs":   //国家基础药物
                    if ($keyword) {
                        $data = EssentialDrugs::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = EssentialDrugs::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->count();
                    } else {
                        $data = EssentialDrugs::field('name')
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = EssentialDrugs::field('name')->count();
                    }
                    break;
                case "DrugOverdose":   //超用药
                    if ($keyword) {
                        $data = DrugOverdose::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = DrugOverdose::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->count();
                    } else {
                        $data = DrugOverdose::field('name')
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = DrugOverdose::field('name')->count();
                    }
                    break;
                case "DrugAnswers":   //药品问答
                    if ($keyword) {
                        $data = DrugAnswers::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = DrugAnswers::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->count();
                    } else {
                        $data = DrugAnswers::field('name')
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = DrugAnswers::field('name')->count();
                    }
                    break;
                case "Inspection":
                    if ($keyword) {
                        /**
                         * 西医检查
                         */
                        $data = CdssInspection::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = CdssInspection::field('name')
                            ->where("name", "like", "%$keyword%")->count();
                    } else {
                        /**
                         * 西医检查
                         */
                        $data = CdssInspection::field('name')
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = CdssInspection::field('name')->count();
                    }

                    break;
                /**
                 * 症状
                 */
                case 'Symptom':
                    if ($keyword) {
                        $data = Symptom::field('name')
                            ->where("disease", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = Symptom::field('name')->where("disease", "like", "%$keyword%")->count();
                    } else {
                        $data = Symptom::field('name')
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = Symptom::field('name')->count();
                    }
                    break;
                /**
                 * 手术操作
                 */
                case "Operation":
                    $data = Operation::field('operation_name as name')
                        ->where("operation_name", "like", "%$keyword%")
                        ->limit($limit, $pagesize)
                        ->select()
                        ->toArray();
                    $count = Operation::field('operation_name as name')->where("operation_name", "like", "%$keyword%")->count();
                    break;
                /**
                 * 诊疗指南
                 */
                case "DiagnosisTreatment":
                    $data = GetGuide::limit($limit, $pagesize)->order('publishDate', 'desc')->select()->toArray();
                    $count = GetGuide::count();
                    //$data  = GetGuideMent::where('name' ,'like' , "%$keyword%")->limit($limit , $pagesize)->select()->toArray();
                    //$count = GetGuideMent::where('name' ,'like' , "%$keyword%")->count();

                    //                    $data = GetGuide ::field('title_trans as name,id')
//                        ->where("keyword_cn"       , "like" , "%$keyword%" )
//                        ->whereOr("keyword"        , "like" , "%$keyword%" )
//                        ->whereOr("title"          , "like" , "%$keyword%" )
//                        ->whereOr("title_trans"    , "like" , "%$keyword%" )
//                        ->order('publish_time'  , 'DESC')
//                        ->limit($limit , $pagesize)
//                        ->select()
//                        ->toArray();
//                    $count = GetGuide ::field('title_trans as name,id')
//                        ->where("keyword_cn"       , "like" , "%$keyword%" )
//                        ->whereOr("keyword"        , "like" , "%$keyword%" )
//                        ->whereOr("title"          , "like" , "%$keyword%" )
//                        ->whereOr("title_trans"    , "like" , "%$keyword%" )
//                        ->count();
                    break;
                case "GuideMap":
                    /**
                     * 指南脑图
                     */
                    $data = [
                        ['name' => 'csco食管癌诊疗指南2022脑图', 'tag' => 'zh'],
                        ['name' => 'nccn食管癌诊疗指南2022v2脑图（中文）', 'tag' => 'en']
                    ];

                    break;

                case "GuideStructure":
                    /**
                     * 指南结构化
                     */
                    $data = [
                        ['name' => 'nccn食管癌诊疗指南2022v2（中文）']
                    ];
                    break;
                case 'Antidiastole':
                    if ($keyword) {
                        /**
                         * 误诊误治（鉴别诊断）
                         */
                        $data = CdssXyDisease::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = CdssXyDisease::field('name')->where("name", "like", "%$keyword%")->count();
                    } else {
                        /**
                         * 误诊误治（鉴别诊断）
                         */
                        $data = CdssXyDisease::field('name')
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = CdssXyDisease::field('name')->count();
                    }

                    break;
                case "DrugTarget":
                    /**
                     * 药物靶点
                     */
                    $data = [
                        ['name' => '食管��'],
                    ];
                    break;
                case "Acupoint":
                    $data = ZyAcupoint::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = ZyAcupoint::where('name', 'like', "%$keyword%")->count();
                    break;

                case "zyxdya":
                    $data = Zyxdya::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = Zyxdya::where('name', 'like', "%$keyword%")->count();
                    break;

                case "CnMedicinalCrop":
                    $data = ZyMedicinalCrop::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = ZyMedicinalCrop::where('name', 'like', "%$keyword%")->count();
                    break;

                case "CnPatentMedicine":
                    $data = ZyPatentMedicine::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = ZyPatentMedicine::where('name', 'like', "%$keyword%")->count();
                    break;
                case "MedicalInsuranceDrugZh":
                    $data = GjybypmlZh::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = GjybypmlZh::where('name', 'like', "%$keyword%")->count();
                    break;
                case "Prescription":
                    $data = ZyPrescription::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = ZyPrescription::where('name', 'like', "%$keyword%")->count();
                    break;

                case "TonicDiet":
                    $data = ZyTonicDiet::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = ZyTonicDiet::where('name', 'like', "%$keyword%")->count();
                    break;

                case "ChannelCollateral":
                    $data = ZyChannelSymptom::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = ZyChannelSymptom::where('name', 'like', "%$keyword%")->count();
                    break;

                case "zySickNess":
                    $data = ZySickness::where('name', 'like', "%$keyword%")->where($where)->limit($limit, $pagesize)->select()->toArray();
                    $count = ZySickness::where('name', 'like', "%$keyword%")->where($where)->count();
                    break;
                case "SickNess":
                    $data = XySickNess::where($where)->where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = XySickNess::where($where)->where('name', 'like', "%$keyword%")->count();
                    break;
                case "Constitution":
                    $data = ZyConstitution::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = ZyConstitution::where('name', 'like', "%$keyword%")->count();
                    break;
                case "zygdya":
                    $data = Zygdya::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = Zygdya::where('name', 'like', "%$keyword%")->count();
                    break;
                case "zyjbbz":
                    $data = Zyjbbz::where('name', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = Zyjbbz::where('name', 'like', "%$keyword%")->count();
                    break;
                case "zyfywlf":
                    try {

                        // 执行查询
                        $data = Zyfywlf::where('name', 'like', "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();

                        $count = Zyfywlf::where('name', 'like', "%$keyword%")->count();



                    } catch (\Exception $e) {
                        trace("Error in zyfywlf case: " . $e->getMessage());
                        throw $e;
                    }
                    break;
                case "zhguide":
                    $data = GetZhGuide::where('documentName', 'like', "%$keyword%")->limit($limit, $pagesize)->select()->toArray();
                    $count = GetZhGuide::where('documentName', 'like', "%$keyword%")->count();
                    break;
                /**
                 * 症状
                 */
                case 'ZhSymptom':
                    if ($keyword) {
                        $data = ZhSymptom::field('name')
                            ->where("name", "like", "%$keyword%")
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = ZhSymptom::field('name')->where("name", "like", "%$keyword%")->count();
                    } else {
                        $data = ZhSymptom::field('name')
                            ->limit($limit, $pagesize)
                            ->select()
                            ->toArray();
                        $count = ZhSymptom::field('name')->count();
                    }
                    break;
            }
            //return $this->_json_succ($data);
            $baseurl = Config::get('app.base_url');
            foreach ($data as $key => $val) {

                $data[$key]['description'] = DiseaseCategoryProperties::getValueByTag($tag, $type);
                if ('ClinicalPathway' === $tag) {
                    //$data[$key]['file'] = $this->checkDocPdfIsExist('http://jm.jiankangche.cn/lcljpdf/'.$val['name'].'.pdf');
                    $data[$key]['file'] = $this->checkDocPdfIsExist($baseurl . '/lcljpdf/' . $val['name'] . '.pdf');
                } elseif ('ClinicalTrial' === $tag) {
                    $data[$key]['file'] = $this->checkDocPdfIsExist($baseurl . '/lcsyword/' . $val['register_number'] . '详细信息.pdf');
                } elseif ('Ferri' === $tag) {
                    $data[$key]['file'] = $baseurl . '/ferri/' . $val['name'] . '.pdf';
                } elseif ($tag === 'cases') {
                    $data[$key]['file'] = $this->checkDocPdfIsExist($baseurl . '/cases/' . $val['document_name'] . '.pdf');
                } elseif ($tag === 'DiagnosisTreatment') {
                    $data[$key]['name'] = $val['documentName'];
                    $data[$key]['file'] = $baseurl . '/lcznpdf/' . $val['documentName'] . '.pdf';
                } elseif ($tag === 'zhguide') {
                    $data[$key]['name'] = $val['documentName'];
                    $data[$key]['file'] = $baseurl . '/lcznzh/' . $val['documentName'] . '.pdf';
                } elseif ($tag === 'Mission' && $val['format'] == 'pdf') {
                    $data[$key]['file'] = $this->checkDocPdfIsExist($baseurl . '/mission/mission/' . $val['name'] . '.pdf');
                } elseif ($tag === 'MedicineProduction') {
                    $data[$key]['description'] = $val['productionEnterprise'];
                } elseif ($tag === 'LawRegulations') {
                    $data[$key]['file'] = $this->checkDocPdfIsExist($baseurl . '/law/' . $val['name'] . '.pdf');
                } else {
                    $data[$key]['file'] = '';
                }
            }
            //return $this->_json_succ($data);	
            $lists[$tag] = $data;
        }

        $count = $count ?? 1;
        return $this->_json_succ(
            [
                'data' => $lists,
                'count' => $count,
                'total_page' => ceil($count / $pagesize),
            ]
        );
    }


    /**
     * 临床试验
     */
    public function getClinicalTrial()
    {
        $params = Request::only(
            [
                'page',
                'keyword'
            ]
        );

        $keyword = $params['keyword'] ?? '';
        $page = $params['page'] ?? 1;
        $pagesize = 10;
        $limit = ($page - 1) * $pagesize;

        if ($keyword) {
            $ClinicalTrial = ClinicalTrial::where("drug_name", "like", "%$keyword%")
                ->whereOr("adaptation_disease", "like", "%$keyword%")
                ->whereOr("experimental_popular_topic", "like", "%$keyword%")
                ->whereOr("register_number", "like", "%$keyword%")
                ->limit($limit, $pagesize)
                ->select() ?? [];
            //foreach ($ClinicalTrial as $key => $value) {
            //    $ClinicalTrial[$key]['file'] = $this->checkDocPdfIsExist('http://jm.jiankangche.cn/clinical/clinicalword/'.$value['register_number'].'详细信息.doc');
            //}

            $total = ClinicalTrial::where("drug_name", "like", "%$keyword%")
                ->whereOr("adaptation_disease", "like", "%$keyword%")
                ->whereOr("experimental_popular_topic", "like", "%$keyword%")
                ->whereOr("register_number", "like", "%$keyword%")
                ->count();
            $totalPage = ceil($total / $pagesize);
        } else {
            $ClinicalTrial = ClinicalTrial::limit($limit, $pagesize)->select() ?? [];
            //foreach ($ClinicalTrial as $key => $value) {
            //    $ClinicalTrial[$key]['file'] = $this->checkDocPdfIsExist('http://jm.jiankangche.cn/clinical/clinicalword/'.$value['register_number'].'详细信息.doc');
            //}
            $total = ClinicalTrial::count();
            $totalPage = ceil($total / $pagesize);
        }

        return $this->_json_succ(
            [
                'list' => $ClinicalTrial,
                'total' => $total,
                'total_page' => $totalPage
            ]
        );
    }

    /**
     *  药物相互作用
     */
    public function getInteract()
    {
        $params = Request::only(['page', 'keyword']);

        $keyword = $params['keyword'] ?? '';
        $page = $params['page'] ?? 1;
        $pagesize = 10;
        $limit = ($page - 1) * $pagesize;

        if ($keyword) {
            $ClinicalTrial = Interact::where("A_medicine", "like", "%$keyword%")
                ->whereOr("B_medicine", "like", "%$keyword%")
                ->limit($limit, $pagesize)
                ->select() ?? [];

            $total = Interact::where("A_medicine", "like", "%$keyword%")
                ->whereOr("B_medicine", "like", "%$keyword%")
                ->count();
            $totalPage = ceil($total / $pagesize);
        } else {

            $ClinicalTrial = Interact::limit($limit, $pagesize)->select() ?? [];

            $total = Interact::count();
            $totalPage = ceil($total / $pagesize);
        }

        return $this->_json_succ(
            [
                'list' => $ClinicalTrial,
                'total' => $total,
                'total_page' => $totalPage
            ]
        );
    }

    //多个检查检验详情
    public function detailmultiple()
    {
        $params = $this->request->all();
        //中联字段
        $zhonglian_name = $params['zhonglian_name'] ?? '';
        $tag = $params['tag'] ?? 'Disease';
        $model = '\app\model\CdssInspection';
        $table = 'jm_cdss_inspection';

        if ($zhonglian_name) {
            $value = $zhonglian_name;
            $field = 'zhonglian_name';
        }
        $values = explode(',', $value);

        $sql = "show full columns from {$table}";
        $res = Db::query($sql);

        $detail = [];
        //foreach ($values as $k => $v) {
//            $detail[] = $model::where($field, $v)->find();
        //   $detail[] = $model::whereRaw('FIND_IN_SET(?, zhonglian_name)', [$v])->find();
        //}

        $aa = [];
        foreach ($values as $k => $v) {
            //            $detail[] = $model::where($field, $v)->find();
            $aa = $model::whereRaw('FIND_IN_SET(?, zhonglian_name)', [$v])->find();
            if (!empty($aa)) {
                foreach ($res as $val) {
                    $aa[$val['Field']] = [
                        'name' => $val['Comment'],
                        'text' => $aa[$val['Field']] ?? ''
                    ];
                    //foreach ($aa as $k => $v) {
                    //    $v[$val['Field']] = [
                    //        'name' => $val['Comment'],
                    //        'text' => $v[$val['Field']] ?? ''
                    //    ];
                    //    unset($v['id']);
                    //    unset($v['productionEnterprise']);
                    //}

                }
                $detail[] = $aa;
            }
        }
        return $this->_json_succ($detail);

    }

    /**
     * 知识库详情（mysql）
     *
     * date 2022/12/19
     * @param  $tag   string  标识
     * @param  $name  string  名称
     * @return
     */
    public function detail()
    {

        $params = $this->request->all();


        $tag = $params['tag'] ?? 'Disease';
        $value = $params['name'] ?? '';
        $id = $params['id'] ?? '';
        //对接东华加的字段
        $donghua_name = $params['donghua_name'] ?? '';
        //中联字段
        $zhonglian_name = $params['zhonglian_name'] ?? '';
        $productionEnterprise = $params['productionEnterprise'] ?? '';

        //ip访问限制
        #$ip = $_SERVER['REMOTE_ADDR'];
        #$today = date('Y-m-d');
        #$row = IpAccessLog::field('access_count')->where('ip_address',$ip)->where('date',$today)->find();
        #if ($row) {
        #    $acccount = $row['access_count'] + 1;
        #    if ($acccount > 20) {
        #        return $this->_json_error('访问超次数');
        #    } else {
        #        IpAccessLog::where('ip_address',$ip)->where('date',$today)->update(['access_count'=>$acccount]);
        #    }
        #}else { // 如果记录不存在，插入新记录
        #    IpAccessLog::insert(['ip_address'=>$ip,'access_count'=>1,'date'=>$today]);
        #    //echo json_encode(['message' => 'Access granted']);
        #}

        if (!$tag) {
            return $this->_json_error('参数错误！');
        }

        switch ($tag) {
            /**
             * 西医部分
             */
            case 'Disease':
                $model = '\app\model\CdssDisease';
                $table = 'jm_cdss_xy_disease';
                $field = 'name';
                break;
            case 'MedicineProduction':
                $model = '\app\model\CdssMedicine';
                $table = 'jm_cdss_medicine';
                if (empty($id) || $id == 'undefined') {
                    if (empty($donghua_name)) {
                        $field = 'name';
                    } else {
                        $value = $donghua_name;
                        $field = 'donghua_medicine_name';
                    }
                } else {
                    $value = $id;
                    $field = 'id';
                }
                break;
            case 'MedicalInsuranceDrugEn':
                $model = '\app\model\GjybypmlEn';
                $table = 'jm_cdss_gjybypmlen';
                $field = 'name';
                break;
            case 'essentialDrugs':
                $model = '\app\model\EssentialDrugs';
                $table = 'jm_cdss_essential_drugs';
                $field = 'name';
                break;
            case 'DrugOverdose':
                $model = '\app\model\DrugOverdose';
                $table = 'jm_cdss_Drug_Overdose';
                $field = 'name';
                break;
            case 'DrugAnswers':
                $model = '\app\model\DrugAnswers';
                $table = 'jm_cdss_drug_answers';
                $field = 'name';
                break;
            case 'Inspection':
                $model = '\app\model\CdssInspection';
                $table = 'jm_cdss_inspection';
                if (empty($donghua_name) && empty($zhonglian_name)) {
                    $field = 'name';
                } else {
                    if ($donghua_name) {
                        $value = $donghua_name;
                        $field = 'donghua_name';
                    }
                    if ($zhonglian_name) {
                        $value = $zhonglian_name;
                        $field = 'zhonglian_name';
                    }
                }
                break;
            case 'Operation':
                $model = '\app\model\Operation';
                $table = 'jm_operation';
                $field = 'operation_name';
                break;
            case 'Symptom':
                $model = '\app\model\Symptom';
                $table = 'jm_symptom';
                $field = 'name';
                break;
            case 'Antidiastole':
                $model = '\app\model\CdssDisease';
                $table = 'jm_cdss_xy_disease';
                $field = 'name';
                break;
            case 'SickNess':
                $model = '\app\model\XySickNess';
                $table = 'jm_xy_sickness';
                $field = 'name';
                break;
            case 'Mission':
                $model = '\app\model\Mission';
                $table = 'jm_xy_mission';
                $field = 'name';
                break;
            case 'XyPrescription':
                $model = '\app\model\XyPrescription';
                $table = 'jm_xy_prescription';
                $field = 'name';
                break;
            case 'Xyhl':
                $model = '\app\model\Xyhl';
                $table = 'jm_xy_xyhl';
                $field = 'name';
                break;
            case 'Zztz':
                $model = '\app\model\Zztz';
                $table = 'jm_xy_zztz';
                $field = 'name';
                break;
            /**
             * 中医疾病
             */
            case 'zySickNess':
                $model = '\app\model\ZySickness';
                $table = 'jm_zh_sickness';
                $field = 'dialecticalName';
                break;
            /**
             * 中药
             */
            case 'CnMedicinalCrop':
                $model = '\app\model\ZyMedicinalCrop';
                $table = 'jm_zh_medicinal_crop';
                $field = 'name';
                break;
            /**
             * 中成药
             */
            case 'CnPatentMedicine':
                $model = '\app\model\ZyPatentMedicine';
                $table = 'jm_zh_patent_medicine';
                $field = 'name';
                break;
            /**
             * 国家医保名录中成药
             */
            case 'MedicalInsuranceDrugZh':
                $model = '\app\model\GjybypmlZh';
                $table = 'jm_zh_gjybypml';
                $field = 'name';
                break;
            /**
             * 方剂
             */
            case 'Prescription':
                $model = '\app\model\ZyPrescription';
                $table = 'jm_zh_prescription';
                $field = 'name';
                break;
            /**
             * 药膳
             */
            case 'TonicDiet':
                $model = '\app\model\ZyTonicDiet';
                $table = 'jm_zh_tonicdiet';
                $field = 'name';
                break;
            /**
             * 体质
             */
            case 'Constitution':
                $model = '\app\model\ZyConstitution';
                $table = 'jm_zh_constitution';
                $field = 'name';
                break;
            /**
             * 经络
             */
            case 'ChannelCollateral':
                $model = '\app\model\ZyChannelSymptom';
                $table = 'jm_zh_channel_symptom';
                $field = 'name';
                break;
            /**
             * 学位
             */
            case 'Acupoint':
                $model = '\app\model\ZyAcupoint';
                $table = 'jm_zh_acupoint';
                $field = 'name';
                break;
            case 'zyxdya':
                $model = '\app\model\Zyxdya';
                $table = 'jm_zh_zyxdya';
                $field = 'name';
                break;
            case 'zygdya':
                $model = '\app\model\Zygdya';
                $table = 'jm_zh_zygdya';
                $field = 'name';
                break;
            case 'zyjbbz':
                $model = '\app\model\Zyjbbz';
                $table = 'jm_zh_zyjbbz';
                $field = 'name';
                break;
            case 'zyfywlf':
                $model = '\app\model\Zyfywlf';
                $table = 'jm_zh_zyfywlf';
                $field = 'name';
                break;
            case 'ZhSymptom':
                $model = '\app\model\ZhSymptom';
                $table = 'jm_zh_symptom';
                $field = 'name';
                break;
        }

        if (stripos($value, ',') !== false) {
            //多个药品查询
            $values = explode(',', $value);
            $detail = CdssDisease::jointZskDetailFieds($table, $model, $field, $values);
        } else {
            $detail = CdssDisease::jointZskDetailFieds($table, $model, $field, $value);
            if (isset($detail['operation_name'])) {
                $detail['name'] = $detail['operation_name'];
            }

            if ($tag == 'Mission') {
                unset($detail['format']);
            }

            if ($tag == 'Inspection') {
                $a[] = $detail;
                $detail = $a;
            }

            if ('Antidiastole' === $tag) {
                return $this->_json_succ(
                    [
                        'name' => $detail['name'],
                        'antidiastole' => $this->replaceStr($detail['antidiastole'])
                    ]
                );
            }
        }
        return $this->_json_succ(
            $detail
        );
    }

    function buildHierarchy(array $data)
    {
        $result = [];

        foreach ($data as $item) {
            $level1 = $item['department'];
            $level2 = $item['department_2'];
            $level3 = $item['department_3'];
            $level4 = $item['department_4'];
            $level5 = $item['department_5'];

            // 构建多层级结构
            if (!isset($result[$level1])) {
                $result[$level1] = ['children' => []];
            }

            if (!empty($level2)) {
                if (!isset($result[$level1]['children'][$level2])) {
                    $result[$level1]['children'][$level2] = ['children' => []];
                }

                if (!empty($level3)) {
                    if (!isset($result[$level1]['children'][$level2]['children'][$level3])) {
                        $result[$level1]['children'][$level2]['children'][$level3] = ['children' => []];
                    }

                    if (!empty($level4)) {
                        if (!isset($result[$level1]['children'][$level2]['children'][$level3]['children'][$level4])) {
                            $result[$level1]['children'][$level2]['children'][$level3]['children'][$level4] = ['children' => []];
                        }

                        if (!empty($level5)) {
                            $result[$level1]['children'][$level2]['children'][$level3]['children'][$level4]['children'][$level5] = [];
                        }
                    }
                }
            }
        }

        return $result;
    }


    public function getDepartments()
    {

        $tag = Request::param('tag');
        $partment1 = Request::param('partment');
        $partment2 = Request::param('partment_2');
        $partment3 = Request::param('partment_3');
        $partment4 = Request::param('partment_4');
        $where = [];
        switch ($tag) {
            case "zySickNess":
                $data = ZySickness::field('department')->where('department', '<>', '')->group('department')->column('department');
                break;
            case "Ferri":
                $data = Ferri::field('department')->where('department', '<>', '')->group('department')->column('department');
                break;
            case "Inspection": //检验检查
                $data = CdssInspection::field('department')->where('department', '<>', '')->group('department')->column('department');
                break;
            case "Operation": //手术操作
                $data = Operation::field('department')->where('department', '<>', '')->group('department')->column('department');
                break;
            case "CdssMedicineMl": //西医目录
                $list = CdssMedicineMl::field('department,department_2,department_3,department_4,department_5')->group('department,department_2,department_3,department_4,department_5')->select()->toArray();
                $data = $this->buildHierarchy($list);
                break;
            case "Disease": //医疗疾病
                $list = CdssXyDisease::field('department_1 as department,department_2')->where('department_1', '<>', '')->group('department_1,department_2')->select()->toArray();
                $data = $this->buildHier($list);
                // 初始化结果数组
//                $result = [];
//                foreach ($data as $item) {
//                    $department1 = $item['department_1'];
//                    $department2 = $item['department_2'];
//
//                    if (!isset($result[$department1])) {
//                        $result[$department1] = [
//                            'department_1' => $department1,
//                            'department_2' => []
//                        ];
//                    }
//                    $result[$department1]['department_2'][] = $department2;
//                }
//                // 将结果转换为数组
//                $resultArray = array_values($result);
                break;

        }

        $result[]['department'] = $data;
        return $this->_json_succ($result);
    }

    function buildHier(array $data)
    {
        $result = [];

        foreach ($data as $item) {
            $level1 = $item['department'];
            $level2 = $item['department_2'];

            // 构建多层级结构
            if (!isset($result[$level1])) {
                $result[$level1] = ['children' => []];
            }
            if (!empty($level2)) {
                if (!isset($result[$level1]['children'][$level2])) {
                    $result[$level1]['children'][$level2] = ['children' => []];
                }
            }
        }
        return $result;
    }

    public function replaceStr($text)
    {
        $searchStr = [
            ' 1.',
            ' 2.',
            ' 3.',
            ' 4.',
            ' 5.',
            ' 6.',
            ' 7.',
            ' 8.',
            ' 9.',
            ' 10.',
            ' 11.',
            '(1)',
            '(2)',
            '(3)',
            '(4)',
            '0级',
            'Ⅰ级',
            'Ⅱ级',
            '���级',
            'Ⅳ级',
            '①',
            '②',
            '③',
            '④',
            '⑤',
            '⑥',
            '⑦',
            '•',
            '一、',
            '二、',
            '三、',
            '四、',
            '(一)',
            '(二)',
            '(三)',
            '(四)'
        ];
        $replaceStr = [
            "\r\n1.",
            "\r\n2.",
            "\r\n3.",
            "\r\n4.",
            "\r\n5.",
            "\r\n6.",
            "\r\n7.",
            "\r\n8.",
            "\r\n9.",
            "\r\n10.",
            "\r\n\t(1)",
            "\r\n\t(2)",
            "\r\n\t(3)",
            "\r\n\t(4)",
            "\r\n\t0级",
            "\r\n\tⅠ级",
            "\r\n\tⅡ级",
            "\r\n\tⅢ级",
            "\r\n\tⅢ级",
            "\r\n\tⅣ级",
            "\r\n\t①",
            "\r\n\t②",
            "\r\n\t③",
            "\r\n\t④",
            "\r\n\t⑤",
            "\r\n\t⑥",
            "\r\n\t⑦",
            "\r\n\t•",
            "\r\n\t\t一、",
            "\r\n\t\t二、",
            "\r\n\t\t三、",
            "\r\n\t\t四、",
            "\r\n\t\t\t(一)",
            "\r\n\t\t\t(二)",
            "\r\n\t\t\t(三)",
            "\r\n\t\t\t(四)",
        ];
        return str_replace($searchStr, $replaceStr, $text);
    }



    private function checkDocPdfIsExist($url)
    {
        $check = get_headers($url);
        return stripos($check[0], '200') !== false ? $url : "";
    }


    /**
     * Cdss 诊断
     *
     * @return Json
     */
    public function getDiagnosisField(): Json
    {
        return $this->_json_succ(Diagnosis::select() ?? []);
    }


    /**
     * 获取疾病icd10
     *
     * @param string $name
     * @return Json
     */
    public function getIcdByDiagnosis(): Json
    {
        if (!$name = input('post.name')) {
            return $this->_json_error('请求参数有误！');
        }

        $icdData = CdssXyDisease::field('icd')->where('name', $name)->find();
        return $this->_json_succ(
            $icdData ?? []
        );
    }


    /**
     * 关键字匹配相关疾病
     *
     * @param string $keyword
     * @return Json
     */
    public function getDiseaseByKeyword()
    {
        if (!$keyword = input('post.keyword')) {
            return $this->_json_error('请求参数有误！');
        }

        $names = CdssXyDisease::field('name')->where('name', 'like', "%$keyword%")->select()->toArray();
        $nameArr = $names ? array_column($names, 'name') : [];
        return $this->_json_succ(
            $nameArr
        );
    }


    /**
     * 根据临床表现获取症状（nlp接口）
     */
    public function getSymptomByClinicalFeature()
    {
        $pagesize = 1000;
        $page = Request::param('page') ?? 1;
        $limit = ($page - 1) * $pagesize;
        $list = CdssXyDisease::field('clinicalFeature , id')->limit($limit, $pagesize)->select()->toArray();

        $url = "http://121.36.94.218:10090/disease/ner/predict?sentence=";
        foreach ($list as $key => $value) {
            $url1 = $url . urlencode($value['clinicalFeature']);
            $result = file_get_contents($url1);
            $data = json_decode($result, true);
            $symptoms = $data['data']['symptom'] ?? '';

            if ($symptoms) {
                $diseaseSymptoms = implode(',', array_column($symptoms, 'entity'));
                CdssXyDisease::where('id', $value['id'])->update(
                    [
                        'symptom' => $diseaseSymptoms
                    ]
                );
            }
        }
    }


    /**
     * 从疾病的临床表现匹配症状
     */
    public function matchClinicalFeature()
    {
        $values = Request::param('symptom') ?? '';
        if (!$values) {
            return $this->_json_error('请求参数错误！');
        }

        if (stripos($values, ',') !== false) {
            $symptoms = explode(',', $values);
            foreach ($symptoms as $key => $symptom) {
                $arr[$key] = '%' . $symptom . '%';
            }
            $aboutDiseases = CdssXyDisease::field('clinicalFeature,name')->where('clinicalFeature', 'like', $arr, 'OR')->limit(200)->select()->toArray() ?? [];
        } else {
            $aboutDiseases = CdssXyDisease::field('clinicalFeature,name')->whereLike('clinicalFeature', '%' . $values . '%')->limit(200)->select()->toArray() ?? [];
        }
        return $this->_json_succ($aboutDiseases);
    }

    //获取症状体征
    public function getXyzztz()
    {
        $name = Request::param('name') ?? '';
        if (empty($name)) {
            return $this->_json_error('name不能为空');
        }

        $data = Zztz::where('name', 'like', "%$name%")->column('id,name,department');
        return $this->_json_succ($data);
    }

    /**
     * 医嘱审核
     * @param array $params
     * @return array
     */
    public function yzEamine(array $params): array
    {
        // 查询医嘱审核规则,使用like进行模糊查询
        $rule = Db::table('jm_knowledge_rule')
            ->whereLike('name', '%' . $params['name'] . '%')
            ->where('gender', $params['gender'])
            ->find();

        return $rule ?: [];
    }

    /**
     * 获取中医疾病相关信息
     * @return Json
     */
    public function getZhInspectionOrMedicineByDisease(): Json
    {
        $diseaseName = Request::param('disease_name');
        $dialecticalName = Request::param('dialectical_name');

        if (!$diseaseName || !$dialecticalName) {
            return $this->_json_error('疾病名称和证型不能为空！');
        }

        // 同时匹配疾病名称和证型
        $diseases = ZySickness::where([
            ['name', '=', $diseaseName],
            ['dialecticalName', '=', $dialecticalName]
        ])->select()->toArray();

        if (empty($diseases)) {
            return $this->_json_error('未找到相关疾病信息');
        }

        // 初始化数组用于存储合并后的数据
        $mergedData = [
            'symptom_list' => [],
            'therapeutic_list' => [],
            'medicine_list' => [],
            'prescription_list' => [],
            'diet_list' => [],
            'tonic_list' => [],
            'acupoint_list' => [],
            'tongue_condition' => $diseases[0]['tongueCondition'],
            'pulse_condition' => $diseases[0]['pulseCondition']
        ];

        // 用于存储已存在的项，避免重复
        $existingItems = [
            'symptom' => [],
            'therapeutic' => [],
            'medicine' => [],
            'prescription' => [],
            'diet' => [],
            'tonic' => [],
            'acupoint' => []
        ];

        foreach ($diseases as $disease) {
            // 处理症状列表
            $symptoms = array_filter(explode('，', $disease['symptom'])); // 使用中文逗号分割
            foreach ($symptoms as $symptom) {
                if (!in_array($symptom, $existingItems['symptom'])) {
                    $mergedData['symptom_list'][] = ['name' => trim($symptom)]; // 添加trim去除可能的空格
                    $existingItems['symptom'][] = trim($symptom);
                }
            }

            // 处理治法原则
            $therapeutics = array_filter(explode('，', $disease['therapeuticMethod']));
            foreach ($therapeutics as $therapeutic) {
                if (!in_array($therapeutic, $existingItems['therapeutic'])) {
                    $mergedData['therapeutic_list'][] = ['name' => trim($therapeutic)];
                    $existingItems['therapeutic'][] = trim($therapeutic);
                }
            }

            // 处理中成药
            $medicines = array_filter(explode('，', $disease['cnPatentMedicine']));
            foreach ($medicines as $medicine) {
                if (!in_array($medicine, $existingItems['medicine'])) {
                    $mergedData['medicine_list'][] = ['name' => trim($medicine)];
                    $existingItems['medicine'][] = trim($medicine);
                }
            }

            // 处理方剂
            $prescriptions = array_filter(explode('，', $disease['prescription']));
            foreach ($prescriptions as $prescription) {
                if (!in_array($prescription, $existingItems['prescription'])) {
                    $mergedData['prescription_list'][] = ['name' => trim($prescription)];
                    $existingItems['prescription'][] = trim($prescription);
                }
            }

            // 处理食疗
            $diets = array_filter(explode('，', $disease['dietTherapy']));
            foreach ($diets as $diet) {
                // 清理数据：去除换行符，并按换行符分割
                $dietItems = explode("\n", trim($diet));
                // 去重
                $dietItems = array_unique($dietItems);

                foreach ($dietItems as $item) {
                    $item = trim($item);
                    // 去除空值
                    if (!empty($item) && !in_array($item, $existingItems['diet'])) {
                        $mergedData['diet_list'][] = ['name' => $item];
                        $existingItems['diet'][] = $item;
                    }
                }
            }

            // 处理药膳
            $tonics = array_filter(explode('，', $disease['tonicDiet']));
            foreach ($tonics as $tonic) {
                if (!in_array($tonic, $existingItems['tonic'])) {
                    $mergedData['tonic_list'][] = ['name' => trim($tonic)];
                    $existingItems['tonic'][] = trim($tonic);
                }
            }

            // 处理针灸穴位
            $acupoints = array_filter(explode('，', $disease['acupuncturePoints']));
            foreach ($acupoints as $acupoint) {
                if (!in_array($acupoint, $existingItems['acupoint'])) {
                    $mergedData['acupoint_list'][] = ['name' => trim($acupoint)];
                    $existingItems['acupoint'][] = trim($acupoint);
                }
            }
        }

        return $this->_json_succ($mergedData);
    }
}
