package org.jeecg.modules.energy.controller;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.mybatis.ThreadLocalDataHelper;


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.entity.BuDevice;
import org.jeecg.modules.device.service.IBuDeviceService;
import org.jeecg.modules.energy.entity.BuAirNoise;
import org.jeecg.modules.energy.entity.BuAirWater;
import org.jeecg.modules.energy.entity.BuElectric;
import org.jeecg.modules.energy.entity.BuFlowOnline;
import org.jeecg.modules.energy.service.IBuFlowOnlineService;
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.jeecgframework.minidao.datasource.DataSourceContextHolder;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
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_flow_online
 * @Author: jeecg-boot
 * @Date:   2024-12-28
 * @Version: V1.0
 */
@Api(tags="bu_flow_online")
@RestController
@RequestMapping("/energy/buFlowOnline")
@Slf4j
public class BuFlowOnlineController extends JeecgController<BuFlowOnline, IBuFlowOnlineService> {
	@Autowired
	private IBuFlowOnlineService buFlowOnlineService;

	 @Autowired
	 private IBuSensorService buSensorService;
	 @Autowired
	 private IBuDeviceService buDeviceService;
	 @Autowired
	 private IBuSensorTypeService buSensorTypeService;

	 @Value("${jeecg.path.upload}")
	 private String upLoadPath;

	/**
	 * 分页列表查询
	 *
	 * @param buFlowOnline
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "bu_flow_online-分页列表查询")
	@ApiOperation(value="bu_flow_online-分页列表查询", notes="bu_flow_online-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BuFlowOnline>> queryPageList(BuFlowOnline buFlowOnline,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
//		QueryWrapper<BuFlowOnline> queryWrapper = QueryGenerator.initQueryWrapper(buFlowOnline, req.getParameterMap());
//		Page<BuFlowOnline> page = new Page<BuFlowOnline>(pageNo, pageSize);
//		IPage<BuFlowOnline> pageList = buFlowOnlineService.page(page, queryWrapper);
//		return Result.OK(pageList);


		BuDevice buDevice = buDeviceService.getById(buFlowOnline.getDeviceId());
		List<BuSensor> buSensors = buSensorService.getByCheckName(buDevice.getId(),"%流量%");
		BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
		String tableName = "";
		if(buFlowOnline.getBeginTime()!=null){
			String substring = buFlowOnline.getBeginTime().substring(0, buFlowOnline.getBeginTime()
					.indexOf("-", buFlowOnline.getBeginTime().indexOf("-") + 1)).replaceAll("-","");

			tableName = buSensorType.getTableHead() + "_history_" + substring;
		}
		// 分页查询
		Page<BuFlowOnline> page = new Page<>(pageNo, pageSize);
		IPage<BuFlowOnline> pageList = buFlowOnlineService.selectByDynamicTable(
				page,
				tableName,
				buFlowOnline.getDeviceId(),
				buFlowOnline.getSensorId(),
				buFlowOnline.getBeginTime(),
				buFlowOnline.getEndTime()
		);
//
//		ThreadLocalDataHelper.clear();
//		ThreadLocalDataHelper.put("bu_flow_online",tableName);
//
//		LambdaQueryWrapper<BuFlowOnline> queryWrapper = new LambdaQueryWrapper<>();
//
//		if(buFlowOnline.getDeviceId()!=null){//设置查询限制条件
//			LambdaQueryWrapper<BuSensor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//			lambdaQueryWrapper.eq(BuSensor::getDeviceId,buFlowOnline.getDeviceId());
//			List<String> codeList = buSensorService.list(lambdaQueryWrapper).stream().map(BuSensor::getId).collect(Collectors.toList());
//			queryWrapper.in(BuFlowOnline::getSensorId,codeList);
//		}
//		if(buFlowOnline.getSensorId()!=null){
//			queryWrapper.eq(BuFlowOnline::getSensorId,buFlowOnline.getSensorId());
//		}
//		if (StringUtils.isNotBlank(buFlowOnline.getBeginTime()) && StringUtils.isNotBlank(buFlowOnline.getEndTime())){
//			queryWrapper.between(BuFlowOnline::getCreateTime,buFlowOnline.getBeginTime(),buFlowOnline.getEndTime());
//		}
//		if (StringUtils.isNotBlank(buFlowOnline.getInTime()) && StringUtils.isNotBlank(buFlowOnline.getOutTime())){
//			queryWrapper.between(BuFlowOnline::getCreateTime,buFlowOnline.getInTime(),buFlowOnline.getOutTime());
//		}
//
//		queryWrapper.orderByDesc(BuFlowOnline::getCreateTime);
//		Page<BuFlowOnline> page = new Page<BuFlowOnline>(pageNo, pageSize);
//		page.setOptimizeCountSql(false);
//		IPage<BuFlowOnline> pageList = buFlowOnlineService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @AutoLog(value = "水浸传感器数据-首页查询")
	 @ApiOperation(value="水浸传感器数据-首页查询", notes="水浸传感器数据-首页查询")
	 @GetMapping(value = "/getFlowData")
	 public Result<?> getFlowData() {
		 List<BuFlowOnline> buflowList = buFlowOnlineService.getFlowData();//实时数据
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 for (BuFlowOnline buflow : buflowList) {
			 buflow.setDeviceName(buflow.getDeviceName() + buflow.getDevicecode()+"_" + buflow.getDataUnit());
			 // 取绝对值处理
			 buflow.setDischarge(Math.abs(buflow.getDischarge()));
			 buflow.setFlowspeed(Math.abs(buflow.getFlowspeed()));
			 buflow.setFlowrate(Math.abs(buflow.getFlowrate()));
		 }
		 return Result.OK(buflowList);
	 }




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

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

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

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

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

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

	 @RequestMapping(value = "/exportXls")
	 public ModelAndView ExportXlsCommon(HttpServletRequest request, BuFlowOnline buFlowOnline) {
		 BuDevice buDevice = buDeviceService.getById(buFlowOnline.getDeviceId());
		 List<BuSensor> buSensors = buSensorService.getByCheckName(buDevice.getId(),"%流量%");
		 BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
		 String tableName = "";
		 if(buFlowOnline.getBeginTime()!=null){
			 String substring = buFlowOnline.getBeginTime().substring(0, buFlowOnline.getBeginTime()
					 .indexOf("-", buFlowOnline.getBeginTime().indexOf("-") + 1)).replaceAll("-","");

			 tableName = buSensorType.getTableHead() + "_history_" + substring;
		 }
		 // 分页查询
		 List<BuFlowOnline> list = buFlowOnlineService.selectByDynamicTable(
				 tableName,
				 buFlowOnline.getDeviceId(),
				 buFlowOnline.getSensorId(),
				 buFlowOnline.getBeginTime(),
				 buFlowOnline.getEndTime()
		 );
		 return super.exportHisXls(request, buFlowOnline, BuFlowOnline.class, tableName, list);
		/* // Step.1 组装查询条件

		 QueryWrapper<BuFlowOnline> queryWrapper = new QueryWrapper<>();
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//获取当前用户信息
		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 queryWrapper.in("id", selectionList);
		 }
		 // Step.2 获取导出数据
		 BuDevice buDevice = buDeviceService.getById(buFlowOnline.getDeviceId());
		 List<BuSensor> buSensors = buSensorService.getByCheckName(buDevice.getId(), "%流量%");
		 BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
		 String tableName = "";
		 if (buFlowOnline.getBeginTime() != null) {
			 String substring = buFlowOnline.getBeginTime().substring(0, buFlowOnline.getBeginTime()
					 .indexOf("-", buFlowOnline.getBeginTime().indexOf("-") + 1)).replaceAll("-", "");
			 tableName = buSensorType.getTableHead() + "_history_" + buDevice.getTypeId() + "_" + buDevice.getDeviceCode() + "_" + substring;
		 }
		 ThreadLocalDataHelper.put("bu_flow_online", tableName);
		 List<BuFlowOnline> exportList = buFlowOnlineService.list(queryWrapper);

		 if (exportList == null || exportList.isEmpty()) {
			 // 根据实际情况决定如何处理这种情况
			 throw new IllegalArgumentException("Invalid export parameters or data list.");// 抛出异常，或者返回错误响应等处理
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());// // 创建一个新的ModelAndView实例，并指定使用的视图
		 //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "bu_flow");
		 mv.addObject(NormalExcelConstants.CLASS, BuFlowOnline.class);
		 //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		 ExportParams exportParams = new ExportParams("流量表" + "报表", "导出人:" + sysUser.getRealname(), "bu_flow");
		 exportParams.setImageBasePath(upLoadPath);
		 //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		 mv.addObject(NormalExcelConstants.PARAMS, exportParams);// 添加自定义参数
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);// 添加数据
		 return mv;*/
	 }

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

}
