package com.tofly.gpsboot.custom.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.es.CarGpsUpload;
import com.tofly.gpsboot.config.car.CommonConfig;
import com.tofly.gpsboot.custom.mapper.CustomCarMapper;
import com.tofly.gpsboot.custom.service.CustomCarService;
import com.tofly.api.es.SnwsGpsClient;
import com.tofly.gpsboot.service.car.CarBaseinfoService;
import com.tofly.pojo.car.CarBaseinfo;
import com.tofly.pojo.car.CarOil;
import com.tofly.pojo.car.cusom.CarUploadSearch;
import com.tofly.pojo.car.cusom.GpsCarSearch;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@AllArgsConstructor
public class CustomCarServiceImpl implements CustomCarService {
    private final CustomCarMapper customCarMapper;
    private final SnwsGpsClient dyrqGpsService;
    private final CarBaseinfoService carBaseinfoService;

    private List<Map> dyrqGps(Map param, List<Map> list) {
        ResultRespone resultRespone = dyrqGpsService.getListPage(param);
        if (resultRespone.getCode() != 1) {
            throw new ToflyDeniedException("es车辆分页信息查询失败");
        }
        LinkedHashMap result = (LinkedHashMap) resultRespone.getResult();
        List<Map> records = (List<Map>) result.get("records");
        list.addAll(records);
        int total = (int) result.get("total");
        if (total >= 10000) {
            param.remove("startTime");
            String startTime = (String) records.get(records.size() - 1).get("gpstime");
            param.put("startTime", startTime);
            return dyrqGps(param, list);
        } else {
            return list;
        }
    }


    @Override
    public ResultRespone getGpsCarList(Page page, GpsCarSearch gpsCarSearch) {
        Date startDate = gpsCarSearch.getStartTime();
        Date endDate = gpsCarSearch.getEndTime();
        //调用ES车辆最新状态查询接口
        if (gpsCarSearch.getStartTime() == null && gpsCarSearch.getEndTime() == null) {
            startDate = Date8Util.getStartTime();
            gpsCarSearch.setStartTime(startDate);
            endDate = Date8Util.getEndTime();
            gpsCarSearch.setEndTime(endDate);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-d HH:mm:ss");
        String startTime = sdf.format(startDate);
        String endTime = sdf.format(endDate);
        Map param = new HashMap();
        if (gpsCarSearch.getCarId() != null) {
            param.put("carId", gpsCarSearch.getCarId());
        }
        param.put("startTime", startTime);
        param.put("endTime", endTime);
        param.put("orderAsc", true);
        param.put("size", 10000);
        param.put("current", 1);
        //调用ES车辆最新状态查询接口
        /*ResultRespone resultRespone = dyrqGpsService.getListPage(param);
        if (resultRespone.getCode() != 1) {
            throw new ToflyDeniedException("es车辆分页信息查询失败");
        }
        LinkedHashMap result = (LinkedHashMap) resultRespone.getResult();
        List<Map> records = (List<Map>) result.get("records");*/

        List<Map> records = new ArrayList<>();
        dyrqGps(param, records);
        for (int i = 0; i < records.size(); i++) {
            CarBaseinfo carBaseinfo = carBaseinfoService.getOne(Wrappers.<CarBaseinfo>lambdaQuery().eq(records.get(i).get("carid") != null, CarBaseinfo::getId, records.get(i).get("carid")));
            String carNum = null;
            if (carBaseinfo != null) {
                carNum = carBaseinfo.getCarNumber();
            }
            records.get(i).put("carNum", carNum);
            //result.put("records", records);
        }
        //resultRespone.setResult(result);
        page.setRecords(records);
        page.setTotal(records.size());
        page.setSize(page.getSize());
        return ResultRespone.success(page);
    }

    @Override
    public List<String> getSection(GpsCarSearch gpsCarSearch) {
        Date startDate = gpsCarSearch.getStartTime();
        Date endDate = gpsCarSearch.getEndTime();
        //调用ES车辆最新状态查询接口
        if (gpsCarSearch.getStartTime() == null && gpsCarSearch.getEndTime() == null) {
            startDate = Date8Util.getStartTime();
            endDate = Date8Util.getEndTime();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-d HH:mm:ss");
        String startTime = sdf.format(startDate);
        String endTime = sdf.format(endDate);
        Map param = new HashMap();
        if (gpsCarSearch.getCarId() != null) {
            param.put("carId", gpsCarSearch.getCarId());
        }
        param.put("startTime", startTime);
        param.put("endTime", endTime);
        param.put("orderAsc", true);
        //调用ES车辆最新状态查询接口
        ResultRespone resultRespone = dyrqGpsService.getList(param);
        if (resultRespone.getCode() != 1) {
            throw new ToflyDeniedException("es车辆信息查询失败");
        }
        //截取分段信息
        Object result1 = resultRespone.getResult();
        System.out.println(result1);
        List<CarGpsUpload> resultList = JSON.parseArray(JSON.toJSONString(result1),CarGpsUpload.class);
        int pointNum = CommonConfig.POINT_NUM;
        int total = resultList.size();
        float section = (float) total / pointNum;
        List<String> result = new ArrayList<>();
        for (int i = 0; i < section; i++) {
            int start = i * pointNum;
            int end = start + pointNum - 1;
            if (section - i < 1) {
                end = start + total % pointNum - 1;
            }
            String startStr = resultList.get(start).getGpsTime() == null ? "" : Date8Util.format(resultList.get(start).getGpsTime(), Date8Util.DATE_TIME);
            String endStr = resultList.get(end).getGpsTime() == null ? "" : Date8Util.format(resultList.get(end).getGpsTime(), Date8Util.DATE_TIME);
            result.add("第" + (i + 1) + "段:" +startStr+ " - " + endStr);
        }
        return result;
    }


    @Override
    public Page<Map> listCarWatch(Page page, CarUploadSearch carUploadSearch) {
        Long deptId = carUploadSearch.getDeptId();
        Calendar cal = Calendar.getInstance();
        if (carUploadSearch.getDate() != null) {
            cal.setTime(carUploadSearch.getDate());
        }
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        Date startDate = cal.getTime();
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        Date endDate = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = sdf.format(startDate);
        String endTime = sdf.format(endDate);
        Long carId = carUploadSearch.getCarId();
        List<Map> list1 = new ArrayList<>();
        List<Map> list2 = customCarMapper.listCarWatch(carId, deptId, endDate);
        List<Map> list3 = customCarMapper.listCarWatch2(carId, deptId, endDate);
        list1.addAll(list2);
        list1.addAll(list3);
        Page<Map> result = new Page<>();
        result.setTotal(list1.size());
        BigDecimal lSize = new BigDecimal(list1.size());
        BigDecimal pSize = new BigDecimal(page.getSize());
        int pages = lSize.divide(pSize).setScale(0, BigDecimal.ROUND_CEILING).intValue();
        if (pages < 1) {
            pages = 1;
        }
        result.setPages(pages);
        result.setSize(page.getSize());
        result.setCurrent(page.getCurrent());
        //result.setRecords(list1);
        int pageBegin = (int) ((page.getCurrent() - 1) * page.getSize());
        int pageEnd = (int) (page.getCurrent() * page.getSize());
        if (page.getCurrent() == result.getPages() && list1.size() % page.getSize() == 0) {
            result.setRecords(list1.subList(pageBegin, pageEnd));
        } else if (page.getCurrent() == pages && list1.size() % page.getSize() != 0) {
            result.setRecords(list1.subList(pageBegin, list1.size()));
        } else if (page.getCurrent() < result.getPages()) {
            result.setRecords(list1.subList(pageBegin, pageEnd));
        } else if (page.getCurrent() > result.getPages()) {
            return result.setRecords(null);
        }
        List<Map> list = result.getRecords();
        try {
            for (int i = 0; i < list.size(); i++) {
                Map param = new HashMap();
                param.put("carId", list.get(i).get("carid"));
                param.put("startTime", startTime);
                param.put("endTime", endTime);
                ResultRespone resultRespone = dyrqGpsService.getCarLocation(param);
                if (resultRespone.getCode() != 1) {
                    throw new ToflyDeniedException("es车辆上传信息查询失败");
                }
                result.getRecords().get(i).putAll((Map) resultRespone.getResult());
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public Page<Map> getCarOilPage(Page page, CarOil carOil) {
        Page<Map> result = page.setRecords(customCarMapper.getCarOilPage(page, carOil));
        return result;
    }
}
