package com.slodon.b2b2c.controller.system.admin;

import com.slodon.b2b2c.aop.OperationLogger;
import com.slodon.b2b2c.core.config.DomainUrlUtil;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.model.goods.ESGoodsModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;

@Api(tags = "admin-索引初始化")
@RestController
@RequestMapping("v3/system/admin/search")
public class SearchInitController {

    @Resource
    private ESGoodsModel esGoodsModel;

    @ApiOperation("初始化es索引")
    @OperationLogger(option = "初始化es索引")
    @GetMapping("esInit")
    public JsonResult esInit(String webSite) throws IOException {
        //删除索引
        deleteByQuery(webSite);
        //重新把索引生成
        esGoodsModel.jobCreateIndexesES(DomainUrlUtil.SLD_ES_URL, DomainUrlUtil.SLD_ES_PORT, "init", webSite);

        return SldResponse.success("初始化成功");
    }

    private static RestHighLevelClient getESClient() {
        //阿里云Elasticsearch集群需要basic auth验证。
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        //访问用户名和密码为您创建阿里云Elasticsearch实例时设置的用户名和密码，也是Kibana控制台的登录用户名和密码。
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DomainUrlUtil.SLD_ES_USERNAME, DomainUrlUtil.SLD_ES_PASSWORD));
        return new RestHighLevelClient(RestClient.builder(new HttpHost(DomainUrlUtil.SLD_ES_URL, DomainUrlUtil.SLD_ES_PORT, "http")).setHttpClientConfigCallback(
                httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
        ));
    }

    /**
     * 删除索引
     */
    private static void deleteByQuery(String webSite) throws IOException {
        RestHighLevelClient client = getESClient();
        boolean indexExist = client.indices().exists(new GetIndexRequest(DomainUrlUtil.ES_INDEX_NAME + "_" + webSite), RequestOptions.DEFAULT);
        if (indexExist) {
            //索引存在，删除索引
            DeleteByQueryRequest request = new DeleteByQueryRequest(DomainUrlUtil.ES_INDEX_NAME + "_" + webSite);
            request.setConflicts("proceed");
            request.setQuery(QueryBuilders.matchAllQuery());
            client.deleteByQuery(request, RequestOptions.DEFAULT);
        }
        client.close();
    }
}
