package org.jeecg.modules.energy.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.config.mybatis.ThreadLocalDataHelper;
import org.jeecg.modules.device.entity.BuDevice;
import org.jeecg.modules.device.service.IBuDeviceService;
import org.jeecg.modules.energy.entity.BuAirQuality;
import org.jeecg.modules.energy.entity.BuElectric;
import org.jeecg.modules.energy.service.IBuAirQualityService;
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.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: bu_air_quality
 * @Author: jeecg-boot
 * @Date:   2024-05-09
 * @Version: V1.0
 */
@Api(tags="bu_air_quality")
@RestController
@RequestMapping("/energy/buAirQuality")
@Slf4j
public class BuAirQualityController extends JeecgController<BuAirQuality, IBuAirQualityService> {
	@Autowired
	private IBuAirQualityService buAirQualityService;
	@Autowired
	private IBuSensorService buSensorService;
	 @Autowired
	 private IBuDeviceService buDeviceService;
	 @Autowired
	 private IBuSensorTypeService buSensorTypeService;
	/**
	 * 分页列表查询
	 *
	 * @param buAirQuality
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "bu_air_quality-分页列表查询")
	@ApiOperation(value="bu_air_quality-分页列表查询", notes="bu_air_quality-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BuAirQuality>> queryPageList(BuAirQuality buAirQuality,
													 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													 HttpServletRequest req) {
		BuDevice buDevice = buDeviceService.getById(buAirQuality.getDeviceId());
		List<BuSensor> buSensors = buSensorService.getByCheckName(buDevice.getId(),"%空气%");
		BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
		String tableName = "";
		if(buAirQuality.getBeginTime()!=null){
			String substring = buAirQuality.getBeginTime().substring(0, buAirQuality.getBeginTime()
					.indexOf("-", buAirQuality.getBeginTime().indexOf("-") + 1)).replaceAll("-","");
			tableName = buSensorType.getTableHead() + "_history_" + substring;
		}
		// 分页查询
		Page<BuAirQuality> page = new Page<>(pageNo, pageSize);
		IPage<BuAirQuality> pageList = buAirQualityService.selectByDynamicTable(
				page,
				tableName,
				buAirQuality.getDeviceId(),
				buAirQuality.getSensorId(),
				buAirQuality.getBeginTime(),
				buAirQuality.getEndTime()
		);
		/*ThreadLocalDataHelper.put("bu_air_quality_online",tableName);
//		QueryWrapper<BuAirQuality> queryWrapper = QueryGenerator.initQueryWrapper(buAirQuality, req.getParameterMap());
		LambdaQueryWrapper<BuAirQuality> queryWrapper = new LambdaQueryWrapper<>();
		if(buAirQuality.getDeviceId()!=null){
			LambdaQueryWrapper<BuSensor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(BuSensor::getDeviceId,buAirQuality.getDeviceId());
			List<String> codeList = buSensorService.list(lambdaQueryWrapper).stream().map(BuSensor::getId).collect(Collectors.toList());
			queryWrapper.in(BuAirQuality::getSensorId,codeList);
		}
		if(buAirQuality.getSensorId()!=null){
			queryWrapper.eq(BuAirQuality::getSensorId,buAirQuality.getSensorId());
		}
		if (StringUtils.isNotBlank(buAirQuality.getBeginTime()) && StringUtils.isNotBlank(buAirQuality.getEndTime())){
			queryWrapper.between(BuAirQuality::getCreateTime,buAirQuality.getBeginTime(),buAirQuality.getEndTime());
		}
		if (StringUtils.isNotBlank(buAirQuality.getInTime()) && StringUtils.isNotBlank(buAirQuality.getOutTime())){
			queryWrapper.between(BuAirQuality::getCreateTime,buAirQuality.getInTime(),buAirQuality.getOutTime());
		}
		Page<BuAirQuality> page = new Page<BuAirQuality>(pageNo, pageSize);
//		IPage<BuAirQuality> pageList = buAirQualityService.page(page, queryWrapper);
		Page<BuAirQuality> list = buAirQualityService.page(page, queryWrapper);*/
		return Result.OK(pageList);
	}

	 @AutoLog(value = "空气传感器数据-首页查询")
	 @ApiOperation(value="空气传感器数据-首页查询", notes="空气传感器数据-首页查询")
	 @GetMapping(value = "/getAirQualityData")
	 public Result<?> getAirQualityData() {
		 List<BuAirQuality> buAirQualityList = buAirQualityService.getAirQualityData();
		 List<List<String>> lists = new ArrayList<>();
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 for (BuAirQuality buAirQuality : buAirQualityList) {
			 buAirQuality.setDeviceName(buAirQuality.getDeviceName()+buAirQuality.getDeviceCode()+"_"+buAirQuality.getDataUnit());
//			 List<String> list = new ArrayList<>();
////			 String deviceId = buSensorService.getById(buAirQuality.getSensorId()).getDeviceId();
////			 BuDevice buDevice = buDeviceService.getById(deviceId);
//			 list.add(buAirQuality.getDeviceName()+buAirQuality.getDeviceCode());
//			 Date date = new Date();
//			 long diff = date.getTime() - buAirQuality.getCreateTime().getTime();
////				 if (diff < 30000)
//			 if(true)
//			 {
//				 String time = sdf.format(buAirQuality.getCreateTime());
//				 list.add(time);
//			 }else {
//				 continue;
//			 }
////				 list.add(buAirQuality.getHcho().toString());
////				 list.add(buAirQuality.getO3().toString());
//			 list.add(buAirQuality.getO2().toString());
//			 list.add(buAirQuality.getCo().toString());
//			 list.add(buAirQuality.getCh4().toString());
//			 list.add(buAirQuality.getH2s().toString());
//
//			 lists.add(list);
		 }
		 return Result.OK(buAirQualityList);
	 }
	/**
	 *   添加
	 *
	 * @param buAirQuality
	 * @return
	 */
	@AutoLog(value = "bu_air_quality-添加")
	@ApiOperation(value="bu_air_quality-添加", notes="bu_air_quality-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:bu_air_quality:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BuAirQuality buAirQuality) {
		buAirQualityService.save(buAirQuality);
		return Result.OK("添加成功！");
	}

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

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

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

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

    /**
    * 导出excel
    *
    * @param request
    * @param buAirQuality
    */
    //@RequiresPermissions("org.jeecg.modules.demo:bu_air_quality:exportXls")
    @RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, BuAirQuality buAirQuality) {
		BuDevice buDevice = buDeviceService.getById(buAirQuality.getDeviceId());
		List<BuSensor> buSensors = buSensorService.getByCheckName(buDevice.getId(),"%空气%");
		BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
		String tableName = "";
		if(buAirQuality.getBeginTime()!=null){
			String substring = buAirQuality.getBeginTime().substring(0, buAirQuality.getBeginTime()
					.indexOf("-", buAirQuality.getBeginTime().indexOf("-") + 1)).replaceAll("-","");
			tableName = buSensorType.getTableHead() + "_history_" + substring;
		}
		List<BuAirQuality> list = buAirQualityService.selectByDynamicTable(
				tableName,
				buAirQuality.getDeviceId(),
				buAirQuality.getSensorId(),
				buAirQuality.getBeginTime(),
				buAirQuality.getEndTime()
		);
		return super.exportHisXls(request, buAirQuality, BuAirQuality.class, tableName, list);
//        return super.exportXls(request, buAirQuality, BuAirQuality.class, "bu_air_quality");
	}

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

}
