package org.jeecg.modules.energy.controller;

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

import org.jeecg.common.api.vo.Result;


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.entity.BuDevice;
import org.jeecg.modules.device.entity.BuDeviceOnline;
import org.jeecg.modules.device.entity.BuRiskItem;
import org.jeecg.modules.device.service.IBuDeviceOnlineService;
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.BuAirWater;
import org.jeecg.modules.energy.service.IBuAirWaterService;
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.jeecg.common.system.base.controller.JeecgController;
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_air_water_online
 * @Author: jeecg-boot
 * @Date:   2024-10-11
 * @Version: V1.0
 */
@Api(tags="bu_air_water_online")
@RestController
@RequestMapping("/energy/buAirWater")
@Slf4j
public class BuAirWaterController extends JeecgController<BuAirWater, IBuAirWaterService> {
	@Autowired
	private IBuAirWaterService buAirWaterService;
	@Autowired
	private IBuSensorService buSensorService;
	@Autowired
	private IBuDeviceService buDeviceService;
	@Autowired
	private IBuSensorTypeService buSensorTypeService;
	 @Autowired
	 private IBuRiskItemService buRiskItemService;

	 @Autowired
	 private IBuRiskItemValueService buRiskItemValueService;

	 @Autowired
	 private IBuDeviceOnlineService buDeviceOnlineService;
	/**
	 * 分页列表查询
	 *
	 * @param buAirWater
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "bu_air_water_online-分页列表查询")
	@ApiOperation(value="bu_air_water_online-分页列表查询", notes="bu_air_water_online-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BuAirWater>> queryPageList(BuAirWater buAirWater,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		BuDevice buDevice = buDeviceService.getById(buAirWater.getDeviceId());
		List<BuSensor> buSensors = buSensorService.getByCheckName(buDevice.getId(),"%水浸%");
		BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
		String tableName = "";
		if(buAirWater.getBeginTime()!=null){
			String substring = buAirWater.getBeginTime().substring(0, buAirWater.getBeginTime()
					.indexOf("-", buAirWater.getBeginTime().indexOf("-") + 1)).replaceAll("-","");

//			tableName = buSensorType.getTableHead() + "_history_" + buDevice.getTypeId() + "_" + buDevice.getDeviceCode() + "_" + substring;
			tableName = buSensorType.getTableHead() + "_history_" + substring;
		}
		// 分页查询
		Page<BuAirWater> page = new Page<>(pageNo, pageSize);
		IPage<BuAirWater> pageList = buAirWaterService.selectByDynamicTable(
				page,
				tableName,
				buAirWater.getDeviceId(),
				buAirWater.getSensorId(),
				buAirWater.getBeginTime(),
				buAirWater.getEndTime()
		);
/*		ThreadLocalDataHelper.put("bu_water_immersion_online",tableName);

//		QueryWrapper<BuAirSmoke> queryWrapper = QueryGenerator.initQueryWrapper(buAirSmoke, req.getParameterMap());
		LambdaQueryWrapper<BuAirWater> queryWrapper = new LambdaQueryWrapper<>();
		if(buAirWater.getDeviceId()!=null){
			LambdaQueryWrapper<BuSensor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(BuSensor::getDeviceId,buAirWater.getDeviceId());
			List<String> codeList = buSensorService.list(lambdaQueryWrapper).stream().map(BuSensor::getId).collect(Collectors.toList());
			queryWrapper.in(BuAirWater::getSensorId,codeList);
		}
		if(buAirWater.getSensorId()!=null){
			queryWrapper.eq(BuAirWater::getSensorId,buAirWater.getSensorId());
		}
		if (StringUtils.isNotBlank(buAirWater.getBeginTime()) && StringUtils.isNotBlank(buAirWater.getEndTime())){
			queryWrapper.between(BuAirWater::getCreateTime,buAirWater.getBeginTime(),buAirWater.getEndTime());
		}
		if (StringUtils.isNotBlank(buAirWater.getInTime()) && StringUtils.isNotBlank(buAirWater.getOutTime())){
			queryWrapper.between(BuAirWater::getCreateTime,buAirWater.getInTime(),buAirWater.getOutTime());
		}
		queryWrapper.orderByDesc(BuAirWater::getCreateTime);
		Page<BuAirWater> page = new Page<BuAirWater>(pageNo, pageSize);
		page.setOptimizeCountSql(false);
		IPage<BuAirWater> pageList = buAirWaterService.page(page, queryWrapper);*/
		return Result.OK(pageList);
	}

	@AutoLog(value = "水浸传感器数据-首页查询")
	@ApiOperation(value="水浸传感器数据-首页查询", notes="水浸传感器数据-首页查询")
	@GetMapping(value = "/getAirWaterData")
	public Result<?> getAirWaterData() {
		List<BuAirWater> buAirWaterList = buAirWaterService.getAirWaterData();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (BuAirWater buAirWater : buAirWaterList) {
			buAirWater.setDeviceName(buAirWater.getDeviceName()+buAirWater.getDeviceCode()+"_"+buAirWater.getDataUnit());
		}
		return Result.OK(buAirWaterList);
	}

	 @GetMapping(value = "/getAirWaterDatajcj")
	 public Result<?> getAirWaterDatajcj(@RequestParam String deviceId) throws InterruptedException {
		 // 获取所有电能数据
		 List<BuAirWater> buElectricList = buAirWaterService.getAirWaterData();

		 // 如果提供了设备ID，则过滤列表
		 if (deviceId != null && !deviceId.isEmpty()) {
			 BuAirWater buDevice = buAirWaterService.getById(deviceId);
			 if (buDevice != null) {
				 List<BuSensor> buSensors = buSensorService.getByCheckName(buDevice.getId(), "%水浸%");
				 List<String> sensorIds = buSensors.stream().map(BuSensor::getId).collect(Collectors.toList());
				 buElectricList = buElectricList.stream().filter(electric -> sensorIds.contains(electric.getSensorId())).collect(Collectors.toList());
			 }
		 }

		 buElectricList = buElectricList.stream()
				 .filter(buAirWater -> "架车机".equals(buAirWater.getDeviceName()))
				 .collect(Collectors.toList());

		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 for (BuAirWater buElectric : buElectricList) {
			 buElectric.setDeviceName(buElectric.getDeviceName() + buElectric.getDeviceCode() + "_" + buElectric.getDataUnit());
		 }
		 return Result.OK(buElectricList);
	 }

	 @AutoLog(value = "根据deviceid读取设备信息")
	 @ApiOperation(value="根据deviceid读取设备信息", notes="根据deviceid读取设备信息")
	 @GetMapping(value = "/getDeviceById")
	 public Result<?> getDeviceById(@RequestParam(name="deviceId", required = true) String deviceId) {
		 BuDevice device = buDeviceService.getById(deviceId);
		 if (device == null) {
			 return Result.error("未找到对应设备");
		 }
		 return Result.OK(device);
	 }

	 @AutoLog(value = "水浸传感器数据-首页查询")
	 @ApiOperation(value="水浸传感器数据-首页查询", notes="水浸传感器数据-首页查询")
	 @GetMapping(value = "/getAirWateronline")//else水侵状态报警
	 public Result<?> getAirWaterDataa(@RequestParam(required = false) String sensorId) {

		 BuDevice buDevice = buDeviceService.getDevicesensorid(sensorId);
		 BuRiskItem buRiskItem = buRiskItemService.getById("566706130");
		 BuAirWater buAirWater = new BuAirWater();

		 BuDeviceOnline buDeviceOnline = new BuDeviceOnline();
		 buDeviceOnline.setDeviceId(buDevice.getSensorId());
		 buDeviceOnline.setDeviceName(buDevice.getDeviceName());
		 buDeviceOnline.setDeviceCode(buDevice.getDeviceCode());
		 buDeviceOnline.setTime(new Date());
		 buDeviceOnline.setRemindType(6);
		 buDeviceOnline.setTestItem(buRiskItem.getRiskName());
		 buDeviceOnline.setRemind(buRiskItem.getRiskExplain());
		 buDeviceOnline.setStatus(0);
		 buDeviceOnline.setRiskExplain(buRiskItem.getRiskExplain());
		 buDeviceOnline.setRiskHarm(buRiskItem.getRiskHarm());
		 buDeviceOnline.setSuggest(buRiskItem.getDealAdvice());
		 buDeviceOnline.setRiskData(JSON.toJSONString(buAirWater));
		 buDeviceOnlineService.save(buDeviceOnline);
		 return Result.OK();
	 }
	/**
	 *   添加
	 *
	 * @param buAirWater
	 * @return
	 */
	@AutoLog(value = "bu_air_water_online-添加")
	@ApiOperation(value="bu_air_water_online-添加", notes="bu_air_water_online-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:bu_air_water_online:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BuAirWater buAirWater) {
		buAirWaterService.save(buAirWater);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param buAirWater
	 * @return
	 */
	@AutoLog(value = "bu_air_water_online-编辑")
	@ApiOperation(value="bu_air_water_online-编辑", notes="bu_air_water_online-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:bu_air_water_online:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BuAirWater buAirWater) {
		buAirWaterService.updateById(buAirWater);
		return Result.OK("编辑成功!");
	}

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

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

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

    /**
    * 导出excel
    *
    * @param request
    * @param buAirWater
    */
    //@RequiresPermissions("org.jeecg.modules.demo:bu_air_water_online:exportXls")
    @RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, BuAirWater buAirWater) {
		BuDevice buDevice = buDeviceService.getById(buAirWater.getDeviceId());
		List<BuSensor> buSensors = buSensorService.getByCheckName(buDevice.getId(),"%水浸%");
		BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
		String tableName = "";
		if(buAirWater.getBeginTime()!=null){
			String substring = buAirWater.getBeginTime().substring(0, buAirWater.getBeginTime()
					.indexOf("-", buAirWater.getBeginTime().indexOf("-") + 1)).replaceAll("-","");
			tableName = buSensorType.getTableHead() + "_history_" + substring;
		}

		List<BuAirWater> list = buAirWaterService.selectByDynamicTable(
				tableName,
				buAirWater.getDeviceId(),
				buAirWater.getSensorId(),
				buAirWater.getBeginTime(),
				buAirWater.getEndTime()
		);
		return super.exportHisXls(request, buAirWater, BuAirWater.class, tableName, list);
//		return super.exportXls(request, buAirWater, BuAirWater.class, "bu_air_water_online");
	}

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

}
