package com.yeejoin.equipmanage.thread;

import ch.qos.logback.core.joran.conditional.ElseAction;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.listener.CarIotNewListener;
import com.yeejoin.equipmanage.service.ICarService;
import com.yeejoin.equipmanage.service.IWlCarMileageService;
import com.yeejoin.equipmanage.utils.CarUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.jfree.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
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.List;
import java.util.Timer;
import java.util.concurrent.TimeUnit;

public class
ThreadCar extends Thread {
    Logger logger = LoggerFactory.getLogger(ThreadCar.class);
    private IWlCarMileageService iWlCarMileageService;

    private IotFeign iotFeign;
    private String topic;
    private Long clippingTime;
    ICarService iCarService;
    private JSONObject jsonObject;

    public ThreadCar(String topic, JSONObject jsonObject, IWlCarMileageService iWlCarMileageService, IotFeign iotFeign, ICarService iCarService, Long clippingTime) {
        this.topic = topic;
        this.jsonObject = jsonObject;
        this.iWlCarMileageService = iWlCarMileageService;
        this.iotFeign = iotFeign;
        this.iCarService = iCarService;
        this.clippingTime = clippingTime;
    }

    @Override
    public void run() {
        //toDo
        // 获取最后一个有坐标的数据
        JSONObject lastObj = null;
        WlCarMileage last = null;
        String measurement = topic.split("/")[0];
        String deviceName = topic.split("/")[1];
        String iotCode = measurement + deviceName;
        try {
            Long startTime = System.currentTimeMillis();
            logger.info("=============================================" + topic + "结束坐标开始计时=======================================");
            this.sleep(clippingTime);
            //业务处理
            //如果十分钟没有坐标,则需要设置结束标记
            // 获取结束坐标
            last = iWlCarMileageService
                    .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 i = 0; i < list.size(); i++) {
                    JSONObject Obj = JSONObject.parseObject(JSONObject.toJSONString(list.get(i)));
                    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(i));
                        // 获取第一个不为空的坐标
                        if (lastObj == null) {
                            lastObj = Obj;
                        }
                    }
                }
                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);
                    logger.info("---过滤后last信息为null时的数据：：" + JSONObject.toJSONString(last));
                }
                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.setTakeTime(takeTime);
                last.setEndLongitude(endLongitude);
                last.setEndLatitude(endLatitude);
                last.setEndTime(endTime);
                last.setEndName(CarUtils.getAddress(endLongitude, endLatitude));
                //原来的写法不够健壮，如果上报的数据为double写法则会直接报凑错
                try {
                    Double.valueOf(jsonObject.getDoubleValue("FireCar_Speed")).intValue();
                    if (ObjectUtils.isEmpty(lastObj.containsKey("FireCar_Speed"))) {
                        last.setEndSpeed(0);
                    } else {
                        last.setEndSpeed(Double.valueOf(jsonObject.getString("FireCar_Speed")).intValue());
                    }
                } catch (Exception exception) {
                    last.setEndSpeed(0);
                }
                double travel = 0.0;
                // 获取里程
                for (int i = 0; i < filterList.size() - 1; i++) {
                    JSONObject start = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(i)));
                    JSONObject end = JSONObject.parseObject(JSONObject.toJSONString(filterList.get(i + 1)));
                    travel += CoordinateUtil.distance(start.getDoubleValue("FireCar_Latitude"),
                            start.getDoubleValue("FireCar_Longitude"), end.getDoubleValue("FireCar_Latitude"),
                            end.getDoubleValue("FireCar_Longitude"));
                }
                Double travle =new BigDecimal(travel / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                logger.info("---------------------本次里程：："+travle+"---------------------------------------");
                last.setTravel(travle);
                
                iWlCarMileageService.updateById(last);
                Long lastTime = System.currentTimeMillis();
                logger.info("---正常时获取到的获取last信息：：" + JSONObject.toJSONString(last));
                logger.info("--------------" + topic + "结束坐标成功::花费时间====" + String.valueOf((lastTime - startTime) / 60000) + "分钟-------------------------");
                logger.info("============================================================更新结束坐标成功==============================================：" + topic);
                //从缓存信息中移除运行完成的线程与坐标信息
                CarIotNewListener.deviceInfo.remove(iotCode);
            }
        } catch (Exception exception) {
            if (last != null) {
                logger.info("---异常时获取到的获取last信息：：" + JSONObject.toJSONString(last));
                iWlCarMileageService.updateById(last);
            }
        } finally {
            logger.info("销毁车辆倒计时线程：：topic_" + topic);
        }
    }

}

