package com.njcn.executor.handler;

import com.njcn.energy.pojo.api.EleOnlineRateFeignClient;
import com.njcn.energy.pojo.dto.OnlineRateDTO;
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.InfluxDB;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 类的介绍：
 *
 * @author xuyang
 * @version 1.0.0
 * @createTime 2022/4/15 15:57
 */
@Slf4j
@Component
@AllArgsConstructor
public class EleOnlineRateJob {

    private final InfluxDbConfig influxDbConfig;

    private final InfluxDbUtils influxDbUtils;

    private final EleOnlineRateFeignClient eleOnlineRateFeignClient;

    @XxlJob("eleOnlineRateJobHandler")
    public void eleOnlineRateJobHandler() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)-1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.set(calendar2.get(Calendar.YEAR), calendar2.get(Calendar.MONTH), calendar2.get(Calendar.DAY_OF_MONTH)-1, 23, 59, 59);
        calendar2.set(Calendar.MILLISECOND, 0);
        String startTime = format.format(calendar.getTime());
        String endTime = format.format(calendar2.getTime());
        List<OnlineRateDTO> list = eleOnlineRateFeignClient.getDeviceTime(startTime,endTime).getData();
        createMeasurement(list,calendar.getTimeInMillis());
    }

    /**
     * 生成用能终端在线率表
     */
    private void createMeasurement(List<OnlineRateDTO> list, long time){
        List<String> records = new ArrayList<String>();
        list.forEach(item->{
            Map<String, String> tags = new HashMap<>();
            Map<String, Object> fields = new HashMap<>();
            tags.put("device_id",item.getDeviceId());
            fields.put("online_rate",item.getOnlineRate());
            Point point = influxDbUtils.pointBuilder("ele_online_rate", time, TimeUnit.MILLISECONDS, tags, fields);
            BatchPoints batchPoints = BatchPoints.database(influxDbConfig.getDatabase()).tag("device_id", item.getDeviceId()).retentionPolicy("").consistency(InfluxDB.ConsistencyLevel.ALL).build();
            batchPoints.point(point);
            records.add(batchPoints.lineProtocol());
        });
        influxDbUtils.batchInsert(influxDbConfig.getDatabase(),"", InfluxDB.ConsistencyLevel.ALL, records);
    };


}
