<?php

namespace App\Services\goods;

use Api\PhpUtils\Common\BaseConvert;
use Api\PhpUtils\Elastic\ElasticUtil;

class ElasticGoodService
{
    const INDEX = "bp_goods";

    public static function createIndex($index)
    {
        $elasticClient = ElasticUtil::getInstance();
        $data = [
            'mappings' => [
                'properties' => [
                    'id' => [
                        'type' => 'keyword',
                    ],
                    'name' => [
                        'type' => 'text',
                    ],
                ]
            ]
        ];
        $res = $elasticClient->createIndex($index, $data);
        var_export($res);
    }

    /**
     * 写入 es 一条数据
     * @param $data
     * @param $id
     * @return array|callable
     */
    public static function indexDoc($id, $data)
    {
        $elasticClient = ElasticUtil::getInstance();
        return $elasticClient->indexDoc(self::INDEX, $data, $id);
    }

    /**
     * 修改 es 一条数据
     * @param $id
     * @param $data
     * @return array|callable
     */
    public static function updateDoc($id, $data)
    {
        $elasticClient = ElasticUtil::getInstance();
        return $elasticClient->updateDoc(self::INDEX, $id, $data);
    }

    public static function bulk($index)
    {
        $elasticClient = ElasticUtil::getInstance();

        $data = [
            ['index' => ['_index' => $index]],
            ['test_field' => '公安部：各地校车将享最高路权'],
            ['index' => ['_index' => $index]],
            ['test_field' => '中韩渔警冲突调查：韩警平均每天扣1艘中国渔船'],
            ['index' => ['_index' => $index]],
            ['test_field' => '中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首'],
        ];
        $res = $elasticClient->bulkIndexDoc($data);
        var_export($res);
    }

    /**
     * @param array $params
     * @return array|object
     */
    public static function searchDoc($params = [])
    {
        $sortType = 0;
        if (!empty($params["sort_type"])) {
            $sortType = $params["sort_type"];
        }
        $from = empty($params["from"]) ? 0 : (int)$params["from"];
        $size = empty($params["size"]) ? 10 : (int)$params["size"];

        $sortList = [
            ["price_sort" => "asc", "total_amount_sold" => "desc"],
            //todo 距离排序
            ["total_amount_sold" => "desc"],
            ["price_sort" => "asc"],
        ];
        $data = [
            "from" => $from,
            "size" => $size,
            "sort" => $sortList[$sortType],
        ];
        if (!empty($params["search_content"])) {
            $data["query"] = ["multi_match" => [
                "query" => $params["search_content"],
                "fields" => ["name", "category_1_name", "category_2_name", "desc"],
            ]];
        }

        $elasticClient = ElasticUtil::getInstance();
        $res = $elasticClient->searchDoc(self::INDEX, $data);

        $result = [];
        if (!empty($res["hits"]["total"]["value"])) {
            $result["count"] = $res["hits"]["total"]["value"];
            foreach ($res["hits"]["hits"] as $key => $source) {
                $result["list"][$key]["id"] = BaseConvert::decToOther($source["_source"]["id"]);
                $result["list"][$key]["goods_pic"] = $source["_source"]["goods_pic"];
                $result["list"][$key]["name"] = $source["_source"]["name"];
                $result["list"][$key]["inventory_rest"] = $source["_source"]["inventory_rest"];
                $result["list"][$key]["total_amount_sold"] = $source["_source"]["total_amount_sold"];
                $result["list"][$key]["original_price"] = $source["_source"]["original_price"];
                $result["list"][$key]["price"] = $source["_source"]["price"];
                $result["list"][$key]["status"] = $source["_source"]["status"];
                $result["list"][$key]["online_status"] = $source["_source"]["online_status"];
            }
        }
        //为避免空数据时候返回给前端错误结构
        return $result ? $result : (object)$result;
    }

}