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.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.entity.BuVibration;
import org.jeecg.modules.energy.service.IBuVibrationService;
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: 振动数据表模板
 * @Author: jeecg-boot
 * @Date:   2024-05-09
 * @Version: V1.0
 */
@Api(tags="振动数据表模板")
@RestController
@RequestMapping("/energy/buVibration")
@Slf4j
public class BuVibrationController extends JeecgController<BuVibration, IBuVibrationService> {
	@Autowired
	private IBuVibrationService buVibrationService;
	 @Autowired
	 private IBuSensorService buSensorService;
	 @Autowired
	 private IBuDeviceService buDeviceService;
	 @Autowired
	 private IBuSensorTypeService buSensorTypeService;
	/**
	 * 分页列表查询
	 *
	 * @param buVibration
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "振动数据表模板-分页列表查询")
	@ApiOperation(value="振动数据表模板-分页列表查询", notes="振动数据表模板-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BuVibration>> queryPageList(BuVibration buVibration,
													@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													HttpServletRequest req) {
		BuDevice buDevice = buDeviceService.getById(buVibration.getDeviceId());
		List<BuSensor> buSensors = buSensorService.getByCheckName(buDevice.getId(),"%振动%");
		BuSensorType buSensorType = buSensorTypeService.getById(buSensors.get(0).getTypeId());
		String tableName = "";
		if(buVibration.getBeginTime()!=null){
			String substring = buVibration.getBeginTime().substring(0, buVibration.getBeginTime()
					.indexOf("-", buVibration.getBeginTime().indexOf("-") + 1)).replaceAll("-","");
			tableName = buSensorType.getTableHead() + "_history_" + buDevice.getTypeId() + "_" + buDevice.getDeviceCode() + "_" + substring;
		}
		ThreadLocalDataHelper.put("bu_vibration_online",tableName);
//		QueryWrapper<BuVibration> queryWrapper = QueryGenerator.initQueryWrapper(buVibration, req.getParameterMap());
		LambdaQueryWrapper<BuVibration> queryWrapper = new LambdaQueryWrapper<>();
		if(buVibration.getDeviceId()!=null){
			LambdaQueryWrapper<BuSensor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(BuSensor::getDeviceId,buVibration.getDeviceId());
			//			ThreadLocalDataHelper.put("vib_sy_dto","bu_air_quality_history_"+req.getParameter("time"));
			List<String> codeList = buSensorService.list(lambdaQueryWrapper).stream().map(BuSensor::getId).collect(Collectors.toList());
			queryWrapper.in(BuVibration::getSensorId,codeList);
		}
		if(buVibration.getSensorId()!=null){
			queryWrapper.eq(BuVibration::getSensorId,buVibration.getSensorId());
		}
		if (StringUtils.isNotBlank(buVibration.getBeginTime()) && StringUtils.isNotBlank(buVibration.getEndTime())){
			queryWrapper.between(BuVibration::getCreateTime,buVibration.getBeginTime(),buVibration.getEndTime());
		}
		if (StringUtils.isNotBlank(buVibration.getInTime()) && StringUtils.isNotBlank(buVibration.getOutTime())){
			queryWrapper.between(BuVibration::getCreateTime,buVibration.getInTime(),buVibration.getOutTime());
		}

		queryWrapper.orderByDesc(BuVibration::getCreateTime);
		Page<BuVibration> page = new Page<BuVibration>(pageNo, pageSize);
		page.setOptimizeCountSql(false);
		IPage<BuVibration> pageList = buVibrationService.page(page, queryWrapper);
		return Result.OK(pageList);
	}


	 @AutoLog(value = "震动传感器数据-首页查询")
	 @ApiOperation(value="震动传感器数据-首页查询", notes="震动传感器数据-首页查询")
	 @GetMapping(value = "/getBuVibrationData")
	 public Result<?> getBuVibrationData() {

		List<BuVibration> buVibrationList = buVibrationService.getBuVibrationData();
		List<List<String>> lists = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 try {
			for (BuVibration buVibration : buVibrationList) {
				buVibration.setDeviceName(buVibration.getDeviceName()+buVibration.getDeviceCode());
//				List<String> list = new ArrayList<>();
//				list.add(buVibration.getDeviceName() + buVibration.getDeviceCode());
//				Date date = new Date();
//				long diff = date.getTime() - buVibration.getCreateTime().getTime();
////				 if (diff < 30000)
//				if (true) {
//					String time = sdf.format(buVibration.getCreateTime());
//					list.add(time);
//				} else {
//					continue;
//				}
//				list.add(buVibration.getAccX().toString());
//				list.add(buVibration.getAccY().toString());
//				list.add(buVibration.getAccZ().toString());
//				list.add(buVibration.getSpeedX().toString());
//				list.add(buVibration.getSpeedY().toString());
//				list.add(buVibration.getSpeedZ().toString());
//				list.add(buVibration.getDisplacementX().toString());
//				list.add(buVibration.getDisplacementY().toString());
//				list.add(buVibration.getDisplacementZ().toString());
//				list.add(buVibration.getTemperature().toString());
//				lists.add(list);
			}
		}
		catch (Exception e)
		{
            log.error(e.getMessage(), e);
		}
		 return Result.OK(buVibrationList);
	 }
	/**
	 *   添加
	 *
	 * @param buVibration
	 * @return
	 */
	@AutoLog(value = "振动数据表模板-添加")
	@ApiOperation(value="振动数据表模板-添加", notes="振动数据表模板-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:bu_vibration:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BuVibration buVibration) {
		buVibrationService.save(buVibration);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param buVibration
	 * @return
	 */
	@AutoLog(value = "振动数据表模板-编辑")
	@ApiOperation(value="振动数据表模板-编辑", notes="振动数据表模板-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:bu_vibration:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BuVibration buVibration) {
		buVibrationService.updateById(buVibration);
		return Result.OK("编辑成功!");
	}

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

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

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "振动数据表模板-通过id查询")
	@ApiOperation(value="振动数据表模板-通过id查询", notes="振动数据表模板-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BuVibration> queryById(@RequestParam(name="id",required=true) String id) {
		BuVibration buVibration = buVibrationService.getById(id);
		if(buVibration==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(buVibration);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param buVibration
    */
    //@RequiresPermissions("org.jeecg.modules.demo:bu_vibration:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BuVibration buVibration) {
        return super.exportXls(request, buVibration, BuVibration.class, "振动数据表模板");
    }

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

}
