<?php
namespace app\controller;

require_once app()->getRootPath().'vendor/autoload.php';
use Neoxygen\NeoClient\ClientBuilder;
use think\facade\Request;
use function GuzzleHttp\Psr7\str;
use app\model\Guide;
use app\model\GetGuide;
use think\facade\Config;

class Document extends CommonTwoController
{

    // 文献指南左侧菜单
    public function menu()
    {
        $lists = [
            ['knowledge_base_name' => '文献和指南']
        ];
        foreach ($lists as $k => $v) {
            $lists[0]['subordinate'] = [['name' => '文献' , 'tag' => 'document'] , ['name' => '指南' , 'tag' => 'guide'] , ['name' => '药品' , 'tag' => 'medicine']];
        }
        return $this->_json_succ($lists);
    }


    // 文献 | 指南 搜索
    public function index()
    {
        // 标识
        $tag       = Request::param('tag') 	 ?? 'Document';

        // 分页参数
        $pn        = Request::param('pn')  	 ?? 1;
        $pagesize  = 10;
        $limit     = ($pn - 1) * $pagesize;

        // 是否搜索标识  is 是 notis 不是
        $is_search = Request::param('is_search') ?? 'is';

        // 排序标识
        $order     = Request::param('order') ?? 'desc';

        // 搜索值
        $search    = Request::param('search') ?? '';
        if('is' == $is_search) {
            if(!$search) {
                return $this->_json_succ('请求参数有误！');
            }
        }

        switch ($tag)
        {
            // 文献
            case "Document":
                $search  = $search ? $search : "Alport综合征";
                $query   = "CALL db.index.fulltext.queryNodes('documentFullIndex', "."'".$search."'".") YIELD node, score where node.year is not null and node.abstract is not null RETURN node skip $limit limit $pagesize";
                $data  	 = $this->getProperty($query);
                $data    = array_column($data , 'node');
                $list    = [];

                $query_count  = "CALL db.index.fulltext.queryNodes('documentFullIndex', "."'".$search."'"." ) YIELD node where node.year is not null and node.abstract is not null RETURN count(node) as count";
                $count_ 	  = $this->_getTotalCount($query_count);

                foreach ($data as $key => $value)
                {
                    $list[$key]['title'] 	  = $value['name'] 	    ?? '';
                    $list[$key]['abstract']   = $value['abstract']  ?? '';
                    $list[$key]['year']   	  = $value['year']      ?? '';
                    $list[$key]['author']     = $this->getAuthorByDocument($value['name']) 	?? '';
                    $list[$key]['keyword'] 	  = $this->getKeywordByDocument($value['name']);
                    //$list[$key]['onlineRead'] = $this->checkDocPdfIsExist('https://zskweb.jiankangche.cn/file/wenxian/file/'.$value['name'].'.pdf');
                    if(strrpos($value['name'] , '.')) {
                        $list[$key]['onlineRead'] = $this->checkDocPdfIsExist('https://zskweb.jiankangche.cn/file/wenxian/file/'.$value['name'].'pdf');
                    } else {
                        $list[$key]['onlineRead'] = $this->checkDocPdfIsExist('https://zskweb.jiankangche.cn/file/wenxian/file/'.$value['name'].'.pdf');
                    }
                }

//				foreach ($list as $k => $v) {
//                    if(!$list[$k]['abstract'] && !$list[$k]['year'] && !$list[$k]['author'] && !$list[$k]['keyword']) {
//                        unset($list[$k]);
//                    }
//                }

                //return $this->_json_succ($list);
                $year = array_column($list , 'year');
                if($order) {
                    if('asc' == $order) {
                        $order = SORT_ASC;
                    } else {
                        $order = SORT_DESC;
                    }
                }
                array_multisort($year , $order , $list);
                break;

            // 指南
            case "Guide":
//			    $search = $search ? $search : "指南";
//				$query  = "CALL db.index.fulltext.queryNodes('guideFullIndex', "."'".$search."'".") YIELD node, score RETURN node skip $limit limit $pagesize";
//				$data   = $this->getProperty($query);
//				$data   = array_column($data , 'node');
//				$list   = [];
//
//				// 统计
//				$query_count = "CALL db.index.fulltext.queryNodes('guideFullIndex', "."'".$search."'"." ) YIELD node RETURN count(node) as count";
//				$count = $this->_getTotalCount($query_count);

                if('is' === $is_search) {
                    //$data  = Guide::where("documentName" , "like" , "%$search%" )->select();
                    $data_ = GetGuide::where("documentName" , "like" , "%$search%" )->limit($limit , $pagesize)->order('publishDate',$order)->select();
                    //$count  = Guide::where("documentName" , "like" , "%$search%" )->count();
                    $count_ = GetGuide::where("documentName" , "like" , "%$search%" )->count();
                } else {
                    $data_   = GetGuide::limit($limit , $pagesize)->order('publishDate',$order)->select();
		    //$count  = GetGuide::count();
                    $count_ = GetGuide::count();
                }
		
                $list  = [];
                //foreach ($data_ as $key => $value)
                //{
                //    $list[$key]['title'] 	      = $value['title_trans']         ?? '';
                //    $list[$key]['enTitle']  	  = $value['title'] 	          ?? '';
                //    $list[$key]['source']   	  = $value['source'] 		      ?? '';
                //    $list[$key]['constitutor']    = $value['author']              ?? '';
                //    $list[$key]['year'] 	      = $value['publish_time'] 	 	  ?? '';
                //    $list[$key]['abstract'] 	  = $value['abstract'] 	 	      ?? '';
                //    $list[$key]['abstract_trans'] = $value['abstract_trans'] 	  ?? '';

                //    is_numeric(substr($data_[$key]['publish_time'] , -4)) ? $publish_time = substr($data_[$key]['publish_time'] , -4) : $publish_time = substr($data_[$key]['publish_time'] , 0 , 4);
                //    $list[$key]['publish_time']   = $publish_time;
                //    $list[$key]['full_text_url']  = $value['full_text_url'] ?? '';
		    //$list[$key]['full_text_url']  = 'http://182.43.12.243:8981/lcznpdf/'.rtrim($value['title_trans'],'。').'.pdf';;
                //    $list[$key]['onlineRead']     = $value['pdf'] ? 'https://jm.admin.jiankangche.cn/uploads/'.$value['pdf'] : '';
                //}

                //$publishTime = array_column($list , 'publish_time');
                //if($order) {
                //    if('asc' == $order) {
                //        $order = SORT_ASC;
                //    } else {
                //        $order = SORT_DESC;
                //    }
                //}
                //array_multisort($publishTime , $order , $list);
		foreach ($data_ as $key => $value){
                    $list[$key]['department'] 	      = $value['department']         ?? '';
                    $list[$key]['sickName'] 	      = $value['sickName']         ?? '';
                    $list[$key]['documentName'] 	      = $value['documentName']         ?? '';
                    $list[$key]['year'] 	      = $value['year']         ?? '';
                    $list[$key]['publishDate'] 	      = $value['publishDate']         ?? '';
                    $list[$key]['enTitle'] 	      = $value['enTitle']         ?? '';
                    $list[$key]['constitutor'] 	      = $value['constitutor']         ?? '';
                    $list[$key]['source'] 	      = $value['source']         ?? '';
                    $list[$key]['abstract'] 	      = $value['abstract']         ?? '';
                    $list[$key]['abstract_trans'] 	      = $value['abstract_trans']         ?? '';
                    $list[$key]['url'] 	      = $this->checkDocPdfIsExist('http://106.225.184.197:8981/lcznpdf/'.$value['documentName'].'.pdf');
                    //$list[$key]['url']        = 'http://106.225.184.197:8981/lcznpdf/'.$value['documentName'].'.pdf';
		}
                break;

        }
        return $this->_json_succ(['count' => $count_ , 'list' => $list]);
    }


    private function checkDocPdfIsExist($url)
    {
        $check = get_headers($url);
        if(strstr($check[0] , '200')) {
            return $url;
        }
        return "";
    }


    // 文献详情
    public function detail()
    {
        $tag   = Request::param('tag') 	 ?? 'Document';
        $title = Request::param('title')   ?? '';

        $query = "match(n:Document) where n.name = "."'".$title."'"." return n";
        $data  = $this->getProperty($query);
        $data  = array_column($data , 'n');

        // 获取 文献的作者 参考文献  引证文献
        $query1 = "match p=(n:Document {name:"."'".$title."'"."}) -[r:LinkAuthor|LinkReference|LinkCitationDocument]-(m) return m.name as mname, m.kgid as kgid,  r.name as rname";
        $data1  = $this->getProperty($query1);

        foreach ($data1 as $key => $value)
        {
            if(($value['rname'] == "作者")) {
                $authors[] = ['name' => $value['mname'] , 'kgid' => $value['kgid']];
            }

            if(($value['rname'] == "参考文献")) {
                $rer[] = $value['mname'];
                $wx = ['titles' => $rer];
            }
        }

        $list  = [
            'title'    		   => $data[0]['name'] ?? '',
            'abstract' 		   => $data[0]['abstract'] ?? '',
            'author'   		   => $authors ?? [],
            'keyword'  		   => '',
            'publishMagazine'  => $data[0]['publishMagazine'] ?? '',
            'similarDocument'  => $wx ?? [],  		// 参考文献
            'citationDocument' => [],  				// 引证文献
        ];
        return $this->_json_succ($list);
    }


    // 作者详情
    public function authorDetail()
    {
        $kgid 	= Request::param('kgid');
        $query  = "match(n:Thing) where n.kgid =  "."'".$kgid."'"."return n.name as name , n.focusField as focusField , n.organization as organization limit 1";
        $data   = $this->getProperty($query);
        $list   = [
            'name' 				=> $data[0]['name'],
            'focusField' 		=> explode('||' ,$data[0]['focusField']),
            'organization' 		=> $data[0]['organization'],
            'authorDocument'	=> $this->getDocumentByAuthor($kgid),
        ];
        return $this->_json_succ($list);
    }



    // 热点研究方向
    public function getHotList()
    {
        $title = Request::param('title') ?? '诊断';
        $query = "CALL db.index.fulltext.queryNodes('documentFullIndex', "."'".$title."'".") YIELD node match p=(node)-[r:LinkKeyword]-(k:Keyword) with node.year as year, k.name as keyword, 
		count(*) as cnt order by year desc, cnt desc return year, apoc.agg.slice(keyword, 0, 5) AS hots, apoc.agg.slice(cnt, 0, 5) as count limit 5";
        $data  = $this->getProperty($query);
        foreach ($data as $key => $value) {
            for ($i=0;$i<5;$i++) {
                $data[$key]['hots'] = [
                    [
                        'name'  => $value['hots'][0] ,
                        'count' => $value['count'][0]
                    ],
                    [
                        'name'  => $value['hots'][1] ,
                        'count' => $value['count'][1]
                    ],
                    [
                        'name'  => $value['hots'][2] ,
                        'count' => $value['count'][2]
                    ],
                    [
                        'name'  => $value['hots'][3] ,
                        'count' => $value['count'][3]
                    ],
                    [
                        'name'  => $value['hots'][4] ,
                        'count' => $value['count'][4]
                    ]

                ];
            }
            unset($data[0]);
            unset($data[$key]['count']);
        }
        rsort($data);
        return $this->_json_succ($data);
    }


    // 作者图谱
    public function authorGraph()
    {
        $hot = Request::param('hot_name') ?? "心力衰竭";
        $id  = $this->_getId($hot);

        $query = "match (a0:Author)<-[r:LinkAuthor]-(:Document)-[:LinkKeyword]->(k:Keyword {name:"."'".$hot."'"."}) with  a0, k, count(r.name) as cnt order by cnt desc with k, apoc.agg.slice(a0, 0,10) as authors unwind authors as author with k, author call apoc.create.vRelationship(k,'LinkToKeyword',{}, author) yield rel return k, author, rel";
        $data  = $this->getProperty($query);
        $lists = [];
        foreach ($data as $key => $value)
        {
            $lists[$key]['start']['identity'] = $id;
            $lists[$key]['start']['labels']   = ['Document' , 'Thing'];
            $lists[$key]['start']['properties']['name'] = ['name' => '热点名称' , 'text' => $value['k']['name']];

            $lists[$key]['end']['identity'] = $this->_getId($value['author']['kgid'] , 'endid');
            $lists[$key]['end']['labels']   = ['Thing' , 'Author'];
            $lists[$key]['end']['properties']['name']         = ['name' => '作者'    , 'text' => $value['author']['name']];
            $lists[$key]['end']['properties']['organization'] = ['name' => '所属单位' , 'text' => $value['author']['organization']];

            $lists[$key]['relationship']['start'] = $id;
            $lists[$key]['relationship']['end']   = $this->_getId($value['author']['kgid'] , 'endid');
            $lists[$key]['relationship']['type']  = 'LINKAUTHOR';
            $lists[$key]['relationship']['properties']['@type'] = [
                "LinkAuthor",
                "CnsLink"
            ];
            $lists[$key]['relationship']['properties']['name'] = '作者';
        }
        return $this->_json_succ($lists);
    }



    // 获取热点对应作者的kgid
    public function getHotAuthorKgids($hot = '')
    {
        $query1 = "match(n:Author) where n.focusField ="."'".$hot."'"." return n.name as name, n.kgid as kgid limit 10";
        $data1  = $this->getProperty($query1);
        //dump($data1);die;
        return array_column($data1 , 'kgid');
    }


    // 获取作者的文献
    private function getDocumentByAuthor($kgid)
    {
        $query = "match(n:Document)-[r:LinkAuthor]-(m:Author) where m.kgid="."'".$kgid."'"." return n.name as name";
        $data  = $this->getProperty($query) ?? [];
        return $data ? array_column($data,  'name') : [];
    }


    // 获取文献的作者
    private function getAuthorByDocument($title)
    {
        if(strstr($title , "'")) {
            $title = trim(str_replace("'","",$title));
            $query = "match(n:Document)-[r:LinkAuthor]-(m:Thing) where n.name= "."'".$title."'"." return m.name as name , m.kgid as kgid";
        } elseif (strstr($title , '"')) {
            $title = trim(str_replace('"',"",$title));
            $query = 'match(n:Document)-[r:LinkAuthor]-(m:Thing) where n.name= '.'"'.$title.'"'.' return m.name as name , m.kgid as kgid';
        } else {
            $query = "match(n:Document)-[r:LinkAuthor]-(m:Thing) where n.name= "."'".$title."'"." return m.name as name , m.kgid as kgid";
        }
        $data  = $this->getProperty($query) ?? [];
        return $data ?? [];
    }


    // 获取文献的关键词
    private function getKeywordByDocument($title)
    {
        if(strstr($title , "'")) {
            $title = trim(str_replace("'","",$title));
            $query = "match(n:Document)-[r:LinkKeyword]-(m:Keyword) where n.name= "."'".$title."'"." return m.name as name";
        } elseif (strstr($title , '"')) {
            $title = trim(str_replace('"',"",$title));
            $query = 'match(n:Document)-[r:LinkKeyword]-(m:Keyword) where n.name= '."'".$title."'".'return m.name as name';
        } else {
            $query = "match(n:Document)-[r:LinkKeyword]-(m:Keyword) where n.name= "."'".$title."'"." return m.name as name";
        }
        $data  = $this->getProperty($query) ?? [];
        return $data ? array_column($data , 'name') : [];
    }
}
