/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.car.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.core.util.Date8Util;
import com.tofly.es.CarGpsUpload;
import com.tofly.gpsboot.mapper.car.CarGpsMapper;
import com.tofly.gpsboot.mapper.car.EsSaveInfoMapper;
import com.tofly.gpsboot.mapper.es.CarGpsUploadRepository;
import com.tofly.gpsboot.repository.EsCarGpsUploadService;
import com.tofly.gpsboot.service.car.CarGpsService;
import com.tofly.gpsboot.service.es.ICarGpsUploadService;
import com.tofly.gpsboot.util.EsSaveInfoUtil;
import com.tofly.pojo.car.CarGps;
import lombok.AllArgsConstructor;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

/**
 * 车辆GPS设备管理
 *
 * @author Zhangyu
 * @date Thu Apr 23 00:00:00 GMT+08:00 2020
 */
@Service("carGpsService")
@AllArgsConstructor
public class CarGpsServiceImpl extends ServiceImpl<CarGpsMapper, CarGps> implements CarGpsService {
    private final EsSaveInfoUtil esSaveInfoUtil;
    private final CarGpsUploadRepository esCarGpsUploadService;
    private final ElasticsearchTemplate elasticsearchTemplate;
    private final EsSaveInfoMapper esSaveInfoMapper;


    @Override
    public Boolean cargpsSave(CarGpsUpload esCarGpsUpload) {
        esSaveInfoUtil.checkInsertEsInfo(esCarGpsUploadService.getIndex());
        if (esCarGpsUpload.getUploadTime() == null) {
            esCarGpsUpload.setUploadTime(Date8Util.getCurrentDate());
        }
        if (esCarGpsUpload.getGpsTime() == null) {
            esCarGpsUpload.setGpsTime(Date8Util.getCurrentDate());
        }
        Long carId = esSaveInfoUtil.getCarId(esCarGpsUpload.getGpsId());
        esCarGpsUpload.setCarId(carId);
//        //查询最新记录，比较时间，判断速度是否大于设置的最大容差
//        EsCarGpsUpload lastest = queryLastestOne(elasticsearchTemplate, carId);
//        if (lastest != null){
//            double timeSpan = (esCarGpsUpload.getGpstime().getTime() - lastest.getGpstime().getTime())/1000;
//            //间隔时间小于5分钟的进行判断，超出5分钟直接录入
//            if (timeSpan < 300.0){
//                BigDecimal lastLng = lastest.getLocationLongitude();
//                BigDecimal lastLat = lastest.getLocationLatitude();
//                double maxSpeed = esSaveInfoMapper.getCarMaxSpeed();
//                double distance = getDistance(lastLng.doubleValue(),lastLat.doubleValue(),esCarGpsUpload.getLocationLongitude().doubleValue(), esCarGpsUpload.getLocationLatitude().doubleValue());
//                double speed = distance/timeSpan;
//                if (speed < maxSpeed){
//                    esCarGpsUploadService.save(esCarGpsUpload);
//                    return true;
//                }
//                else{
//                    return false;
//                }
//            }else{
//                esCarGpsUploadService.save(esCarGpsUpload);
//                return true;
//            }
//        }
//        else{
//            esCarGpsUploadService.save(esCarGpsUpload);
//            return true;
//        }

        esCarGpsUploadService.save(esCarGpsUpload);
        return true;


    }


    public CarGpsUpload queryLastestOne(ElasticsearchTemplate elasticsearchTemplate, Long carId) {
        BoolQueryBuilder qb = QueryBuilders.boolQuery();
        MatchQueryBuilder qbIsvalid = QueryBuilders.matchQuery("carid", carId);
        qb.must(qbIsvalid);
//        OrderItem orderItem = new OrderItem();
//        orderItem.setColumn("gpstime");
//        orderItem.setAsc(false);
//        page.addOrder(orderItem);
        PageRequest pageRequest = PageRequest.of(0, 1);
        SortBuilder sortBuilder = SortBuilders.fieldSort("gpstime").order(SortOrder.fromString("DESC"));
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(qb)
                .withSort(sortBuilder)
                .withPageable(pageRequest)
                .build();

        try {
            AggregatedPage<CarGpsUpload> list = elasticsearchTemplate.queryForPage(searchQuery, esCarGpsUploadService.getEntityClass());
            return list.getContent().get(0);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @param lng1 点1经度
     * @param lat1 点1纬度
     * @param lng2 点2经度
     * @param lat2 点2纬度
     * @return 两点距离，单位m
     */
    public static double getDistance(double lng1, double lat1, double lng2, double lat2) {
        Double EARTH_RADIUS = 6378.137; // 地球长半径  地球半径系数6370.996
        Double radLat1 = lat1 * Math.PI / 180.0;
        Double radLat2 = lat2 * Math.PI / 180.0;

        Double radLng1 = lng1 * Math.PI / 180.0;
        Double radLng2 = lng2 * Math.PI / 180.0;

        Double a = radLat1 - radLat2;
        Double b = radLng1 - radLng2;

        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS * 1000;
        //s = Math.round(s * 10000) / 10000;
        return s;
    }

}
