package com.yeejoin.equipmanage.thread;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.equipmanage.common.entity.Car;
import com.yeejoin.equipmanage.common.entity.WlCarMileage;
import com.yeejoin.equipmanage.common.utils.CoordinateUtil;
import com.yeejoin.equipmanage.fegin.IotFeign;
import com.yeejoin.equipmanage.service.ICarService;
import com.yeejoin.equipmanage.service.IWlCarMileageService;
import com.yeejoin.equipmanage.service.impl.CarServiceImpl;
import com.yeejoin.equipmanage.service.impl.WlCarMileageServiceImpl;
import com.yeejoin.equipmanage.utils.CarUtils;
import liquibase.pro.packaged.E;
import org.jfree.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class ThreadCarMileageTreatment extends Thread {
    Logger logger = LoggerFactory.getLogger(ThreadCarMileageTreatment.class);
    @Autowired
    private WlCarMileageServiceImpl wlCarMileageServiceImpl;

    @Autowired
    CarServiceImpl carServiceImpl;
    @Autowired
    private IotFeign iotFeign;
    @Value("${mileage.clippingtime}")
    private Long clipping_time;

    @Override
    public void run() {
        logger.info("----------------------------------------------------开始处理未结束里程---------------------------------");
        HashMap<String, String> hashMap = new HashMap<>();
        //toDo
        WlCarMileage last = null;
        JSONObject lastObj = null;
        Car car =null;
        List<WlCarMileage> wlCarMileageList = wlCarMileageServiceImpl.list(new QueryWrapper<WlCarMileage>().isNull("end_time"));
        for (int i = 0; i < wlCarMileageList.size(); i++) {
           car =  carServiceImpl.getOne(new QueryWrapper<Car>().eq("iot_code", wlCarMileageList.get(i).getIotCode()));
            String coordinateSting = String.valueOf(car.getLongitude()) + String.valueOf(car.getLatitude());
            hashMap.put(car.getIotCode(), coordinateSting);
        }
        try {
            Thread.sleep(clipping_time);
            for (int i = 0; i < wlCarMileageList.size(); i++) {
                WlCarMileage wlCarMileage =wlCarMileageList.get(i);
                 car = carServiceImpl.getOne(new QueryWrapper<Car>().eq("iot_code", wlCarMileage.getIotCode()));
                String coordinateSting = String.valueOf(car.getLongitude()) + String.valueOf(car.getLatitude());
                if (coordinateSting.equals(hashMap.get(car.getIotCode()))) {
                    String iotCode = car.getIotCode();
                    String measurement = "0THMcLKR";
                    String deviceName = iotCode.replace(measurement, "");
                    last = wlCarMileageServiceImpl
                            .getOne(new LambdaQueryWrapper<WlCarMileage>().eq(WlCarMileage::getIotCode, iotCode)
                                    .isNull(WlCarMileage::getEndLongitude).isNull(WlCarMileage::getEndLatitude)
                                    .orderByDesc(WlCarMileage::getStartTime).last("limit 1"));
                    ResponseModel<List<Object>> result = iotFeign.getLiveData(measurement, deviceName,
                            last.getStartTime(), new Date(new Date().getTime() + 2000));
                    List<Object> list = result.getResult();
                    if (list != null && list.size() > 0) {
                        // 过滤空坐标
                        List<Object> filterList = new ArrayList<Object>();
                        for (int j = 0; j < list.size(); j++) {
                            JSONObject Obj = JSONObject.parseObject(JSONObject.toJSONString(list.get(j)));
                            if (Obj.get("FireCar_Longitude") != null && Obj.get("FireCar_Latitude") != null
                                    && Obj.getDoubleValue("FireCar_Longitude") != 0
                                    && Obj.getDoubleValue("FireCar_Latitude") != 0) {
                                filterList.add(list.get(j));
                                // 获取第一个不为空的坐标
                                lastObj = Obj;
                            }
                        }
                        logger.info("----------------------------------------lastobj----------------------"+lastObj.toJSONString());
                        if (lastObj == null) {
                            lastObj = new JSONObject();
                            lastObj.put("FireCar_Longitude", last.getStartLongitude());
                            lastObj.put("FireCar_Latitude", last.getEndLatitude());
                            lastObj.put("time", 0);
                            lastObj.put("FireCar_Speed", 0);
                        }
                        double endLongitude = lastObj.getDoubleValue("FireCar_Longitude");
                        double endLatitude = lastObj.getDoubleValue("FireCar_Latitude");
                        Date endTime = new Date();
                        long takeTime = (endTime.getTime() / 1000 * 1000) - (last.getStartTime().getTime() / 1000 * 1000);
                        if(takeTime<0){
                            takeTime = 0-takeTime;
                        }
                        last.setEndLongitude(endLongitude);
                        last.setEndLatitude(endLatitude);
                        last.setEndTime(endTime);
                        last.setEndName(CarUtils.getAddress(endLongitude, endLatitude));
                        last.setEndSpeed(lastObj.getIntValue("FireCar_Speed"));
                        last.setTakeTime(takeTime);
                        double travel = 0.0;
                        // 获取里程
                        for (int k = 0; k < filterList.size() - 1; k++) {
                            JSONObject start = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(k)));
                            JSONObject end = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(k + 1)));
                            travel += CoordinateUtil.distance(start.getDoubleValue("FireCar_Latitude"),
                                    start.getDoubleValue("FireCar_Longitude"), end.getDoubleValue("FireCar_Latitude"),
                                    end.getDoubleValue("FireCar_Longitude"));
                        }
                        last.setTravel(new BigDecimal(travel / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
                        logger.info("----------------------------------------last----------------------"+lastObj.toJSONString());
//                        wlCarMileageServiceImpl.updateById(last);
                    }
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

}

