<?php
namespace app\controller;


use think\facade\Request;
use think\response\Json;


/**
 * 期刊分析
 */
class EsAlbum extends CommonEsController
{

    protected $pagesize   = 10;
    protected $albumIndex = 'album_zh';


    public function getAlbumIndex()
    {
        $index = $this->currentLanguage();
        //return $index === "document_zh" ? 'album_zh' : 'album_zh';
        return 'album';
    }


    /**
     * 期刊首页
     *
     * @param  $page         int     分页页码
     * @param  $search       string  搜索值
     * @param  $search_tag   string  搜索标识
     * @param  $impactIndex  string  影响指数
     * @return Json
     */
    public function index():Json
    {
        /**
         * 分页参数
         */
        $page  = Request::param('page') ?? 1;
        $limit = ($page - 1) * $this->pagesize;
        /**
         * 搜索
         */
        $search      = Request::param('search')       ?? '';
        $searchTag   = Request::param('search_tag')   ?? 'album';
        $impactIndex = Request::param('impact_index') ?? '';

        $body = [];
	$albumIndex = $this->albumIndex;
        if($search || $impactIndex) {
            if($impactIndex) {
                $impactIndexArr = explode(',' , $impactIndex);
                $body['query']['bool']['filter'][] = [
                    'range' => [
                        'composite_impact_factor' => [
                            'gte' => $impactIndexArr[0] ,
                            'lte' => $impactIndexArr[1] ,
                        ]
                    ]
                ];
            }

            if($search) {
                $albumIndex = $this->getAlbumIndex();
                $body['query']['bool']['should'][] = [
                    'match_phrase' => [
                        $searchTag => $search
                    ]
                ];
                $body['query']['bool']['minimum_should_match'] = 1;
            }
        } else {
            $body['query'] = [
                'match_all'  => (object)[]
            ];
        }
        $body['from']  = $limit;
        $body['size']  = $this->pagesize;

        $body['sort'] = [
            [
                'mark' => [
                    'order' => 'desc'
                ]
            ]
        ];
        $params =  [
            'index' => $albumIndex,
            'body'  => $body
        ];
        
	$result = $this->esCommonGetData($params);
        if( 0 == $result['total']) {
            return $this->_json_error('未查到相关数据！');
        }

        $data      = $result['data'];
        $albumList = array_column($data, 'album');
        $select    = 'terms';
        $size      = $this->pagesize;
        foreach($data as $key => $value) {
            $data[$key]['tag']        = isset($value['md5']) ? 'cn' : 'en';
            $data[$key]['unique_val'] = isset($value['md5']) ? $value['md5'] : $value['uniq_id'];
        }

        $documentIndex = 'album_en' === $albumIndex ? 'document_en' : 'document_zh';

        /**
         * 期刊下文献统计
         */
        $paramsB = [
            'index' => $documentIndex,
            'body'  => [
                'size'  => 1 ,
                'query' => [
                    'bool' => [
                        'filter' => [
                            $select => [
                                'album.keyword' => $albumList
                            ]
                        ]
                    ]
                ] ,
                'aggs' => [
                   'albumStat' => [
                       'terms' => [
                           'field' => 'album.keyword' ,
                           'order' => [
                               '_count' => 'desc'
                           ] ,
                           'size' => $size
                       ] ,
                       'aggs' => [
                           'citedDocCnt' => [
                               'filter' => [
                                   'range' => [
                                       'citation_relate_count' => [
                                           'gte' => 1
                                       ]
                                   ]
                               ],
                               'aggs' => [
                                   'citedTotalCnt' => [
                                       'sum' => [
                                           'field' => 'citation_relate_count'
                                       ]
                                   ]
                               ]
                           ] ,
                           'authorCnt' => [
                               'cardinality' => [
                                   'field' => 'author_list.keyword'
                               ]
                           ] ,
                           'orgCnt' => [
                               'cardinality' => [
                                   'field' => 'organization_parsed.keyword'
                               ]
                           ]

                       ]
                   ]
                ]
            ]
        ];

        $client  = $this->getEsClient();
        $resultB = $client->search($paramsB);
        $buckets = $resultB['aggregations']['albumStat']['buckets'] ?? [];

        if( empty($buckets) && ! empty($data)) {
            return $this->_json_succ(
                $this->albumSearchList($data, $result['total'])
            );
        }

        /**
         * 期刊有数据 文献无数据
         */
        $newArray = [];

        foreach ($buckets as $key => $value) {
            /**
             * 获取期刊字段
             */
            $fields = $this->getAlbumField($data , $value['key']);

            /**
             * 名称
             */
            $newArray[$key]['album'] = $value['key'];

            /**
             * 专题名称
             */
            $newArray[$key]['special_name'] = $fields['special_name'] ?? '';

            /**
             * 所属杂志
             */
            $newArray[$key]['cn_name'] = $fields['cn_name'] ?? '';

            /**
             * 识别码
             */
            $newArray[$key]['postal_distribution_code'] = $fields['postal_distribution_code'] ?? '';

            $newArray[$key]['tag'] = $fields['tag']  ?? '';
            $newArray[$key]['unique_val'] = $fields['unique_val'] ?? '';

            /**
             * 审稿周期
             */
            $newArray[$key]['review_cycle'] = $fields['review_cycle'] ?? '';

            /**
             * 投稿命中率
             */
            $newArray[$key]['submission_hit_rate'] = $fields['submission_hit_rate'] ?? '';


            /**
             * 发文量
             */
            $newArray[$key]['doc_count'] = $value['doc_count'] ?? 0;

            /**
             * 影响指数
             */
            $newArray[$key]['composite_impact_factor'] = $fields['composite_impact_factor'] ?? 0;

            /**
             * 作者数
             */
            $newArray[$key]['author_count'] = $buckets[$key]['authorCnt']['value'] ?? 0;


            /**
             * 机构数
             */
            $newArray[$key]['org_count'] = $buckets[$key]['orgCnt']['value'] ?? 0;

            /**
             * 被引文献数量
             */
            $citedDocCnt = $buckets[$key]['citedDocCnt']['doc_count'] ?? 0;

            /**
             * 被引总量
             */
            $citedTotalCnt = $buckets[$key]['citedDocCnt']['citedTotalCnt']['value'] ?? 0;

            $newArray[$key]['cited_total_Cnt'] = $citedTotalCnt ?? 0;
            $newArray[$key]['article_Average_cited_count'] = 0 == $citedTotalCnt ? 0 : round($citedDocCnt / $citedTotalCnt , 2);
        }


        return $this->_json_succ(
            [
                'total'      => $result['total'],
                'total_page' => ceil($result['total']  / $this->pagesize),
                'data'       => $newArray ,
            ]
        );
    }


    /**
     * 获取期刊字段
     */
    protected function getAlbumField($data , $album)
    {
        foreach($data as $value) {
            if($album === $value['album']) {
                return $value;
            }
        }
    }



    /**
     * 期刊搜索返回
     */
    protected function albumSearchList($data, $total)
    {
        foreach($data as $key => $value) {
            $data[$key]['doc_count']    = 0;
            $data[$key]['author_count'] = 0;
            $data[$key]['org_count']    = 0;
            $data[$key]['cited_total_Cnt'] = 0;
            $data[$key]['article_Average_cited_count'] = 0;
            $data[$key]['composite_impact_factor']     = $value['composite_impact_factor']  ?? '';
            $data[$key]['postal_distribution_code']    = $value['postal_distribution_code'] ?? '';
        }

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


    /**
     * 期刊详情
     */
    public function albumDetail()
    {
        $tag   = Request::param('tag')     ?? 'tag';
        $value = Request::param('unique_val')   ?? '';
        if( ! $value || ! $tag) {
            return $this->_json_error('请求参数有误！');
        }

        $field  = 'cn' === $tag ? 'md5' : 'uniq_id';
        $index  = 'cn' === $tag ? 'album_zh' : 'album_en';

        $params = [
            'index' => $this->getAlbumIndex(),
            'body'  => [
                'query' => [
                    'bool' => [
                        'filter' => [
                            'term' => [
                                $field => $value
                            ]
                        ]
                    ]
                ] ,
            ]
        ];

        $client  = $this->getEsClient();
        $result  = $client->search($params);
        $source  = $result['hits']['hits'][0]['_source'];
        $albumCountDetail = $this->albumCountDetail($source['album'] , $tag);
        $albumCountDetail['album']                   = $source['album'];
        $albumCountDetail['special_name']            = $source['special_name']            ?? '';
        $albumCountDetail['cn_name']                 = $source['cn_name']                 ?? '';
        $albumCountDetail['composite_impact_factor'] = $source['composite_impact_factor'] ?? '';
        $albumCountDetail['review_cycle']            = $source['review_cycle']            ?? '';
        $albumCountDetail['submission_hit_rate']     = $source['submission_hit_rate']     ?? '';

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


    /**
     * 期刊详情统计
     */
    protected function albumCountDetail($album , $tag)
    {
        $params = [
            'index' => $this->currentLanguage() ,
            'body'  => [
                'query' => [
                    'bool' => [
                        'filter' => [
                            'term' => [
                                'album.keyword' => $album
                            ]
                        ],
                        'must' => [
                            [
                                'range' => [
                                    'year' => [
                                        'gte' => 2012 ,
                                        'lte' => 2022
                                    ]
                                ]
                            ]
                        ]
                    ]
                ],
                'aggs' => [
                    'citedDocCnt' => [
                        'filter' => [
                            'range' => [
                                'citation_relate_count' => [
                                    'gte' => 1
                                ]
                            ]
                        ] ,
                        'aggs' => [
                            'citedTotalCnt' => [
                                'sum' => [
                                    'field' => 'citation_relate_count'
                                ]
                            ]
                        ]
                    ] ,
                    'authorCnt' => [
                       'cardinality' => [
                           'field' => 'author_list.keyword'
                       ]
                    ],
                    'orgCnt' => [
                        'cardinality' => [
                            'field' => 'organization_parsed.keyword'
                        ]
                    ],
                    'docStat' => [
                        'terms' => [
                            'field' => 'year' ,
                            'order' => [
                                '_key' => 'asc'
                            ] ,
                            'size' => 10
                        ] ,

                        'aggs' => [
                            'citedPerYear' => [
                                'sum' => [
                                    'field' => 'citation_relate_count'
                                ]
                            ]
                        ]
                    ],
                    'keywordCnt' => [
                        'terms' => [
                            'field' => 'keyword_list.keyword' ,
                            'order' => [
                                '_count' => 'desc'
                            ] ,
                            'size' => 20
                        ]
                    ]
                ]
            ]
        ];

        $client = $this->getEsClient();
        $result = $client->search($params);

        /**
         * 发文量
         */
        $total = $result['hits']['total'];

        /**
         * 被引量
         */
        $citedTotalCnt = $result['aggregations']['citedDocCnt']['citedTotalCnt']['value'];

        /**
         * 作者数
         */
        $authorCnt = $result['aggregations']['authorCnt']['value'];

        /**
         * 机构数
         */
        $orgCnt = $result['aggregations']['orgCnt']['value'];

        /**
         * 篇均被引量 citedDocCnt／citedTotalCnt
         */
        $citedDocCnt = $result['aggregations']['citedDocCnt']['doc_count'];

        if(0 == $citedTotalCnt) {
            $article_Average_cited_count = 0;
        } else {
            $article_Average_cited_count = round($citedDocCnt / $citedTotalCnt , 2);
        }

        $citedTrend = $result['aggregations']['docStat']['buckets'];
        foreach($citedTrend as $key => $value) {
            $newCitedTrend[$key]['key']       = $value['key'];
            $newCitedTrend[$key]['doc_count'] = $value['citedPerYear']['value'];
        }

        $albumCountDetail = [
            /**
             * 统计
             */
            //'total'           => $total ,
            'cited_total_Cnt'   => $citedTotalCnt ,
            //'author_count'    => $authorCnt ,
            //'org_count'       => $orgCnt,
            //'article_Average_cited_count' => $article_Average_cited_count,
            /**
             * 统计图
             */
            'post_trend'      => $result['aggregations']['docStat']['buckets'] ,
            'cited_trend'     => $newCitedTrend ?? [],
            'research_topic'  => $result['aggregations']['keywordCnt']['buckets'] ,
        ];

        return $albumCountDetail;
    }


    /**
     * 根据主题获取专辑名
     */
    protected function getAlbum($specialName)
    {
        $index = $this->currentLanguage();
        $params = [
            'index'   => $index ,
            '_source' => 'album',
            'size'    => 1,
            'body' => [
                'query' => [
                    'bool' => [
                        'filter' => [
                            'term' => [
                                'special_name.keyword' => $specialName
                            ]
                        ]
                    ]
                ]
            ]
        ];
        $client = $this->getEsClient();
        $result = $client->search($params);
        return $result['hits']['hits'][0]['_source']['album'] ?? [];
    }

}

