package org.jeecg.modules.device.controller;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.WebsocketConst;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.config.mybatis.ThreadLocalDataHelper;
import org.jeecg.modules.device.entity.*;
import org.jeecg.modules.device.entity.Export.ExportDeviceRisk;
import org.jeecg.modules.device.model.DeviceRiskAnalysis;
import org.jeecg.modules.device.model.StatusData;
import org.jeecg.modules.device.service.IBuDeviceOnlineService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.device.service.IBuDeviceService;
import org.jeecg.modules.device.service.IBuRiskItemService;
import org.jeecg.modules.device.service.IBuRiskItemValueService;
import org.jeecg.modules.energy.entity.*;
import org.jeecg.modules.energy.service.IBuAirQualityService;
import org.jeecg.modules.message.websocket.WebSocket;
import org.jeecg.modules.sensor.entity.BuSensor;
import org.jeecg.modules.sensor.service.IBuSensorService;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysAnnouncementService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.under.entity.Under;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: bu_device_online
 * @Author: jeecg-boot
 * @Date:   2024-05-09
 * @Version: V1.0
 */
@Api(tags="bu_device_online")
@RestController
@RequestMapping("/device/buDeviceOnline")
@Slf4j
public class BuDeviceOnlineController extends JeecgController<BuDeviceOnline, IBuDeviceOnlineService> {
	@Autowired
	private IBuDeviceOnlineService buDeviceOnlineService;
	@Autowired
	private IBuDeviceService buDeviceService;
	@Autowired
	private IBuSensorService buSensorService;
	@Autowired
	private IBuAirQualityService buAirQualityService;
	@Autowired
	private ISysAnnouncementService sysAnnouncementService;
	@Autowired
	private IBuRiskItemService buRiskItemService;
	@Autowired
	private IBuRiskItemValueService buRiskItemValueService;
	@Autowired
	private ISysUserService sysUserService;
	 @Resource
	 private WebSocket webSocket;

	/**
	 * 分页列表查询
	 *
	 * @param buDeviceOnline
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "bu_device_online-分页列表查询")
	@ApiOperation(value="bu_device_online-分页列表查询", notes="bu_device_online-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BuDeviceOnline>> queryPageList(BuDeviceOnline buDeviceOnline,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   @RequestParam(name="beginTime", required = false) String beginTime,
								   @RequestParam(name="endTime", required = false) String endTime,
								   HttpServletRequest req) {
		QueryWrapper<BuDeviceOnline> queryWrapper = QueryGenerator.initQueryWrapper(buDeviceOnline, req.getParameterMap());
		if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)){
			queryWrapper.between("time",beginTime,endTime);
		}
		queryWrapper.orderByDesc("time").orderByAsc("status");
		Page<BuDeviceOnline> page = new Page<BuDeviceOnline>(pageNo, pageSize);
		IPage<BuDeviceOnline> pageList = buDeviceOnlineService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@GetMapping(value = "/SpareList")
	public Result<?> SpareList(BuDeviceOnline buDeviceOnline,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   @RequestParam(name="beginTime", required = false) String beginTime,
								   @RequestParam(name="endTime", required = false) String endTime,
								   HttpServletRequest req) {
		QueryWrapper<BuDeviceOnline> queryWrapper = QueryGenerator.initQueryWrapper(buDeviceOnline, req.getParameterMap());
		if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)){
			queryWrapper.between("time",beginTime,endTime);
		}
		queryWrapper.eq("remind_type",5);
		Page<BuDeviceOnline> page = new Page<BuDeviceOnline>(pageNo, pageSize);
		IPage<BuDeviceOnline> pageList = buDeviceOnlineService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @GetMapping(value = "/listByUser")
	 public Result<?> listByUser(){
		 JSONObject obj = new JSONObject();
		 QueryWrapper<BuDeviceOnline> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("status",0).or().eq("status",3);
//		 queryWrapper.groupBy("device_id", "time", "test_item");
		 queryWrapper.orderByDesc("time").orderByAsc("status");
		 Page<BuDeviceOnline> page = new Page<BuDeviceOnline>(1, 10);
		 IPage<BuDeviceOnline> pageList = buDeviceOnlineService.page(page, queryWrapper);
		 List<BuDeviceOnline> records = pageList.getRecords();
		 obj.put("record",records);
		 obj.put("count",pageList.getTotal());
		 return Result.OK(obj);
	 }

	 @RequestMapping(value = "/getById", method = RequestMethod.GET)
	 public SysAnnouncement getById(@RequestParam String anntId) {
		 SysAnnouncement sysAnnouncement = sysAnnouncementService.getById(anntId);
//		 BuDeviceOnline buDeviceOnline = buDeviceOnlineService.getById(anntId);
//		 buDeviceOnline.setStatus(3);
//		 buDeviceOnlineService.updateById(buDeviceOnline);
		 return sysAnnouncement;
	 }

	 // 风险表批量忽略
	 @GetMapping(value = "/getBatchSee")
	 public Result<?> getBatchSee(@RequestParam(name="ids",required=true) String ids) {
		String[] list = ids.split(",");
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		for (String id : list){
			BuDeviceOnline buDeviceOnline = buDeviceOnlineService.getById(id);
			buDeviceOnline.setStatus(2);
			buDeviceOnline.setUser(user.getRealname());
			buDeviceOnline.setProcessingTime(new Date());
			buDeviceOnlineService.updateById(buDeviceOnline);
			//推送页面右上角重新查询风险项数量
			SysUser sysUser = sysUserService.getUserByName("admin");
			String userId = sysUser.getId();
			String[] userIds = userId.substring(0, (userId.length()-1)).split(",");
			JSONObject obj = new JSONObject();
			obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_RISK);
			obj.put(WebsocketConst.MSG_ID, buDeviceOnline.getId());
			obj.put(WebsocketConst.MSG_TXT, buDeviceOnline.getTestItem());
			webSocket.sendMessage(userIds, obj.toJSONString());
		}
		 return Result.OK("操作成功");
	 }

	 // 异常信息表单个信息查看
//	 @GetMapping(value = "/remind")
//	 public Result<?> remind(String data) {
//		 BuDeviceOnline buDeviceOnline = buDeviceOnlineService.getById(data);
//		 buDeviceOnline.setStatus(1);
//		 buDeviceOnlineService.updateById(buDeviceOnline);
//		 return Result.OK("操作成功");
//	 }

	 //忽略
	 @GetMapping(value = "/ignore")
	 public Result<?> ignore(String id){
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 BuDeviceOnline buDeviceOnline = buDeviceOnlineService.getById(id);
		 buDeviceOnline.setStatus(2);
		 buDeviceOnline.setUser(user.getRealname());
		 buDeviceOnline.setProcessingTime(new Date());
		 buDeviceOnlineService.updateById(buDeviceOnline);
		 //更改当前设备风险状态，通过设备id和风险名称确定唯一项
		 //查询当前设备相同风险项下是否存在多条风险
		 QueryWrapper<BuDeviceOnline> queryWrapper1 = new QueryWrapper<>();
		 queryWrapper1.eq("device_id",buDeviceOnline.getDeviceId());
		 queryWrapper1.eq("test_item",buDeviceOnline.getTestItem());
		 queryWrapper1.eq("status",0);
		 List<BuDeviceOnline> list = buDeviceOnlineService.list(queryWrapper1);
		 //更新风险状态为正常：1
		 if(list.size()==0){
			 QueryWrapper<BuRiskItem> queryWrapper = new QueryWrapper<>();
			 queryWrapper.eq("risk_name",buDeviceOnline.getTestItem());
			 BuRiskItem buRiskItem = buRiskItemService.getOne(queryWrapper);
			 BuRiskItemValue buRiskItemValue = buRiskItemValueService.getDataByTwoId(buDeviceOnline.getDeviceId(),buRiskItem.getId());
			 buRiskItemValue.setStatus(1);
			 buRiskItemValueService.updateById(buRiskItemValue);
		 }
		 //推送页面右上角重新查询风险项数量
		 SysUser sysUser = sysUserService.getUserByName("admin");
		 String userId = sysUser.getId();
		 String[] userIds = userId.substring(0, (userId.length()-1)).split(",");
		 JSONObject obj = new JSONObject();
		 obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_RISK);
		 obj.put(WebsocketConst.MSG_ID, buDeviceOnline.getId());
		 obj.put(WebsocketConst.MSG_TXT, buDeviceOnline.getTestItem());
		 webSocket.sendMessage(userIds, obj.toJSONString());
		 return Result.OK("操作成功");
	 }

	 // 首页设备状态扇形图
	 @GetMapping(value = "/getStatusData")
	 public Result<?> getStatusData() {
		 String a = "0,1,2,3";
		 List<String> result = Arrays.asList(a.split(","));
		 List<StatusData> statusData = buDeviceOnlineService.getDataByStatus(result);
		 return Result.OK(statusData);
	 }

	/**
	 *   添加
	 *
	 * @param buDeviceOnline
	 * @return
	 */
	@AutoLog(value = "bu_device_online-添加")
	@ApiOperation(value="bu_device_online-添加", notes="bu_device_online-添加")
	//@RequiresPermissions("org.jeecg.modules:bu_device_online:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BuDeviceOnline buDeviceOnline) {
		buDeviceOnlineService.save(buDeviceOnline);
		return Result.OK("添加成功！");
	}

	 // 首页进度条统计
	 @GetMapping(value = "/getProgress")
	 public Result<?> getProgress() {
		 Date date = new Date();
		 String queryYear = String.format("%tY", date);
		 int complete1 = buDeviceOnlineService.getRepairComplete(queryYear);
		 int total1 = buDeviceOnlineService.getRepairTotal(queryYear);
		 int complete2 = buDeviceOnlineService.getMaintainComplete(queryYear);
		 int total2 = buDeviceOnlineService.getMaintainTotal(queryYear);
		 NumberFormat numberFormat = NumberFormat.getInstance();
		 // 设置精确到小数点后2位
		 numberFormat.setMaximumFractionDigits(2);
		 int result1 = (int)((float)complete1/(float)total1*100);
		 int result2 = (int)((float)complete2/(float)total2*100);
		 StatusData statusData = new StatusData();
		 statusData.setOne(result1);
		 statusData.setTwo(result2);
		 return Result.OK(statusData);
	 }

	 // 异常信息前后时间段传感器数据查询
	 @GetMapping(value = "/getChartSensor")
	 public Result<?> getChartSensor(@RequestParam(name="name",required=true) String name,
									 @RequestParam(name="time",required=true) String time,
									 @RequestParam(name="level",required=true) String level,
									 @RequestParam(name="item",required=true) String item) throws ParseException {
		 BuDevice buDevice = buDeviceService.getDeviceByName(name);
		 BuSensor buSensor = buSensorService.getByCheckItem(buDevice.getId(),item);// 获取ip
//		 String tableName = buDevice.getDataTable();// 获取表名
		 String beginTime = timeSwitch(time,"old",level);
		 String endTime = timeSwitch(time,"new",level);
		 // 电压、电流、温度、湿度、烟雾、噪声
//		 List<BuSensorDeviceData> buSensorDeviceData = buSensorDeviceDataService.getTestData(tableName,buSensor.getIpAddress(),beginTime,endTime);
		 return Result.OK();
	 }

	 // 时间前后查询转换
	 public String timeSwitch(String time,String value,String level) throws ParseException, ParseException {
		 Date date = new Date();
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 long times = (sdf.parse(time)).getTime();
		 long resultTime = 0;
		 if (value.equals("old")){
		 	if (level.equals("1")){
				resultTime = times - 300000;
			}else if (level.equals("2")){
				resultTime = times - 900000;
			}else {
				resultTime = times - 1800000;
			}
		 }else if (value.equals("new")){
			 if (level.equals("1")){
				 resultTime = times + 300000;
			 }else if (level.equals("2")){
				 resultTime = times + 900000;
			 }else {
				 resultTime = times + 1800000;
			 }
		 }
		 date.setTime(resultTime);
		 return sdf.format(date);
	 }

	 //查询当前风险对应的传感器数据
	 @GetMapping(value = "/sensorDataById")
	 public Result<?> sensorDataById(@RequestParam String id){
		 BuDeviceOnline buDeviceOnline = buDeviceOnlineService.getById(id);
		 if (buDeviceOnline != null){
			 String value = buDeviceOnline.getRiskData();
			 if (buDeviceOnline.getRemindType() == 1){//电能
				 BuElectric buElectric = JSON.parseObject(value,BuElectric.class);
				 return Result.OK(buElectric);
			 }else if (buDeviceOnline.getRemindType() == 2){//空气
				 BuAirQuality buAirQuality = JSON.parseObject(value,BuAirQuality.class);
				 return Result.OK(buAirQuality);
			 }else if (buDeviceOnline.getRemindType() == 3){//振动
				 BuVibration buVibration = JSON.parseObject(value,BuVibration.class);
				 return Result.OK(buVibration);
			 }else if (buDeviceOnline.getRemindType() == 4){//噪声
				 BuAirNoise buAirNoise = JSON.parseObject(value,BuAirNoise.class);
				 return Result.OK(buAirNoise);
			 }else if (buDeviceOnline.getRemindType() == 5){//烟雾
				 BuAirSmoke buAirSmoke = JSON.parseObject(value,BuAirSmoke.class);
				 return Result.OK(buAirSmoke);
			 }else if (buDeviceOnline.getRemindType() == 6){//水浸
				 BuAirWater buAirWater = JSON.parseObject(value,BuAirWater.class);
				 return Result.OK(buAirWater);
			 }else if (buDeviceOnline.getRemindType() == 7){//流量
				 BuFlowOnline buFlowOnline = JSON.parseObject(value,BuFlowOnline.class);
				 return Result.OK(buFlowOnline);
			 }else if (buDeviceOnline.getRemindType() == 8){//倾角
				 BuDipAngle buDipAngle = JSON.parseObject(value,BuDipAngle.class);
				 return Result.OK(buDipAngle);
			 }else if (buDeviceOnline.getRemindType() == 9){//PLC
                 Under under = JSON.parseObject(value,Under.class);
                 return Result.OK(under);
             }


		 }
		 return Result.error("查询不到数据！");
	 }

	/**
	 *  编辑
	 *
	 * @param buDeviceOnline
	 * @return
	 */
	@AutoLog(value = "bu_device_online-编辑")
	@ApiOperation(value="bu_device_online-编辑", notes="bu_device_online-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BuDeviceOnline buDeviceOnline) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		buDeviceOnline.setUser(user.getRealname());
		buDeviceOnline.setProcessingTime(new Date());
		buDeviceOnline.setStatus(1);
		buDeviceOnlineService.updateById(buDeviceOnline);
		//查询当前设备相同风险项下是否存在多条风险
		QueryWrapper<BuDeviceOnline> queryWrapper1 = new QueryWrapper<>();
		queryWrapper1.eq("device_id",buDeviceOnline.getDeviceId());
		queryWrapper1.eq("test_item",buDeviceOnline.getTestItem());
		queryWrapper1.eq("status",0);
		List<BuDeviceOnline> list = buDeviceOnlineService.list(queryWrapper1);
		//更新风险状态为正常：1
		if(list.size()==0){
			QueryWrapper<BuRiskItem> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("risk_name",buDeviceOnline.getTestItem());
			BuRiskItem buRiskItem = buRiskItemService.getOne(queryWrapper);
			BuRiskItemValue buRiskItemValue = buRiskItemValueService.getDataByTwoId(buDeviceOnline.getDeviceId(),buRiskItem.getId());
			buRiskItemValue.setStatus(1);
			buRiskItemValueService.updateById(buRiskItemValue);
		}
		//推送页面右上角重新查询风险项数量
		SysUser sysUser = sysUserService.getUserByName("admin");
		String userId = sysUser.getId();
		String[] userIds = userId.substring(0, (userId.length()-1)).split(",");
		JSONObject obj = new JSONObject();
		obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_RISK);
		obj.put(WebsocketConst.MSG_ID, buDeviceOnline.getId());
		obj.put(WebsocketConst.MSG_TXT, buDeviceOnline.getTestItem());
		webSocket.sendMessage(userIds, obj.toJSONString());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "bu_device_online-通过id删除")
	@ApiOperation(value="bu_device_online-通过id删除", notes="bu_device_online-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		buDeviceOnlineService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "bu_device_online-批量删除")
	@ApiOperation(value="bu_device_online-批量删除", notes="bu_device_online-批量删除")
	//@RequiresPermissions("org.jeecg.modules:bu_device_online:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.buDeviceOnlineService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "bu_device_online-通过id查询")
	@ApiOperation(value="bu_device_online-通过id查询", notes="bu_device_online-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BuDeviceOnline> queryById(@RequestParam(name="id",required=true) String id) {
		BuDeviceOnline buDeviceOnline = buDeviceOnlineService.getById(id);
		if(buDeviceOnline==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(buDeviceOnline);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param buDeviceOnline
    */
    //@RequiresPermissions("org.jeecg.modules:bu_device_online:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BuDeviceOnline buDeviceOnline) {
        return super.exportXls(request, buDeviceOnline, BuDeviceOnline.class, "bu_device_online");
    }

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

	 @GetMapping(value = "/queryDeviceRiskByTypeAndId")
	 public Result<?> queryDeviceRiskByTypeAndId(@RequestParam(name="deviceType", required = false) String deviceType,
												 @RequestParam(name="deviceId", required = false) String deviceId,
												 @RequestParam(name="startDate", required = false) String startDate,
												 @RequestParam(name="endDate", required = false) String endDate) {
		 JSONObject obj = new JSONObject();

		 // 如果提供了日期范围，则使用日期范围查询
		 try {
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			 Date start = sdf.parse(startDate);
			 Date end = sdf.parse(endDate);

			 List<String> x = new ArrayList<>();
			 List<String> y = new ArrayList<>();
			 DecimalFormat df = new DecimalFormat("0.00");

			 // 遍历日期范围内的每一天
			 Calendar calendar = Calendar.getInstance();
			 calendar.setTime(start);

			 while (!calendar.getTime().after(end)) {
				 String dateStr = sdf.format(calendar.getTime());
				 int sum = 0;
				 sum = buDeviceOnlineService.queryDeviceRiskByTypeAndId(dateStr, deviceType, deviceId);
				 x.add(dateStr);
				 y.add(String.valueOf(sum));
				 calendar.add(Calendar.DAY_OF_MONTH, 1);
			 }
			 obj.put("x", x);
			 obj.put("y", y);
			 return Result.OK(obj);
		 } catch (Exception e) {
			 return Result.error("日期格式错误");
		 }
	 }
	 /**
	  * 导出风险数据
	  */
	 @GetMapping(value = "/exportDeviceRiskXls")
	 public ModelAndView exportDeviceRiskXls(@RequestParam(name="deviceType", required = false) String deviceType,
											 @RequestParam(name="deviceId", required = false) String deviceId,
											 @RequestParam(name="startDate", required = false) String startDate,
											 @RequestParam(name="endDate", required = false) String endDate) {
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 List<ExportDeviceRisk> exportData = new ArrayList<>();
		 // 如果提供了日期范围，则使用日期范围查询
		 if (startDate != null && !startDate.isEmpty() && endDate != null && !endDate.isEmpty()) {
			 try {
				 // 遍历日期范围内的每一天
				 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				 Date start = sdf.parse(startDate);
				 Date end = sdf.parse(endDate);

				 List<String> x = new ArrayList<>();
				 List<String> y = new ArrayList<>();
				 DecimalFormat df = new DecimalFormat("0.00");

				 // 遍历日期范围内的每一天
				 Calendar calendar = Calendar.getInstance();
				 calendar.setTime(start);
				 while (!calendar.getTime().after(end)) {
					 String dateStr = sdf.format(calendar.getTime());
					 int sum = 0;
					 sum = buDeviceOnlineService.queryDeviceRiskByTypeAndId(dateStr, deviceType,deviceId);
					 x.add(dateStr);
					 y.add(String.valueOf(sum));
					 calendar.add(Calendar.DAY_OF_MONTH, 1);
				 }
				 // 构造导出数据
				 for (int i = 0; i < x.size(); i++) {
					 exportData.add(new ExportDeviceRisk(x.get(i), y.get(i)));
				 }

			 } catch (Exception e) {
				 log.error("数据处理异常: ", e);
				 // 发生异常时返回错误信息
				 mv.addObject(NormalExcelConstants.DATA_LIST, new ArrayList<>());
			 }
		 }
		 // 设置导出参数
		 mv.addObject(NormalExcelConstants.FILE_NAME, "设备风险次数统计");
		 mv.addObject(NormalExcelConstants.CLASS, ExportDeviceRisk.class);
		 ExportParams exportParams = new ExportParams("设备风险次数统计报表", "设备风险次数统计导出");
		 mv.addObject(NormalExcelConstants.PARAMS, exportParams);
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportData);
		 return mv;
	 }

	 @ApiOperation(value="bu_device_online-通过id查询", notes="bu_device_online-通过id查询")
	 @GetMapping(value = "/getDeviceByType")
	 public Result<?> getDeviceByType(String typeId) {
		 List<DeviceRiskAnalysis> deviceByType = buDeviceOnlineService.getDeviceByType(typeId);
		 return Result.OK(deviceByType);
	 }
	 @ApiOperation(value="bu_device_online-通过id查询", notes="bu_device_online-通过id查询")
	 @GetMapping(value = "/getDevice")
	 public Result<?> getDevice() {
		 List<DeviceRiskAnalysis> deviceByType = buDeviceOnlineService.getDevice();
		 return Result.OK(deviceByType);
	 }
	 @ApiOperation(value="bu_device_online-通过id查询", notes="bu_device_online-通过id查询")
	 @GetMapping(value = "/queryDeviceRiskByType")
	 public Result<?> queryDeviceRiskByType(String type,String year) {
		 List<DeviceRiskAnalysis> deviceRiskAnalyses = buDeviceOnlineService.queryDeviceRiskByType(type,year);
		 for (DeviceRiskAnalysis deviceRiskAnalysis : deviceRiskAnalyses) {
			 if(deviceRiskAnalysis.getTypeName()!=null){
				 deviceRiskAnalysis.setDeviceName(deviceRiskAnalysis.getTypeName());
			 }
			 List<String> monthList = Arrays.asList(deviceRiskAnalysis.getMonth().split(","));
			 List<String> countList = Arrays.asList(deviceRiskAnalysis.getCount().split(","));
			 Integer[] result = new Integer[12];
			 for (int i=1; i<13; i++){
				 String str = new String();
				 for (String s : monthList) {
					 if(s.equals(String.valueOf(i))){
						 str = countList.get(monthList.indexOf(s));
					 }else {
						 str = "0";
					 }
					 if(result[i-1]==null||result[i-1]==0){
						 result[i-1] = Integer.valueOf(str);
					 }
				 }
			 }
			 deviceRiskAnalysis.setValue(result);
		 }
		 return Result.OK(deviceRiskAnalyses);
	 }
	 @ApiOperation(value="bu_device_online-通过id查询", notes="bu_device_online-通过id查询")
	 @GetMapping(value = "/queryDeviceRiskByDeviceIds")
	 public Result<?> queryDeviceRiskByDeviceIds(String deviceIds,String year) {
		 String[] split = deviceIds.split(",");
		 List<DeviceRiskAnalysis> deviceRiskAnalyses = buDeviceOnlineService.queryDeviceRiskByDeviceIds(split,year);
		 for (DeviceRiskAnalysis deviceRiskAnalysis : deviceRiskAnalyses) {
			 if(deviceRiskAnalysis.getDeviceName()!=null){
				 deviceRiskAnalysis.setDeviceName(deviceRiskAnalysis.getDeviceName()+deviceRiskAnalysis.getDeviceCode());
			 }
			 List<String> monthList = Arrays.asList(deviceRiskAnalysis.getMonth().split(","));
			 List<String> countList = Arrays.asList(deviceRiskAnalysis.getCount().split(","));
			 Integer[] result = new Integer[12];
			 for (int i=1; i<13; i++){
				 String str = new String();
				 for (String s : monthList) {
					 if(s.equals(String.valueOf(i))){
						 str = countList.get(monthList.indexOf(s));
					 }else {
						 str = "0";
					 }
					 if(result[i-1]==null||result[i-1]==0){
						 result[i-1] = Integer.valueOf(str);
					 }
				 }
			 }
			 deviceRiskAnalysis.setValue(result);
		 }
		 return Result.OK(deviceRiskAnalyses);
	 }
	 @ApiOperation(value="bu_device_online查询", notes="bu_device_online查询")
	 @GetMapping(value = "/getAirQuality")
	 public Result<?> getAirQuality() {
		 List<DeviceRiskAnalysis> deviceRiskAnalysis = buDeviceOnlineService.getAirQuality();
//		 List<DeviceRiskAnalysis> result = new ArrayList<>();
//		 for (DeviceRiskAnalysis list : deviceRiskAnalysis){
//			 if(list.getCreateTime()!=null){
//				 Date date = new Date();
//				 long diff = date.getTime() - list.getCreateTime().getTime();
////				 if (diff > 30000)
//				 if(true)
//				 {
//					 list.setCo(null);
//					 list.setCh4(null);
//					 list.setO2(null);
//					 list.setH2s(null);
//				 }
//			 }
//		 }
		 return Result.OK(deviceRiskAnalysis);
	 }

	 @ApiOperation(value="bu_device_online实时查询", notes="bu_device_online实时查询")
	 @GetMapping(value = "/getAirQualityOnlineList")
	 public Result<?> getAirQualityOnline(String deviceId) {
		 DeviceRiskAnalysis airQualityList = buDeviceOnlineService.getAirQualityOnline(deviceId);
		 JSONObject obj = new JSONObject();
		 obj.put("time",airQualityList.getCreateTime());
		 obj.put("o2",airQualityList.getO2());
		 obj.put("co",airQualityList.getCo());
		 obj.put("ch4",airQualityList.getCh4());
		 obj.put("h2s",airQualityList.getH2s());
		 return Result.OK(obj);
	 }

	 @ApiOperation(value="bu_device_online实时查询", notes="bu_device_online实时查询")
	 @GetMapping(value = "/getAirQualityOnline")
	 public Result<?> getAirQualityOnlineList(String deviceId) {
//		 DeviceRiskAnalysis airQualityList = buDeviceOnlineService.getAirQualityOnlineList(deviceId);
		 Date date1 = new Date();
		 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		 String format = simpleDateFormat.format(date1);
		 String tableName = "";
		 String substring = format.substring(0,4)+format.substring(5,7);
		 tableName = "bu_air_quality" + "_history_" + substring;
		 ThreadLocalDataHelper.put("bu_air_quality_online",tableName);
		 LambdaQueryWrapper<BuSensor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		 lambdaQueryWrapper.eq(BuSensor::getDeviceId,deviceId);
		 lambdaQueryWrapper.eq(BuSensor::getTypeId,"RS-MG111-ETH-1");
//		 List<BuSensor> list1 = buSensorService.list(lambdaQueryWrapper);
		 QueryWrapper<BuAirQuality> queryWrapper = new QueryWrapper<>();
		 queryWrapper.in("sensor_id", deviceId);
		 String date = format.substring(8, 10);
// queryWrapper.eq("day(create_time)", date);
		 queryWrapper.last("LIMIT 10");
		 List<BuAirQuality> list = buAirQualityService.list(queryWrapper);
		 List<Date> timeList = list.stream().map(BuAirQuality::getCreateTime).collect(Collectors.toList());
		 List<Double> o2 = list.stream().map(BuAirQuality::getO2).collect(Collectors.toList());
		 List<Double> co = list.stream().map(BuAirQuality::getCo).collect(Collectors.toList());
		 List<Double> ch4 = list.stream().map(BuAirQuality::getCh4).collect(Collectors.toList());
		 List<Double> h2s = list.stream().map(BuAirQuality::getH2s).collect(Collectors.toList());

		 JSONObject obj = new JSONObject();
		 obj.put("time",timeList);
		 obj.put("o2",o2);
		 obj.put("co",co);
		 obj.put("ch4",ch4);
		 obj.put("h2s",h2s);
		 return Result.OK(obj);
	 }
}
