package org.jeecg.modules.energy.controller;

import java.lang.reflect.Field;
import java.sql.SQLException;
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.conditions.query.QueryWrapper;
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 org.jeecg.common.system.query.QueryGenerator;

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.IBuElectricService;
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_electric
 * @Author: jeecg-boot
 * @Date:   2024-05-09
 * @Version: V1.0
 */
@Api(tags="bu_electric")
@RestController
@RequestMapping("/energy/buElectric")
@Slf4j
public class BuElectricController extends JeecgController<BuElectric, IBuElectricService> {
	@Autowired
	private IBuElectricService buElectricService;
	 @Autowired
	 private IBuSensorService buSensorService;
	 @Autowired
	 private IBuDeviceService buDeviceService;
	 @Autowired
	 private IBuSensorTypeService buSensorTypeService;
	/**
	 * 分页列表查询
	 *
	 * @param buElectric
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "bu_electric-分页列表查询")
	@ApiOperation(value="bu_electric-分页列表查询", notes="bu_electric-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BuElectric>> queryPageList(BuElectric buElectric,
												   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												   HttpServletRequest req) {
		BuDevice buDevice = buDeviceService.getById(buElectric.getDeviceId());
		System.out.println("设备编号:" + buDevice.getId());
		List<BuSensor> buSensors = buSensorService.getByCheckName(buDevice.getId(),"%电能%");
		BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
		String tableName = "";
		if(buElectric.getBeginTime()!=null){
			String substring = buElectric.getBeginTime().substring(0, buElectric.getBeginTime()
					.indexOf("-", buElectric.getBeginTime().indexOf("-") + 1)).replaceAll("-","");

//			bu_electric_history_jcj_468996012_202412

//			tableName = buSensorType.getTableHead() + "_history_" + buDevice.getTypeId() + "_" + buDevice.getDeviceCode() + "_" + substring;
			tableName = "bu_electric" + "_history_"+ buDevice.getTypeId() + "_" + buDevice.getDeviceCode() + "_" + substring;
		}
		// 分页查询
		Page<BuElectric> page = new Page<>(pageNo, pageSize);
		IPage<BuElectric> pageList = buElectricService.selectByDynamicTable(
				page,
				tableName,
				buElectric.getDeviceId(),
				buElectric.getSensorId(),
				buElectric.getBeginTime(),
				buElectric.getEndTime()
		);
		return Result.OK(pageList);

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

	 @AutoLog(value = "电能传感器数据-首页查询")
	 @ApiOperation(value="电能传感器数据-首页查询", notes="电能传感器数据-首页查询")
	 @GetMapping(value = "/getElectricData")
	 public Result<?> getElectricData() throws IllegalAccessException {
		 List<BuElectric> buElectricList = buElectricService.getElectricData();
		 for (BuElectric buElectric : buElectricList) {
			 if (buElectric.getUdl() < 10  && buElectric.getVdl() < 10  && buElectric.getWdl() < 10)
			 {
				 buElectric.setUdl((double) 0);
				 buElectric.setVdl((double) 0);
				 buElectric.setWdl((double) 0);
				 buElectricService.updateById(buElectric);
			 }
			 if(buElectric.getUdy() < 30  && buElectric.getVdy() < 30  && buElectric.getWdy() < 30)
			 {
				 buElectric.setUdy((double) 0);
				 buElectric.setVdy((double) 0);
				 buElectric.setWdy((double) 0);
			 }
		 }
		 List<List<String>> lists = new ArrayList<>();
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 for (BuElectric buElectric : buElectricList) {
			 buElectric.setDeviceName(buElectric.getDeviceName()+buElectric.getDeviceCode()+"_"+buElectric.getDataUnit());

//			 List<String> list = new ArrayList<>();
//			list.add(buElectric.getDeviceName()+buElectric.getDeviceCode());
//			 Date date = new Date();
//			 long diff = date.getTime() - buElectric.getCreateTime().getTime();
//				 if (diff < 30000)
//			 if (true)
//			 {
//				 String time = sdf.format(buElectric.getCreateTime());
//				 list.add(time);
//			 }else {
//				 continue;
//			 }
//			 list.add(buElectric.getUdl().toString());
//			 list.add(buElectric.getVdl().toString());
//			 list.add(buElectric.getWdl().toString());
//			 list.add(buElectric.getUdy().toString());
//			 list.add(buElectric.getVdy().toString());
//			 list.add(buElectric.getWdy().toString());
//			 list.add(buElectric.getActivePower().toString());
//			 list.add(buElectric.getReactivePower().toString());
//			 list.add(buElectric.getPowerFactor().toString());
//			 list.add(buElectric.getFrequency().toString());
//			 lists.add(list);
		 }
		 return Result.OK(buElectricList);
	 }
	/**
	 *   添加
	 *
	 * @param buElectric
	 * @return
	 */
	@AutoLog(value = "bu_electric-添加")
	@ApiOperation(value="bu_electric-添加", notes="bu_electric-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:bu_electric:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BuElectric buElectric) {
		buElectricService.save(buElectric);
		return Result.OK("添加成功！");
	}

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

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

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

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

    /**
    * 导出excel
    *
    * @param request
    * @param buElectric
    */
    //@RequiresPermissions("org.jeecg.modules.demo:bu_electric:exportXls")
    @RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, BuElectric buElectric) {
		BuDevice buDevice = buDeviceService.getById(buElectric.getDeviceId());
		System.out.println("设备编号:" + buDevice.getId());
		List<BuSensor> buSensors = buSensorService.getByCheckName(buDevice.getId(),"%电能%");
		BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
		String tableName = "";
		if(buElectric.getBeginTime()!=null){
			String substring = buElectric.getBeginTime().substring(0, buElectric.getBeginTime()
					.indexOf("-", buElectric.getBeginTime().indexOf("-") + 1)).replaceAll("-","");
			tableName = "bu_electric" + "_history_"+ buDevice.getTypeId() + "_" + buDevice.getDeviceCode() + "_" + substring;
		}

		List<BuElectric> list = buElectricService.selectByDynamicTable(
				tableName,
				buElectric.getDeviceId(),
				buElectric.getSensorId(),
				buElectric.getBeginTime(),
				buElectric.getEndTime()
		);
		return super.exportHisXls(request, buElectric, BuElectric.class, tableName, list);
//		return super.exportXls(request, buElectric, BuElectric.class, "bu_electric");
	}

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

}
