package org.jeecg.modules.job;

import org.jeecg.modules.device.entity.BuDevice;
import org.jeecg.modules.device.entity.BuDeviceRunTime;
import org.jeecg.modules.device.service.IBuDeviceRunTimeService;
import org.jeecg.modules.device.service.IBuDeviceService;
import org.jeecg.modules.energy.entity.BuElectric;
import org.jeecg.modules.energy.service.IBuElectricService;
import org.jeecg.modules.sensor.entity.BuSensor;
import org.jeecg.modules.sensor.entity.BuSensorType;
import org.jeecg.modules.sensor.service.IBuSensorService;
import org.jeecg.modules.sensor.service.IBuSensorTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * 测试实用类 可删除
 * 通过修改为启动类，在项目启动时执行，来验证 DeviceRunTimeJob 中的定时统计方法，
 */
@Component
public class DeviceRunTimeStartupRunner implements CommandLineRunner {

    @Autowired
    private IBuDeviceService buDeviceService;
    @Autowired
    private IBuSensorService buSensorService;
    @Autowired
    private IBuSensorTypeService buSensorTypeService;
    @Autowired
    private IBuElectricService buElectricService;
    @Autowired
    private IBuDeviceRunTimeService buDeviceRunTimeService;


    @Override
    public void run(String... args) throws Exception {
//        try {
        List<BuDevice> list = buDeviceService.list();
        //构建参数
        for (BuDevice buDevice : list) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
            DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMdd");
            DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime now = LocalDateTime.now();
            String formattedDate = now.minusDays(1).format(formatter);
            List<BuSensor> buSensorElectric = buSensorService.getByCheckName(buDevice.getId(), "%电能%");
            try {
                for (BuSensor buSensor : buSensorElectric) {
                    BuSensorType buSensorType = buSensorTypeService.getById(buSensor.getTypeId());
                    //                    String tableName = buSensorType.getTableHead() + "_history_" + formattedDate;
                    String tableName = buSensorType.getTableHead() + "_history_" + buDevice.getTypeId() + "_" + buDevice.getDeviceCode() + "_" + formattedDate;
                    LocalDate today = LocalDate.now();
                    LocalDate yesterday = today.minusDays(1);
                    BuElectric buElectric1 = buElectricService.getYesterdayFirstData(tableName, buSensorElectric.get(0).getId(), yesterday.format(formatter2));
                    BuElectric buElectric2 = buElectricService.getYesterdayLastData(tableName, buSensorElectric.get(0).getId(), yesterday.format(formatter2));
                    if (buElectric1 == null || buElectric2 == null){
                        System.out.println(buDevice.getDeviceName() + "无数据");
                        continue;
                    }
                    BuDeviceRunTime buDeviceRunTime = new BuDeviceRunTime();
                    buDeviceRunTime.setDeviceId(buSensor.getDeviceId());
                    buDeviceRunTime.setStartPower(buElectric1.getEng());
                    buDeviceRunTime.setDeviceTypeId(buDevice.getDeviceTypeId());
                    buDeviceRunTime.setEndPower(buElectric2.getEng());
                    double power = Math.abs(buElectric2.getEng() - buElectric1.getEng());
                    //查询1天的数据，取非0有功功率的平均值
                    String avg = buElectricService.getAverage(tableName,buSensorElectric.get(0).getId(),yesterday.format(formatter2));
                    buDeviceRunTime.setPower(Double.parseDouble(String.format("%.2f", power)));
                    if (avg != null && Double.parseDouble(avg) != 0) {
                        buDeviceRunTime.setRunTime((int) (power / Double.parseDouble(avg) * 60 * 60));
                    } else {
                        buDeviceRunTime.setRunTime(0);
                    }
                    buDeviceRunTime.setCreateTime(Date.from(yesterday.atStartOfDay(ZoneId.from(ZoneOffset.ofHours(8))).toInstant()));
//                    buDeviceRunTimeService.save(buDeviceRunTime);
                }
            }catch (Exception e){
                System.out.println("数据查询异常：" + e);
                continue;
            }
        }
//        }catch (Exception ex){
//            System.out.println("设备运行时间计算任务报错：" + ex);
//        }finally {
//            System.out.println("设备运行时间计算任务完成！");
//        }
    }
}
