package org.jeecg.modules.sensor.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.device.entity.BuDevice;
import org.jeecg.modules.device.service.IBuDeviceService;
import org.jeecg.modules.sensor.entity.*;
import org.jeecg.modules.sensor.model.SensorDataHourStatistics;
import org.jeecg.modules.sensor.model.TableNameStatistics;
import org.jeecg.modules.sensor.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static kotlin.reflect.jvm.internal.impl.builtins.StandardNames.FqNames.list;


/**
 * @Description 设备传感器数据表
 * @Author
 * @Date  2021-02-07
 * @Version V1.0
 */
@Api(tags="设备传感器数据表")
@RestController
@RequestMapping("/sensor/buSensorDeviceData")
@Slf4j
public class BuSensorDeviceDataController extends JeecgController<BuSensorDeviceData, IBuSensorDeviceDataService> {
	@Autowired
	private IBuSensorDeviceDataService buSensorDeviceDataService;
	@Autowired
	private IBuSensorService buSensorService;
	@Autowired
	private IBuDeviceService buDeviceService;
	@Autowired
	private IBuSensorTypeService buSensorTypeService;
	/**
	 * 分页列表查询
	 *
	 * @param buSensorDeviceData;
	 * @param pageNo;
	 * @param pageSize;
	 * @param req;
	 * @return ;
	 */
	@AutoLog(value = "设备传感器数据表-分页列表查询")
	@ApiOperation(value="设备传感器数据表-分页列表查询", notes="设备传感器数据表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(BuSensorDeviceData buSensorDeviceData,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BuSensorDeviceData> queryWrapper = QueryGenerator.initQueryWrapper(buSensorDeviceData, req.getParameterMap());
		Page<BuSensorDeviceData> page = new Page<BuSensorDeviceData>(pageNo, pageSize);
		IPage<BuSensorDeviceData> pageList = buSensorDeviceDataService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	// 根据开始结束时间筛选数据存储时刻
	@GetMapping(value = "/selectList")
	public Result<?> selectList(@RequestParam(name="beginTime", required = true) String beginTime,
								@RequestParam(name="endTime", required = true) String endTime) {
		List<String> times = buSensorDeviceDataService.getSelectTimes(beginTime,endTime);
		return Result.OK(times);
	}
//	 传感器电压数据
//	@GetMapping(value = "/getCountUData")
//	public Result<?> getCountUData(@RequestParam(name="node", required = true) String node,
//								   @RequestParam(name="beginTime", required = true) String beginTime,
//								   @RequestParam(name="endTime", required = true) String endTime){
//		List<BuSensorDeviceData> list = buSensorDeviceDataService.getTestData(node,beginTime,endTime);
//		JSONObject obj = new JSONObject();
//		List<Date> xList=new ArrayList<>();
//		for (BuSensorDeviceData buSensorDeviceData : list) {
//			xList.add(buSensorDeviceData.getTime());
//		}
//		Double[] Ux = new Double[list.size()];
//		Double[] Vx = new Double[list.size()];
//		Double[] Wx = new Double[list.size()];
//		for (int n=0; n<list.size(); n++){
//			Ux[n] = Double.valueOf(list.get(n).getUdy());
//		}
//		for (int n=0; n<list.size(); n++){
//			Vx[n] = Double.valueOf(list.get(n).getVdy());
//		}
//		for (int n=0; n<list.size(); n++){
//			Wx[n] = Double.valueOf(list.get(n).getWdy());
//		}
//		obj.put("x",xList);
//		obj.put("u",Ux);
//		obj.put("v",Vx);
//		obj.put("w",Wx);
//		return Result.OK(obj);
//	}
	// 传感器电流数据
//	@GetMapping(value = "/getCountIData")
//	public Result<?> getCountIData(@RequestParam(name="node", required = true) String node,
//								   @RequestParam(name="beginTime", required = true) String beginTime,
//								   @RequestParam(name="endTime", required = true) String endTime){
//		List<BuSensorDeviceData> list = buSensorDeviceDataService.getTestData(node,beginTime,endTime);
//		JSONObject obj = new JSONObject();
//		List<Date> xList=new ArrayList<>();
//		for (BuSensorDeviceData buSensorDeviceData : list) {
//			xList.add(buSensorDeviceData.getTime());
//		}
//		Double[] Ux = new Double[list.size()];
//		Double[] Vx = new Double[list.size()];
//		Double[] Wx = new Double[list.size()];
//		for (int n=0; n<list.size(); n++){
//			Ux[n] = Double.valueOf(list.get(n).getUdl());
//			Vx[n] = Double.valueOf(list.get(n).getVdl());
//			Wx[n] = Double.valueOf(list.get(n).getWdl());
//		}
//		obj.put("x",xList);
//		obj.put("u",Ux);
//		obj.put("v",Vx);
//		obj.put("w",Wx);
//		return Result.OK(obj);
//
//		List<BuSensorDeviceData> list = buSensorDeviceDataService.getTestData(node,time);
//		JSONObject obj = new JSONObject();
//		List<String> xList=new ArrayList<>();
//		List<String> yList=Arrays.asList(list.get(0).getDatai1().split(" "));
//		List<Double> yLists=new ArrayList<>();
//		for (String s : yList) {
//			yLists.add(Convert.toDouble(s));
//		}
//		BuSensorData buSensorData = buSensorDataService.getById(1);
//		double time1 = Double.parseDouble(buSensorData.getCollectTime());
//		double time2 = Double.parseDouble(buSensorData.getCollectInterval());
//		BigDecimal j = new BigDecimal(Double.toString(0)) ;
//		BigDecimal k = new BigDecimal(Double.toString(time1 / time2)) ;
//		for (int i=0;i<yList.size();i++){
//			if (j.doubleValue() > time1){
//				break;
//			}else {
//				String x = String.valueOf(j.doubleValue());
//				xList.add(x);
//				j = j.add(k);
//			}
//		}
//		obj.put("x",xList);
//		obj.put("y",yLists);
//		return Result.OK(obj);
//	}


	/**
	 *   添加
	 *
	 * @param buSensorDeviceData;
	 * @return ;
	 */
	@AutoLog(value = "设备传感器数据表-添加")
	@ApiOperation(value="设备传感器数据表-添加", notes="设备传感器数据表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody BuSensorDeviceData buSensorDeviceData) {
		buSensorDeviceDataService.save(buSensorDeviceData);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param buSensorDeviceData;
	 * @return ;
	 */
	@AutoLog(value = "设备传感器数据表-编辑")
	@ApiOperation(value="设备传感器数据表-编辑", notes="设备传感器数据表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody BuSensorDeviceData buSensorDeviceData) {
		buSensorDeviceDataService.updateById(buSensorDeviceData);
		return Result.OK("编辑成功!");
	}


//	@GetMapping(value="/timeDataStatistics")
//	public Result<?> timeDataStatistics(
//										  @RequestParam(name="beginTime",required = true) String beginTime,
//										  @RequestParam(name="endTime",required = true) String endTime,
//										  @RequestParam(name="deviceId",required = true) String deviceId,
//										  @RequestParam(name="sensorId",required = true) String sensorId){
//		String[] arr = sensorId.split(",");
//		String[] sensor = new String[10];
//		for (int j=0; j<arr.length; j++){
//			BuSensor buSensor = buSensorService.getById(arr[j]);
//			sensor[j] = buSensor.getDataValue();
//		}
//		List<String> result = Arrays.asList(sensor);
//		List<SensorDataStatistics> sensorDataStatisticsList = buSensorDeviceDataService.timeDataStatistics(beginTime,endTime,deviceId,result);
//		return Result.OK(sensorDataStatisticsList);
//	}
	// 根据开始结束时间、设备id、传感器id筛选
//	@GetMapping(value="/timeDataStatistics")
//	public Result<?> timeDataStatistics(
//			@RequestParam(name="beginTime",required = true) String beginTime,
//			@RequestParam(name="endTime",required = true) String endTime,
//			@RequestParam(name="deviceId",required = true) String deviceId,
//			@RequestParam(name="sensorId",required = true) String sensorId){
//		List<String> result = buSensorService.getValueByName(sensorId);
//		List<SensorDataStatistics> sensorDataStatisticsList = buSensorDeviceDataService.timeDataStatistics(beginTime,endTime,deviceId,result,sensorId);
//		return Result.OK(sensorDataStatisticsList);
//	}

	/**
	 * 查询动态表对应的传感器名称
	 */
	@GetMapping(value = "/getNameValue")
	public Result<?> getNameValue(@RequestParam(name="sensorId",required = true) String sensorId,
								  @RequestParam(name="deviceId",required = true) String deviceId) {
//		List<String> result = Arrays.asList(sensorId.split(","));
//		List<TableNameStatistics> tableNameStatistics = buSensorDeviceDataService.getNameValue(result);
		List<TableNameStatistics> tableNameStatistics = buSensorDeviceDataService.getNameValue(sensorId,deviceId);
		Iterator<TableNameStatistics> it = tableNameStatistics.iterator();
		while (it.hasNext()) {
			TableNameStatistics tab = it.next();
			if (!tab.getDataValue().contains("电池电压"))
				continue;
			it.remove();
		}
		return Result.OK(tableNameStatistics);
	}
	//查询动态表对应的数据值
	@GetMapping(value = "/getValueData")
	public Result<?> getValueData(@RequestParam(name="sensorId",required = true) String sensorId,
								  @RequestParam(name="deviceId",required = true) String deviceId) {
//		List<String> result = Arrays.asList(sensorId.split(","));
//		List<SensorDataHourStatistics> sensorDataHourStatistics = buSensorDeviceDataService.getDataValue(result);
		List<SensorDataHourStatistics> sensorDataHourStatistics = buSensorDeviceDataService.getDataValue(sensorId,deviceId);
		return Result.OK(sensorDataHourStatistics);
	}
	//查询动态传感器name
	@GetMapping(value = "/getSensorDatas")
	public Result<?> getSensorDatas(@RequestParam(name="deviceId",required=true) String deviceId) {
		LambdaQueryWrapper<BuSensor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(BuSensor::getDeviceId,deviceId);
		List<BuSensor> list = buSensorService.list(lambdaQueryWrapper);
		return Result.OK(list);
	}

	//查询动态传感器name
	@GetMapping(value = "/getSensorDatasgg")
	public Result<?> getSensorDatasgg(@RequestParam(name="deviceId",required=true) String deviceId) {
		LambdaQueryWrapper<BuSensor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(BuSensor::getDeviceId,deviceId);
		// 历史数据曲线图中并未对这些设备进行处理
		lambdaQueryWrapper.notLike(BuSensor::getCheckItem, "PLC");
		lambdaQueryWrapper.notLike(BuSensor::getCheckItem, "水浸");
		lambdaQueryWrapper.notLike(BuSensor::getCheckItem, "报警");
		List<BuSensor> list = buSensorService.list(lambdaQueryWrapper);
//		if(deviceId.equals("1384437481886601217"))
//		{
//			if(list.get(17).getCheckItem().equals("PLC输入"))
//			{
//				System.out.println("移除PLC选项");
//				list.remove(list.size() - 1);
////			    list = new ArrayList<>(list.subList(0, list.size() - 1));
//			}
//		}

		return Result.OK(list);
	}


	@GetMapping(value = "/getTimeDatas")
	public Result<?> getTimeDatas(@RequestParam(name="deviceId",required=true)String deviceId,
								  @RequestParam(name="sensorId",required=true)String sensorId,
								  @RequestParam(name="year",required=true)String year,
								  @RequestParam(name="month",required=true)String month) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<BuSensorDeviceData> list =new ArrayList<>();
		List<String> number = new ArrayList<>();
		BuSensor buSensor = buSensorService.getBySensorId(deviceId,sensorId);
//		BuSensorType buSensorType = buSensorTypeService.getById(buSensor.getTypeId());
//		String str = "";
//		if(month.length()<2){
//			str="0"+month;
//		}else {
//			str=month;
//		}
		list = buSensorDeviceDataService.getAllTimeData(buSensor.getId(),year,month);
		List<Date> collect = list.stream().map(BuSensorDeviceData::getCreateTime).collect(Collectors.toList());
		for (Date date : collect) {
			number.add(sdf.format(date).substring(5));
		}
		return Result.OK(number.stream().distinct().collect(Collectors.toList()));
	}
	@GetMapping(value = "/getHistoryTimeDatas")//获取日历表数据
	public Result<?> getByCheckName(@RequestParam(name="deviceId",required=true)String deviceId,
								  @RequestParam(name="name",required=true)String name,
									@RequestParam(name="sensorId",required=true)String sensorId,
								  @RequestParam(name="year",required=true)String year,
								  @RequestParam(name="month",required=true)String month) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<BuSensorDeviceData> list =new ArrayList<>();
		List<String> number = new ArrayList<>();
		LambdaQueryWrapper<BuSensor> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(BuSensor::getDeviceId,deviceId);
		queryWrapper.eq(BuSensor::getId,sensorId);
//		queryWrapper.eq(BuSensor::getName,name);
		BuSensor buSensor = buSensorService.list(queryWrapper).get(0);
//		//传感器类型表
//		BuSensorType buSensorType = buSensorTypeService.getById(buSensor.getTypeId());
//		String str = "";
//		if(month.length()<2){
//			str="0"+month;
//		}else {
//			str=month;
//		}
		list = buSensorDeviceDataService.getAllTimeData(buSensor.getId(),year,month);
		List<Date> collect = list.stream().map(BuSensorDeviceData::getCreateTime).collect(Collectors.toList());
		for (Date date : collect) {
			number.add(sdf.format(date).substring(5));
		}
		return Result.OK(number.stream().distinct().collect(Collectors.toList()));
	}
	@GetMapping(value = "/getCalendarData")
	public Result<?> getCalendarData(@RequestParam(name="year",required=true)String year,
									@RequestParam(name="month",required=true)String month) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<BuSensorDeviceData> datelist =new ArrayList<>();
		List<BuSensorDeviceData> calendarDataList = buSensorDeviceDataService.getCalendarData(year, month);
		for (BuSensorDeviceData buSensorDeviceData : calendarDataList) {
			BuSensorDeviceData buSensorDeviceData1 = new BuSensorDeviceData();
			String format = sdf.format(buSensorDeviceData.getCreateTime());
			buSensorDeviceData1.setMonthDay(format.substring(5));
			buSensorDeviceData1.setDeviceNameList(Arrays.asList(buSensorDeviceData.getDeviceName().split(",")));
			datelist.add(buSensorDeviceData1);
		}
		return Result.OK(JSONObject.toJSONString(datelist)); // 确保返回 JSON 字符串
	}
	@GetMapping(value = "/getHolidays")
	public Result<?> getHolidays(@RequestParam(name="year", required = true) String year) {
		ArrayList<Object> holidays = new ArrayList<>();

		// 示例节假日数据（可以替换为从数据库/文件加载）
		holidays.add(new Holiday(year + "-01-01", "元旦", true));
		holidays.add(new Holiday(year + "-05-01", "劳动节", true));
		holidays.add(new Holiday(year + "-10-01", "国庆节", true));
		holidays.add(new Holiday(year + "-06-10", "端午节", true));

		return Result.OK(holidays);
	}

	public class Holiday {
		private String date; // 格式: yyyy-MM-dd
		private String name;
		private boolean isHoliday;

		public Holiday(String date, String name, boolean isHoliday) {
			this.date = date;
			this.name = name;
			this.isHoliday = isHoliday;
		}

		// Getters and Setters
		public String getDate() {
			return date;
		}

		public void setDate(String date) {
			this.date = date;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public boolean isHoliday() {
			return isHoliday;
		}

		public void setHoliday(boolean holiday) {
			isHoliday = holiday;
		}
	}
	/**
	 *   通过id删除
	 *
	 * @param id;
	 * @return ;
	 */
	@AutoLog(value = "设备传感器数据表-通过id删除")
	@ApiOperation(value="设备传感器数据表-通过id删除", notes="设备传感器数据表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		buSensorDeviceDataService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids;
	 * @return ;
	 */
	@AutoLog(value = "设备传感器数据表-批量删除")
	@ApiOperation(value="设备传感器数据表-批量删除", notes="设备传感器数据表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.buSensorDeviceDataService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id;
	 * @return ;
	 */
	@AutoLog(value = "设备传感器数据表-通过id查询")
	@ApiOperation(value="设备传感器数据表-通过id查询", notes="设备传感器数据表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		BuSensorDeviceData buSensorDeviceData = buSensorDeviceDataService.getById(id);
		if(buSensorDeviceData==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(buSensorDeviceData);
	}

    /**
    * 导出excel
    *
    * @param request;
    * @param buSensorDeviceData;
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BuSensorDeviceData buSensorDeviceData) {
        return super.exportXls(request, buSensorDeviceData, BuSensorDeviceData.class, "设备传感器数据表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request;
    * @param response;
    * @return ;
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BuSensorDeviceData.class);
    }

}
