package cn.com.energy.controller;

import cn.com.energy.config.InfluxDBConfig;
import cn.com.energy.model.DvMachinery;
import cn.com.energy.model.DvMachineryData;
import cn.com.energy.model.InfluxDBQuery;
import cn.com.energy.service.IDvMachineryDataService;
import cn.com.energy.service.IDvMachineryService;
import cn.com.v2.common.base.BaseController;
import cn.com.v2.common.domain.AjaxResult;
import cn.hutool.core.date.DateUtil;
import com.influxdb.client.QueryApi;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/api/energy")
public class EnergyApiController extends BaseController {

	@Autowired
	private InfluxDBConfig influxDBConfig;
	@Autowired
	private IDvMachineryDataService iDvMachineryDataService;
	@Autowired
	private IDvMachineryService iDvMachineryService;

	@ApiOperation(value = "获取数据", notes = "获取数据")
	@GetMapping("/getEnergyData")
	@ResponseBody
	public AjaxResult getEnergyData() {
		DvMachineryData dvMachineryData = new DvMachineryData();
		List<Map<String, Object>> dvMachineryDataList = iDvMachineryDataService.selectElectric(dvMachineryData);
		String val = "0";
		if(dvMachineryDataList.size() > 0 && dvMachineryDataList.get(0) != null){
			val = dvMachineryDataList.get(0).get("parser_data").toString();
			BigDecimal valBig = new BigDecimal(val).setScale(2, RoundingMode.UP);
			val = valBig.toString();
		}
		return success().put("data", val);
	}

	@ApiOperation(value = "获取数据", notes = "获取数据")
	@GetMapping("/getEnergyDayData")
	@ResponseBody
	public AjaxResult getEnergyDayData() {
		String now = DateUtil.format(new Date(), "yyyy-MM-dd");
		DvMachineryData dvMachineryData = new DvMachineryData();
		dvMachineryData.setCreateTimeStr(now);
		List<Map<String, Object>> dvMachineryDataList = iDvMachineryDataService.selectElectric(dvMachineryData);
		String val = "0";
		if(dvMachineryDataList.size() > 0 && dvMachineryDataList.get(0) != null){
			val = dvMachineryDataList.get(0).get("parser_data").toString();
			BigDecimal valBig = new BigDecimal(val).setScale(2, RoundingMode.UP);
			val = valBig.toString();
		}
		return success().put("data", val);
	}

	@ApiOperation(value = "获取设备数据", notes = "获取设备数据")
	@GetMapping("/getMachinery")
	@ResponseBody
	public AjaxResult getMachinery() {
		DvMachinery dvMachinery = new DvMachinery();
		List<DvMachinery> dvMachineryDataList = iDvMachineryService.selectDvMachineryList(dvMachinery);
		String val = dvMachineryDataList.size() + "";
		return success().put("data", val);
	}

//	@ApiOperation(value = "获取周能耗数据", notes = "获取数据")
//	@GetMapping("/getEnergyWeekData")
//	@ResponseBody
//	public AjaxResult getEnergyWeekData() {
//		List<Map<String,Object>> dvMachineryWeekDataList=iDvMachineryDataService.selectElectricByWeek();
//		return success().put("data", dvMachineryWeekDataList);
//	}

	@ApiOperation(value = "获取周能耗数据", notes = "获取数据")
	@GetMapping("/getEnergyWeekData")
	@ResponseBody
	public AjaxResult getEnergyWeekData() {
		String bucket = "home_assistant";
		QueryApi queryApi = influxDBConfig.getClient(bucket).getQueryApi();
		InfluxDBQuery query = new InfluxDBQuery(); // 构建查询语句
		query.setBucket(bucket);
		query.setMeasurement("Wh");

		// 获取当前 UTC 时间的0点
		ZonedDateTime utcMidnight = ZonedDateTime.now(ZoneOffset.UTC)
				.minusDays(7)         // 7天前
				.withHour(0)
				.withMinute(0)
				.withSecond(0)
				.withNano(0);
		// 格式化为 ISO-8601
		String formatted = utcMidnight.format(DateTimeFormatter.ISO_INSTANT);

		query.setTimeRangeStart(formatted);
		query.setWindowPeriod("1d");
		query.setAggregateFunction("last");
		query.setFields(new String[]{"value"});
		query.setSources(new String[]{"HA"});
		String fluxQuery = query.buildFlux();
		// 查询数据
		List<FluxTable> tables = queryApi.query(fluxQuery);
		List<FluxRecord> records = tables.get(0).getRecords();
		List<Double> values = new ArrayList<>(); // 创建空列表存储数据
		for (int i = 0; i < records.size(); i++) {
			values.add(0d);
		}
		for (FluxTable table : tables) { // 遍历表格获取数据
			int i = 0;
			for (FluxRecord record : table.getRecords()) {
				if (record.getValue() != null) {
					double v = Double.parseDouble(record.getValue().toString());
					Double d = values.get(i);
					d += v;
					values.set(i, d);
				}
				i++;
			}
		}
		List<Map<String,Object>> data = new ArrayList<>();
		for (int i = 0; i < records.size(); i++) { // 装填数据
			FluxRecord record = records.get(i);
			if (i == values.size() - 1) break;
			Map<String,Object> map = new HashMap<>();
			map.put("day", record.getTime().atZone(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("MM-dd")));
			Double newValue = values.get(i + 1);
			map.put("value", (newValue - values.get(i)) / 1000d);
			map.put("sum", (newValue - values.get(0)) / 1000d);
			data.add(map);
		}
		return success().put("data", data);
	}
}
