<?php
namespace app\controller;

use app\model\CdssDisease;
use app\model\ClinicalPathway;
use app\model\DocumentImages;
use app\model\MindMapzh;
use app\model\Omics;
use app\model\Operation;
use app\model\XySickNess;
use app\model\XyZskInspection;
use app\model\XyZskMedicine;
use app\model\ZySickness;
use think\response\Json;
use think\facade\Request;
use app\model\DiseaseProperties;
use app\model\DiseaseCategoryProperties;
use app\model\GetGuide;
use app\model\XyZskDisease;
use app\model\GuideKeyword;
use app\model\DocumentCaseReport;
use app\model\TitleContent;

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


class Zsk extends CommonTwoController
{

    /**
     * 科室以及科室下疾病
     */
    public function index():Json
    {
        $tag      = Request::param('tag') ?? 'xy';
        $page     = Request::param('page') ?? 1;
        $pagesize = 10;
        $limit    = ($page - 1) * $pagesize;

        $type = Request::param('type') ?? 'zsk';
        if('department' === $type) {
            $pagesize = 30;
        }

        /**
         * 西医科室以及科室下疾病
         */
        if('xy' === $tag) {
            $departments = XyZskDisease::distinct(true)
                ->field('departmentLevel1 as department')
                ->where('departmentLevel1' , '<>' , null)
                ->limit($limit , $pagesize)
                ->select()
                ->toArray();
            if('department' === $type) {
                $departmentPageSize = 500;
            }

            if('zsk' === $type) {
                $departmentPageSize = 6;
            }

            foreach ($departments as $key => $value)
            {
                $departments[$key]['diseases']     = $this->getDiseaseByDepartment($value['department'] , $tag , $departmentPageSize);
                $departments[$key]['first_letter'] = $this->getFirstCharters($value['department']);
                $departments[$key]['tag']          = 'Disease';
            }
        }


        /**
         * 中医科室以及科室下疾病
         */
        if('zy' === $tag) {
            //$query = "match(n:SickNess)  where n.department is not null return distinct n.department as department skip $limit limit $pagesize";
            //$departments  = $this->getAboutInfo($query , $tag);

            $departments = ZySickness::distinct(true)->field('department')->where('department' , '<>' , null)->limit($limit , $pagesize)->select()->toArray();


            foreach ($departments as $key => $value) {
                $departments[$key]['diseases']     = $this->getDiseaseByDepartment($value['department'] , $tag);
                $departments[$key]['first_letter'] = $this->getFirstCharters($value['department']);
                $departments[$key]['tag']          = 'zySickNess';
            }
        }

        $firstLetters = array_column($departments, 'first_letter');
        array_multisort($firstLetters , SORT_ASC , SORT_NATURAL , $departments);

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


    /**
     * 科室下疾病
     */
    private function getDiseaseByDepartment($department , $tag , $pagesize = 6):array
    {
        $diseases = XyZskDisease::field('name')->where('departmentLevel1' , $department)->limit($pagesize)->select()->toArray();
        $sickness = ZySickness::field('name')->where('department' , $department)->limit($pagesize)->select()->toArray();
        return 'zy' === $tag ? $sickness : $diseases;
    }


    /**
     * 详情
     */
    public function detail()
    {
        $type  = Request::param('type') ?? '';
        $tag   = 'zh' === $type ? 2 : 1;
        $label = Request::param('label');
        $name  = Request::param('name') ?? '';

        /**
         * 中医疾病下存在多种证型情况 需要单独处理
         */
        if(2 === $tag && 'zySickNess' === $label) {
            $diseaseCategoryProperties = ZySickness::where('name' , $name)->field('dialecticalName as name')->select()->toArray();
            foreach ($diseaseCategoryProperties as $key => $value)
            {
                $diseaseCategoryProperties[$key]['DiseaseCategoryProperties'] = DiseaseProperties::where('label' , 'zySickNess')
                    ->order('order' , 'desc')
                    ->select()
                    ->toArray();
            }
        } else {
            $diseaseCategoryProperties = DiseaseCategoryProperties::where('tag' , $tag)
                ->where('label' , $label)
                ->select()
                ->toArray();
            foreach($diseaseCategoryProperties as $key => $value)
            {
                $diseaseCategoryProperties[$key]['DiseaseCategoryProperties'] = DiseaseProperties::where('category_id' , $value['id'])->order('order' , 'desc')->select()->toArray();
            }
        }
        return $this->_json_succ($diseaseCategoryProperties);
    }


    /**
     * 属性详情
     *
     * @param string $name
     * @param string $propertyChName
     * @param string $propertyZhName
     * @param string $type
     * @param string $label
     */
    public function propertyDetail()
    {
        $name           = Request::param('name');
        $propertyZhName = Request::param('property_zh_name');
        $propertyChName = Request::param('property_ch_name');
        $type           = Request::param('type') ?? '';
        $label          = Request::param('label');
        if(! $name || ! $propertyZhName || ! $propertyChName || ! $label) {
            return $this->_json_error('请求参数有误！');
        }

        $model = '';
        $where = [];
        switch ($label) {
            case "Disease":
               $model = '\app\model\CdssDisease';
               break;
            case "Inspection":
               $model = '\app\model\CdssInspection';
               break;
            case "MedicineProduction":
               $model = '\app\model\CdssMedicine';
               break;
            case "Operation":
                $model = '\app\model\Operation';
                break;
            case "zySickNess":
                $model = '\app\model\ZySickness';
                $where = ['dialecticalName' => $name];
                break;
            case "CnMedicinalCrop":
                $model = '\app\model\ZyMedicinalCrop';
                $where = ['id' =>  $name];
                break;
            case "CnPatentMedicine":
                $model = '\app\model\ZyPatentMedicine';
                break;
            case "Prescription":
                $model = '\app\model\ZyPrescription';
                break;
            case "TonicDiet":
                $model = '\app\model\ZyTonicDiet';
                break;
            case "Constitution":
                $model = '\app\model\ZyConstitution';
                break;
            case "ChannelCollateral":
                $model = '\app\model\ZyChannelCollateral';
                $where = ['id' =>  $name];
                break;
            case "Acupoint":
                $model = '\app\model\ZyAcupoint';
                break;
            case "SickNess":
                $model = '\app\model\ZySickness';
                break;
            default:
                if($propertyChName === 'DiagnosisTreatment')
                {
                    $diagnosisTreatment = GetGuide ::field('title , title_trans , abstract , abstract_trans , author , publish_time , full_text_url , pdf')
                        ->where("keyword_cn"    , "like" , "%$name%" )
                        ->order('publish_time'  , 'DESC')
                        ->select()
                        ->toArray();

                    foreach ($diagnosisTreatment as $k => $v)
                    {
                        if(stripos($v['pdf'] , 'file') !== false) {
                            $diagnosisTreatment[$k]['pdf'] = 'https://jm.admin.jiankangche.cn/uploads/'.$v['pdf'];
                        } elseif($v['pdf']) {
                            $diagnosisTreatment[$k]['pdf'] = 'http://124.70.62.102:8212/'.$v['pdf'].'.pdf';
                        }
                    }
                    return $this->_json_succ(
                        [
                            'text'      => $propertyZhName ,
                            'value'     => $diagnosisTreatment ?? '',
                            'data_type' => 'many'
                        ]
                    );
                }
            break;
        }

        if($model) {
            $where = empty($where) ? ['name' => $name] : $where;
            $fieldValue = $model::where($where)->value($propertyChName);
            return $this->_json_succ(
                [
                    'text'      => $propertyZhName ,
                    'value'     => $fieldValue    ,
                    'data_type' => 'single'
                ]
            );
        }

    }



    /**
     * 某个科室下所有疾病的首字母
     */
    public function getDepartmentExistDiseasesLetter()
    {
        $department  = Request::param('department');
        $type        = Request::param('type') ?? '';
        if(! $type) {
            //$query       = "match(n:Disease) where n.departmentLevel1="."'".$department."'"."return n.name as name";
            //$diseases    = $this->getAboutInfo($query) ?? [];
            $diseases = XyZskDisease::field('name')->where('departmentLevel1' , $department)->select()->toArray();
        } else {
            $query       = "match(n:SickNess) where n.department="."'".$department."'"."return n.dialecticalName as name";
            $diseases    = $this->getAboutInfo($query , 'zy') ?? [];
        }

        if(empty($diseases)) {
            return $this->_json_error('暂无数据！');
        }
        foreach ($diseases as $key => $value)
        {
            $diseases[$key]['first_letter'] = $this->getFirstCharters($value['name']);
        }
        $letters = array_unique(array_column($diseases , 'first_letter'));
        sort($letters);
        return $this->_json_succ(array_values(array_filter($letters)));
    }



    /**
     * 首字母检索疾病
     */
    public function getDiseaseNameByFirstLetter()
    {
        $department  = Request::param('department');
        $firstLetter = Request::param('first_letter');
        $type        = Request::param('type') ?? '';
        if(!$type) {
            $diseases = XyZskDisease::field('name')->where('departmentLevel1' , $department)->select()->toArray();
        } else {
            $query    = "match(n:SickNess) where n.department="."'".$department."'"."return n.dialecticalName as name";
            $diseases = $this->getAboutInfo($query , 'zy') ?? [];
        }

        if(empty($diseases)) {
            return $this->_json_error('暂无数据！');
        }

        foreach ($diseases as $key => $value)
        {
            $diseases[$key]['first_letter'] = $this->getFirstCharters($value['name']);
        }

        $searchs = [];
        foreach ($diseases as $disease)
        {
            if($disease['first_letter'] === $firstLetter) {
                $searchs[] = $disease['name'];
            }
        }
        return $this->_json_succ(
            [
                'department' => $department ,
                'searchs'    => $searchs
            ]
        );
    }


    /**
     * 检测neo4j 有的搜索标签 【未用】
     */
    public function getHaveDataLabelByNeo4j():Json
    {
        $keyword  = Request::param('keyword');
        $type     = Request::param('type') ?? '';

        if('zh' === $type) {
            $tags = ['SickNess' , 'CnMedicinalCrop' , 'CnPatentMedicine' , 'Prescription' , 'TonicDiet' , 'Constitution' , 'ChannelCollateral' , 'Acupoint' , 'Symptom'];
        } else {
            $tags = ['Disease' , 'Inspection' , 'MedicineProduction' , 'Identity' , 'SickNess' , 'ClinicalPathway'];
        }

        $existDataTags = [];
        foreach($tags as $tag)
        {
            $query = "match(n:".$tag.") where n.name =~'.*".$keyword.".*' return n.name as name , n.kgid as kgid limit 1";
            $data  = 'zh' === $type ? $this->getAboutInfo($query , $type) : $this->getAboutInfo($query);

            if(isset($data[0]['name'])) {
                $existDataTags[] = $tag;
            }

            if('ClinicalPathway' === $tag) {
                $count = ClinicalPathway::where("clinical_pathway" , "like" , "%$keyword%" )->count();
                if($count > 0) {
                    $existDataTags[] = $tag;
                }
            }
        }

        $result = [];
        if(!empty($existDataTags)) {
            foreach($existDataTags as $existDataTag) {
                $result[] = [
                    'key'   => $existDataTag ,
                    'value' => DiseaseCategoryProperties::getValueByTag($existDataTag , $type)
                ];
            }
        }
        return $this->_json_succ($result);
    }


    /**
     * 搜索下展示标签
     */
    public function getLabels()
    {
        $lables = DiseaseCategoryProperties::getValueByTag('' , Request::param('type') ?? '',Request::param('gh') ?? '');
        $result = [];
        foreach($lables as $key => $value)
        {
            $result[] = [
                'key'   => $key ,
                'value' => $value ,
                'department' => $this->getDepartment($key)
            ];
        }
        return $this->_json_succ($result);
    }


    /**
     * 医疗疾病 ｜ 科普疾病 获取科室
     */
    public function getDepartment($label)
    {
        if('Disease' === $label) {
            $department = CdssDisease::field('department_1 as department')
                ->distinct(true)
                ->limit(30)
                ->select()
                ->toArray();
            return array_values(array_filter(array_column($department , 'department')));
        }
	//9.26 修改
        //if('SickNess' === $label) {
        //    $department = XySickNess::field('departmentLevel1 as department')
        //        ->distinct(true)
        //        ->limit(30)
        //        ->select()
        //        ->toArray();
        //    return array_values(array_filter(array_column($department , 'department')));
        //}
        return [];
    }




    /**
     * 图像库
     */
    public function imgs()
    {
        $page      = Request::param('page') ?? 1;
        $pasgesize = 10;
        $limit     = ($page - 1) * $pasgesize;

        $imgs = XyZskDisease::field('ct')->where('ct' , '<>' , '' )->limit($limit , $pasgesize)->select()->toArray();
        foreach($imgs as $key => $img) {
            $imgs[$key]['ct'] = 'http://124.70.62.102:8212/'.$img['ct'].'.jpg';
        }
        return $this->_json_succ(
            [
                'images' => $imgs ,
                'total' => 500
            ]
        );
    }




    /**
     * 获取疾病诊疗指南关键词（调用外部接口）[弃用]
     */
    public function getKeywordByDiseaseName()
    {
        $name = Request::param('name');
        $url      = "http://124.70.62.102/keyword/query?keyword_cn=".urlencode($name);
        $response = json_decode(file_get_contents($url) , true);
        if(200 == $response['code']) {
            $keyword =  $response['data'][0]['keyword'];
            $keywords = explode(' ' , $keyword);
            return $keywords[0];
        }
        return false;
    }


    // ------------------------------------------- 外部接口数据录入 ---------------------------------------

    /**
     * 诊疗指南录入
     */
    public function addGuide()
    {
        //$date = "2022-07-14"; // 0510
        $date = '';


        if(!$date) {
            return $this->_json_error('日期未输入！');
        }

        if(!$type = Request::param('type') ?? 'guides') {
            return $this->_json_error('日期未输入！');
        }

        $url  = "http://124.70.62.102/data/query?date=".urlencode($date).'&type='.urlencode($type);

        $data = json_decode(file_get_contents($url) , true);
        if(empty($data)) {
            return;
        }

        $guides = $data['data'];
        foreach($guides as  $guide)
        {
            if($guide['references']) {
                $guide['references'] = json_encode($guide['references']);
            }

            if($guide['references_trans']) {
                $guide['references_trans'] = json_encode($guide['references_trans']);
            }

            if($guide['full_text_url']) {
                $guide['full_text_url'] = json_encode($guide['full_text_url']);
            }

            $result = GetGuide::create($guide);
        }
        $result = [];
        return $this->_json_succ($result);
    }


    /**
     * 指南关键词录入
     */
    public function addGuideKeyword()
    {
        $url  = "http://124.70.62.102/keyword/query";
        $data = json_decode(file_get_contents($url) , true);
        if(empty($data)) {
            return;
        }

        $data = $data['data'];

        foreach($data as $value)
        {
            $result = GuideKeyword::create($value);
        }
        $result = [];
        return $this->_json_succ($result);
    }


    /**
     * 疾病录入
     */
    public function addDise()
    {
        $date = "2022-05-13"; // 0510
        //$date = '';
        if(!$date) {
            return $this->_json_error('日期未输入！');
        }

        if(!$type = Request::param('type') ?? 'pet') {
            return $this->_json_error('日期未输入！');
        }

        $url  = "http://124.70.62.102/data/query?date=".urlencode($date).'&type='.urlencode($type);

        $data = json_decode(file_get_contents($url) , true);
        if(empty($data)) {
            return;
        }
        //return $this->_json_succ($data);

        $guides = $data['data'];
        foreach($guides as  $guide)
        {
            if($guide['references']) {
                $guide['references'] = json_encode($guide['references']);
            }

            if($guide['references_trans']) {
                $guide['references_trans'] = json_encode($guide['references_trans']);
            }

            if($guide['full_text_url']) {
                $guide['full_text_url'] = json_encode($guide['full_text_url']);
            }

            $result = DocumentImages::create($guide);
        }
        $result = [];
        return $this->_json_succ($result);
    }


    // -------------------------------- 图像库 ｜ 病例库 ---------------------------------

    /**
     * 图像类型
     */
    public function imageType()
    {
        $imageType = [
            ['key' => 'x'           , 'value' => 'X线片'],
            ['key' => 'ct'          , 'value' => 'CT'],
            ['key' => 'mri'         , 'value' => 'MRI'],
            ['key' => 'pet'         , 'value' => 'PET'],
            ['key' => 'ultrasound'  , 'value' => '超声图像'],
            ['key' => 'microscopy'  , 'value' => '显微镜图'],
            ['key' => 'graphics'    , 'value' => '绘图图表']
        ];
        return $this->_json_succ($imageType);
    }



    /**
     * 图像库首页
     */
    public function documentImages()
    {
        $search    = Request::param('search') ?? '';
        $type      = Request::param('type')   ?? '';
        $page      = Request::param('pn') ?? 1;
        $pasgesize = 12;
        $limit     = ($page - 1) * $pasgesize;

        $where = [];
        if($type) {
            $where[] = ['type' , '=' , $type];
        }

        if($search) {
            $where[] = ["keyword_cn" , "like" , "%$search%"];
        }

        $total = DocumentImages::count();
        $documentImages = DocumentImages::field('img_name , type , title_trans as title , abstract_trans , keyword_cn , publish_time')->where($where)->limit($limit , $pasgesize)->select()->toArray();
        if(empty($documentImages)) {
            return $this->_json_error();
        }

        foreach($documentImages as $key => $img) {
            $documentImages[$key]['image']   = 'https://jm.jiankangche.cn/disease-img/images/'.$img['img_name'].'.jpg';
            $documentImages[$key]['type_zh'] = DocumentImages::imageType($img['type']);
        }

        /**
         * 总页数
         */
        $total_page = ceil($total/$pasgesize);
        return $this->_json_succ(['images' => $documentImages , 'total' => $total , 'total_page' => $total_page]);
    }


    /**
     * 图像库文献详情
     */
    public function documentImagesDetail()
    {
        if(!$imgName = Request::param('img_name') ?? '') {
            return $this->_json_error('请求参数有误！');
        }
        $document    = DocumentImages::getByImgName($imgName);
        $newDocument = [
            'title'         => $document['title_trans'],
            'enTitle'       => $document['title'],
            'source'        => $document['source'],
            'abstract'      => $document['abstract'],
            'abstract_trans'=> $document['abstract_trans'],
            'constitutor'   => $document['author'],
            'year'          => $document['publish_time'],
            'full_text_url' => $document['full_text_url'],
            'onlineRead'    => 'https://jm.jiankangche.cn/disease-img/images/'.$document['pdf_file'].'.pdf'
        ];
        return $this->_json_succ($newDocument);
    }


    /**
     * 病例库文献
     */
    public function documentCaseReports()
    {
        $page      = Request::param('pn') ?? 1;
        $pasgesize = 10;
        $limit     = ($page - 1) * $pasgesize;

        $search    = Request::param('search') ?? '';
        if(!$search) {
            $total = DocumentCaseReport::count();
            $documentCaseReports = DocumentImages::limit($limit , $pasgesize)->select()->toArray();
        } else {
            $total = DocumentCaseReport::where("keyword_cn" , "like" , "%$search%")->whereOr("title_trans" , "like" , "%$search%")->count();
            $documentCaseReports = DocumentImages::where("keyword_cn" , "like" , "%$search%")
                ->whereOr("title_trans" , "like" , "%$search%")
                ->limit($limit , $pasgesize)
                ->select()
                ->toArray();
        }

        if(empty($documentCaseReports)) {
            return $this->_json_error('未查到数据！');
        }

        $newCaeReports = [];
        foreach($documentCaseReports as $key => $value) {
            $newCaeReports[$key]['title']          = $value['title_trans'];
            $newCaeReports[$key]['enTitle']        = $value['title'];
            $newCaeReports[$key]['source']         = $value['source'] ?? '';
            $newCaeReports[$key]['abstract']       = $value['abstract'];
            $newCaeReports[$key]['abstract_trans'] = $value['abstract_trans'];
            $newCaeReports[$key]['constitutor']    = $value['author'];
            $newCaeReports[$key]['year']           = $value['publish_time'];
            $newCaeReports[$key]['full_text_url']  = $value['full_text_url'];
            $newCaeReports[$key]['onlineRead']     = 'https://file.jiankangche.cn/'.$value['pdf_file'].'.pdf';
        }
        /**
         * 总页数
         */
        $total_page = ceil($total/$pasgesize);
        return $this->_json_succ(
            [
                'caeReports' => $newCaeReports ,
                'total'      => $total ,
                'total_page' => $total_page
            ]
        );
    }


    /**
     * 指南脑图（中文）
     */
    public function getMindMapZhList():Json
    {
        $search = Request::param('search') ?? '';
        $type   = Request::param('type')   ?? 1;
        return $this->_json_succ(
            $this->getTrees(MindMapzh::where(['type' => $type])->select() , 0 , $search)
        );
    }


    /**
     * 递归生成树形结构
     * @param  array $data 所有分类数据
     * @param  int   $pid 父级id
     * @return array
     */
    protected function getTrees($data , $pid = 0 , $search = ''):array
    {
        $tree = [];
        foreach ($data as $value)
        {
            /**
             * 关键字搜索
             */
            if(stripos($value['category_name'] , $search) !== false) {
                $value['is_search'] = 1;
            } else {
                $value['is_search'] = 2;
            }

            /**
             * 字符长度超多8个汉字需要截取处理
             */
            $strLen = 24;
            if($strLen < strlen($value['category_name'])) {
                $value['category_name_substr'] = mb_substr($value['category_name'] , 0 , 8) . '...';
            } else {
                $value['category_name_substr'] = $value['category_name'];
            }

            if ($value['parent_id'] == $pid) {
                /*
                 * 销毁节点 , 减少后续递归消耗
                 */
                // unset($data[$key]);
                $children = $this->getTrees($data , $value['id'] , $search);
                if (!empty($children)) {
                    $value['children'] = $children;
                }
                $tree[] = $value;
            }
        }
        return $tree;
    }


    /**
     * 指南结构化
     */
    public function getGuideStructureList():Json
    {
        $search    = Request::param('search') ?? '';
        $page      = Request::param('page') ?? 1;
        $pasgesize = 10;
        $limit     = ($page - 1) * $pasgesize;
        if($search) {
            $list      = TitleContent::field('title , content , page')->where("title" , "like" , "%$search%")->where('title' , '<>' , '')->limit($limit , $pasgesize)->select()->toArray();
            $total     = TitleContent::where("title" , "like" , "%$search%")->where('title' , '<>' , '')->count();
        } else {
            $list      = TitleContent::field('title , content , page')->where('title' , '<>' , '')->limit($limit , $pasgesize)->select()->toArray();
            $total     = TitleContent::where("title" , "like" , "%$search%")->where('title' , '<>' , '')->count();
        }

        foreach($list as $key => $value) {
            $list[$key]['pdf_link'] = "https://jm.jiankangche.cn/sga2022.v2.pdf";
        }

        /**
         * 总页数
         */
        $total_page = ceil($total/$pasgesize);
        return $this->_json_succ(
            [
                'list'    => $list ,
                'total'   => $total ,
                'total_page' => $total_page
            ]
        );
    }


    /**
     * 药物靶点
     */
    public function getOmicsList():Json
    {
        $page      = Request::param('page') ?? 1;
        $pasgesize = 10;
        $limit     = ($page - 1) * $pasgesize;

        $searchField = Request::param('search_field') ?? '';
        $search      = Request::param('search') ?? '';

        if($searchField && $search) {
            $list      = Omics::where($searchField , "like" , "%$search%")->limit($limit , $pasgesize)->select()->toArray();
            $total     = Omics::where($searchField , "like" , "%$search%")->count();
        } else {
            $list      = Omics::limit($limit , $pasgesize)->select()->toArray();
            $total     = Omics::count();
        }

        /**
         * 总页数
         */
        $total_page = ceil($total/$pasgesize);
        return $this->_json_succ(
            [
                'list'  => $list ,
                'total' => $total ,
                'total_page' => $total_page
            ]
        );
    }

}
