package com.tofly.gpsboot.controller.es;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.es.GpsUpload;
import com.tofly.es.dto.EsQueryDto;
import com.tofly.es.dto.StatisticalInfoDto;
import com.tofly.es.vo.InspectionTrackVo;
import com.tofly.es.vo.StatisticalInfoVo;
import com.tofly.gpsboot.service.calculate.ICalculateGpsService;
import com.tofly.gpsboot.service.comm.IDisposeDateService;
import com.tofly.gpsboot.service.es.IGpsUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;


/**
 * ES存储GPS信息
 *
 * @author admin
 * @date Thu Mar 18 00:00:00 CST 2021
 */
@RestController
@RequestMapping("/gps")
@Api(tags = "ES存储GPS信息")
public class GpsUploadController {

    @Autowired
    private IGpsUploadService iGpsUploadService;


    @Autowired
    private ICalculateGpsService iCalculateGpsService;

    @Autowired
    private IDisposeDateService disposeDateService;

    @ApiOperation(value = "新增GPS信息")
    @PostMapping
    public ResultRespone<Boolean> save(@RequestBody GpsUpload gpsUpload) {
        return ResultRespone.success(iGpsUploadService.saveGpsInfo(gpsUpload));
    }

    @ApiOperation(value = "批量新增GPS信息")
    @PostMapping("/saveBatch")
    public ResultRespone<Boolean> saveBatch(@RequestBody List<GpsUpload> gpsUploadList) {
        return ResultRespone.success(iGpsUploadService.saveBatchGpsInfo(gpsUploadList));
    }

    @ApiOperation(value = "修改GPS信息")
    @PutMapping
    public ResultRespone<Boolean> update(@RequestBody GpsUpload gpsUpload) {
        return ResultRespone.success(iGpsUploadService.updateGpsInfo(gpsUpload));
    }

    @ApiOperation(value = "根据ID获取GPS信息")
    @GetMapping("/findone")
    public ResultRespone<GpsUpload> get(String id) {
        return ResultRespone.success(iGpsUploadService.getByIdGpsInfo(id));
    }

    /**
     * 通过id删除GPS信息表
     *
     * @param id id
     * @return ResultRespone
     */
    @ApiOperation(value = "通过id删除GPS信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String")
    })
    @DeleteMapping("/{id}")
    public ResultRespone<Boolean> removeById(@PathVariable String id) {
        return ResultRespone.success(iGpsUploadService.removeByIdGpsInfo(id));
    }

    @ApiOperation(value = "分页获取GPS信息")
    @GetMapping("/page")
    public ResultRespone<Page<List<GpsUpload>>> get(Page page, @ModelAttribute EsQueryDto dto) {
        return ResultRespone.success(iGpsUploadService.getPageGpsInfo(page,dto));
    }

    @ApiOperation(value = "获取所有index的GPS信息")
    @GetMapping("/getAllPage")
    public ResultRespone<Page<List<GpsUpload>>> getAllPage(Page page, @ModelAttribute EsQueryDto dto) {
        return ResultRespone.success(iGpsUploadService.getAllPage(page,dto));
    }

    @ApiOperation(value = "获取所有index的GPS信息（非分页）")
    @GetMapping("/getAll")
    public ResultRespone<List<GpsUpload>> getAll(@ModelAttribute EsQueryDto dto) {
        return ResultRespone.success(iGpsUploadService.getAll(dto));
    }

    @ApiOperation(value = "获取所有GPS信息分段信息")
    @GetMapping("/getSection")
    public ResultRespone<List<String>> getSection(@ModelAttribute EsQueryDto dto) {
        return ResultRespone.success(iGpsUploadService.getSectionGps(dto));
    }

    @ApiOperation(value = "获取统计信息")
    @PostMapping("/statisticalInfo")
    public ResultRespone<List<StatisticalInfoVo>> getStatisticalInfo(@RequestBody StatisticalInfoDto dto){
        List<StatisticalInfoVo> statisticalInfo = iCalculateGpsService.getStatisticalInfo(dto);
        return  ResultRespone.success(statisticalInfo);
    }


    @ApiOperation(value = "GPS统计信息计算")
    @PostMapping("/calculateGps")
    public ResultRespone<Object> getCalculateGps(){
        iCalculateGpsService.CalculateGps();
        return  ResultRespone.success(true);
    }


    @ApiOperation(value = "巡检轨迹查询")
    @GetMapping("/inspectionTrackQuery")
    public ResultRespone<InspectionTrackVo> inspectionTrackQuery(Page page, @ModelAttribute EsQueryDto dto) {
        InspectionTrackVo vo = new InspectionTrackVo();
        // 判断参数是否传入 部门ID 或 用户id
        Long userId = dto.getUserId();
        Long deptId = dto.getDeptId();
        String userIds = disposeDateService.getDeptUsers(userId,deptId);
        dto.setUserIds(userIds);
        // 统计
        List<GpsUpload> all = iGpsUploadService.getAll(dto);
        // 总里程 km
        BigDecimal totalMileage = all.stream().map(GpsUpload::getDistance).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(1000),4,BigDecimal.ROUND_HALF_UP);
        // 总耗时 h
        BigDecimal totalTimeConsuming = all.stream()
                .filter(g->0!=BigDecimal.ZERO.compareTo(g.getDistance()))
                .map(GpsUpload::getGpsTimespan).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(3600),4,BigDecimal.ROUND_HALF_UP);
        // 总平均速度 km/h
        BigDecimal overallAverageSpeed = BigDecimal.ZERO;
        if(0 != BigDecimal.ZERO.compareTo(totalTimeConsuming)){
            overallAverageSpeed = totalMileage.divide(totalTimeConsuming, 2, BigDecimal.ROUND_HALF_UP);
        }

        Page pageGpsInfo = iGpsUploadService.getPageGpsInfo(page, dto);
        vo.setTotalMileage(totalMileage);
        vo.setTotalTimeConsuming(totalTimeConsuming);
        vo.setOverallAverageSpeed(overallAverageSpeed);
        vo.setPageGpsInfo(pageGpsInfo);
        return ResultRespone.success(vo);
    }

}
