<?php
namespace app\controller;

use app\BaseController;
use Elasticsearch\ClientBuilder;
use think\facade\Session;
use think\response\Json;
use think\facade\Request;


class CommonEsController extends BaseController
{

    /**
     * es索引名称
     */
    protected $index = 'document_zh,document_en';

    /**
     * es文档名称
     */
    protected $type  = '_doc';

    /**
     * 分页每页展示数据条数
     */
    protected $pagesize = 25;

    /**
     * 查询字段
     */
    protected $fields   = ['_id' , 'title' , 'abstract' , 'year' , 'author' , 'url_md5' , 'index'];


    /**
     * 连接es
     */
    protected function getEsClient()
    {
        $client = ClientBuilder::create()->setHosts([\think\facade\Config::get('es')])
            ->setConnectionPool('\Elasticsearch\ConnectionPool\SimpleConnectionPool', [])
            ->setRetries(10)
            ->build();
        return $client;
    }


    /**
     * es数据查询统一接口
     */
    protected function esCommonGetData(array $params):array
    {
        /**
         * 连接es
         */
        $client = $this->getEsClient();

        /**
         * 获取查询结果
         */
        $result = $client->search($params);

        /**
         * 数据以及数据总数
         */
        $total  = $result['hits']['total'];
        $data   = $result['hits']['hits'];

        $newArray = [];

        /**
         * 获取实际返回数据源
         */
        foreach ($data as $val) {
            $newArray[] = $val['_source'];
        }

        return [
            'total' => $total ,
            'data'  => $newArray
        ];
    }

    /**
     * es match_phrase
     */
    protected function esCommonGet($select_field , $field_value , $size = 1 , $tag = 'stats' , $index = 'author_v1')
    {
        $params =  [
            'index' => $index ?? $this->index,
            'body'  => [
                'query' => [
                    'match_phrase' => [
                        $select_field => $field_value
                    ]
                ] ,
                'size' => $size ,
                'from' => 0
            ]
        ];
        $result = $this->esCommonGetData($params);
        return 'stats' === $tag ? $result['total'] : $result;
    }


    protected function _json_succ($data = [] , $code = 0 , $msg = 'Success')
    {
        return json(
            [
                'code' => $code ,
                'msg'  => $msg   ,
                'data' => $data
            ]
        );
    }


    protected function _json_error($msg = '' , $code = 1 , $data = null)
    {
        return json(
            [
                'code' => $code ,
                'msg'  => $msg  ,
                'data' => $data
            ]
        );
    }


    /**
     * 判断是英文还是中文
     */
    protected function getEsIndex($value , $tag = 'document')
    {
        $language = preg_match("/^[^\x80-\xff]+$/", $value) ? '_en' :'_zh';
        return $tag.$language;
    }

    /**
     * 当前es语言
     */
    protected function currentLanguage()
    {
        return 'document_zh,document_en';
        return Session::get('language') ?? 'document_zh';
    }

    /**
     * curl get 请求
     */
    protected function curlGetRequest($url , $authtoken = '9f25a6a368b8099acc9297828fb23e7908a8c5c5')
    {
        $curl_con = curl_init();

        curl_setopt($curl_con, CURLOPT_URL , $url);
        curl_setopt($curl_con, CURLOPT_HEADER, false);
        curl_setopt($curl_con, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($curl_con, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_con, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl_con, CURLOPT_FOLLOWLOCATION, true);             // 解决curl返回301

        curl_setopt($curl_con, CURLOPT_HTTPHEADER , array(
                "Content-Type: application/json;charset=utf-8",
                "Authorization: Token $authtoken"
            )
        );

        $res    = curl_exec($curl_con);
        $status = curl_getinfo($curl_con);
        curl_close($curl_con);

        if (isset($status['http_code']) && 200 == $status['http_code']) {
            return $res;
        } else {
            return false;
        }
    }


    /**
     * curl post 请求
     */
    protected function curlPostRequest($url , $params , $authtoken = '')
    {
        $data     = json_encode($params , JSON_UNESCAPED_UNICODE);
        $curl_con = curl_init();

        curl_setopt($curl_con, CURLOPT_URL , $url);
        curl_setopt($curl_con, CURLOPT_HEADER, false);
        curl_setopt($curl_con, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($curl_con, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl_con, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_con, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl_con, CURLOPT_FOLLOWLOCATION, true);             // 解决curl返回301
        if($authtoken) {
            curl_setopt($curl_con, CURLOPT_HTTPHEADER , array(
                    "Content-Type: application/json;charset=utf-8" ,
                    "Authorization: Token $authtoken"
                )
            );
        } else {
            curl_setopt($curl_con, CURLOPT_HTTPHEADER , array(
                    "Content-Type: application/json;charset=utf-8"
                )
            );
        }

        $res    = curl_exec($curl_con);
        $status = curl_getinfo($curl_con);
        curl_close($curl_con);

        if (isset($status['http_code']) && 200 == $status['http_code']) {
            return $res;
        } else {
            return false;
        }
    }

}
