package com.example.repurchase.utils;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.GeoDistanceQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;
import java.util.HashMap;

/**
 * @Author: 黄树文
 * @Date: 2019/12/3 17:34
 */
public class HouseTagsUtils {


    public static Integer getHousePrice(RestHighLevelClient restHighLevelClient, HashMap<String, Double> latLngMaps, Double distance) throws IOException {

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        GeoDistanceQueryBuilder location1 = QueryBuilders.geoDistanceQuery("Location").point(latLngMaps.get("lat"), latLngMaps.get("lng"))
                .distance(distance, DistanceUnit.KILOMETERS);

        searchSourceBuilder.postFilter(location1);

        GeoDistanceSortBuilder sort = SortBuilders.geoDistanceSort("Location", latLngMaps.get("lat"), latLngMaps.get("lng"))
                .order(SortOrder.ASC).point(latLngMaps.get("lat"), latLngMaps.get("lng"));
        searchSourceBuilder.sort(sort);

        SearchRequest searchRequest = new SearchRequest("anjuke_data").source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHit = hits.getHits();
        if (searchHit.length == 0) {
            return getHousePrice(restHighLevelClient, latLngMaps, distance * 10);
        }

        Integer housePrice = Integer.parseInt(searchHit[0].getSourceAsMap().get("HousePrice").toString());
        return housePrice;
    }
}
