package com.njcn.executor.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.njcn.influxdb.config.InfluxDbConfig;
import com.njcn.influxdb.utils.InfluxDbUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * pqs
 * 电能量增量数据处理 10分钟执行一轮
 *
 * @author cdf
 * @date 2022/4/7
 */
@Slf4j
@Component
@AllArgsConstructor
public class ElectricCalJob {

    private final InfluxDbUtils influxDbUtils;

    private final InfluxDbConfig influxDbConfig;

    @XxlJob("ElectricCalJob")
    public void ElectricCalJob() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar startTime = Calendar.getInstance();

        startTime.add(Calendar.MINUTE, -40);
        String start = sdf.format(startTime.getTime());

        Calendar endTime = Calendar.getInstance();
        //endTime.add(Calendar.DAY_OF_MONTH,-8);
        String end = sdf.format(endTime.getTime());

        String sql = "select * from power_data where time > '" + start + "' and time < '" + end + "' order by time";
        List<Map<String, Object>> list = influxDbUtils.getResult(sql);

        if (CollectionUtil.isNotEmpty(list)) {
            Map lineTemMap = new HashMap<>();
            List<Map<String, Object>> insertObj = new ArrayList<>();
            list.stream().collect(Collectors.groupingBy((item) -> item.get("LineId"), Collectors.toList())).forEach(lineTemMap::put);
            lineTemMap.forEach((lineId, mapList) -> {
                List<Map<String, Object>> tmpList = (List) mapList;
                if (CollectionUtil.isNotEmpty(tmpList)) {
                    for (int i = 0; i < tmpList.size(); i++) {
                        if (i != 0) {
                            Map<String, Object> mapEnd = tmpList.get(i);
                            Map<String, Object> mapStart = tmpList.get(i - 1);
                            Long endT = (Long) mapEnd.get("time") + 28800;
                            Long startT = (Long) mapStart.get("time") + 28800;
                            if (endT > startT) {
                                Map<String, Object> map = new HashMap<>();
                                if (endT - startT == 60 * 15) {
                                    for (Entry<String, Object> entry : tmpList.get(i).entrySet()) {
                                        if (entry.getKey().equals("Phase") || entry.getKey().equals("LineId") || entry.getKey().equals("Stat_Method")) {
                                            map.put(entry.getKey(), entry.getValue());
                                        } else if (entry.getKey().equals("time")) {
                                            map.put(entry.getKey(), endT);
                                        } else {
                                            //定义 float最大值
                                            Float endThis = Float.parseFloat(entry.getValue().toString());
                                            Float startThis = Float.parseFloat(mapStart.get(entry.getKey()).toString());
                                            if (-1000000f == endThis || -1000000f == startThis) {
                                                map.put(entry.getKey(), -1000000f);
                                            } else {
                                                map.put(entry.getKey(), endThis - startThis);
                                            }
                                        }
                                    }
                                    insertObj.add(map);
                                } else {
                                    //缺少数据处理

                                }
                            } else {
                                log.error("时间起始顺序错误！");
                            }
                        }
                    }
                }
            });

            if (CollectionUtil.isNotEmpty(insertObj)) {
                BatchPoints batchPoints = BatchPoints.database(influxDbConfig.getDatabase()).build();
                for (Map<String, Object> it : insertObj) {
                    Point.Builder point = Point.measurement("power_data_add");
                    it.forEach((key, val) -> {
                        if (key.equals("LineId")) {
                            point.tag(key, val.toString());
                        } else if (key.equals("time")) {
                            point.time((Long) val, TimeUnit.SECONDS);
                        } else if (key.equals("Phase") || key.equals("Stat_Method")) {
                            point.addField(key, val.toString());
                        } else {
                            point.addField(key, (Float) val);
                        }
                    });
                    Point p = point.build();
                    batchPoints.point(p);
                }

                try {
                    influxDbUtils.batchInsert(batchPoints, TimeUnit.SECONDS);
                    HashMap<String, Map<String, Object>> hashMap = new HashMap<>();
                    for (int j = 0; j < insertObj.size(); j++) {
                        hashMap.put(insertObj.get(j).get("LineId").toString(), insertObj.get(j));
                    }
                    hashMap.forEach((key, val) -> {
                        Long t = (Long) val.get("time") * 1000 - 28800000;
                        String tt = Instant.ofEpochMilli((Long) val.get("time") * 1000).toString();
                        String sqlQs = "delete from power_data_add_Real where time< '" + tt + "' and LineId ='" + key + "'";
                        influxDbUtils.deleteMeasurementData(sqlQs);
                        Map<String, Object> filedss = new HashMap<>();
                        Map<String, String> tagss = new HashMap<>();
                        val.forEach((keytem, valtem) -> {
                            if (keytem.equals("time")) {

                            } else if (keytem.equals("LineId")) {
                                tagss.put(keytem, valtem.toString());
                            } else {
                                filedss.put(keytem, valtem);
                            }
                        });
                        influxDbUtils.insert("power_data_add_Real", tagss, filedss, t, TimeUnit.MILLISECONDS);
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            log.error(start + "——————" + end + "数据为空");
        }


    }

}
