package org.jeecg.modules.device.controller;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
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.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.device.entity.BuDeviceRunTime;
import org.jeecg.modules.device.entity.Export.ExportDeviceRisk;
import org.jeecg.modules.device.entity.Export.ExportPower;
import org.jeecg.modules.device.entity.Export.ExportRunTime;
import org.jeecg.modules.device.service.IBuDeviceRunTimeService;

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.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.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: 设备实际运行时间表
 * @Author: jeecg-boot
 * @Date:   2024-06-01
 * @Version: V1.0
 */
@Api(tags="设备实际运行时间表")
@RestController
@RequestMapping("/device/buDeviceRunTime")
@Slf4j
public class BuDeviceRunTimeController extends JeecgController<BuDeviceRunTime, IBuDeviceRunTimeService> {
	@Autowired
	private IBuDeviceRunTimeService buDeviceRunTimeService;

	/**
	 * 分页列表查询
	 *
	 * @param buDeviceRunTime
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "设备实际运行时间表-分页列表查询")
	@ApiOperation(value="设备实际运行时间表-分页列表查询", notes="设备实际运行时间表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BuDeviceRunTime>> queryPageList(BuDeviceRunTime buDeviceRunTime,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BuDeviceRunTime> queryWrapper = QueryGenerator.initQueryWrapper(buDeviceRunTime, req.getParameterMap());
		Page<BuDeviceRunTime> page = new Page<BuDeviceRunTime>(pageNo, pageSize);
		IPage<BuDeviceRunTime> pageList = buDeviceRunTimeService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 /**
	  * 第一次进页面，展示全设备能耗分析面积图（按月）
	  */
	 @GetMapping(value = "/devicePowerStatistics")
	 public Result<?> devicePowerStatistics(@RequestParam(name="selectYear", required = true) String selectYear){
		 JSONObject obj = new JSONObject();
		 String year = "";
		 if (selectYear == null || selectYear.equals("")){
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
			 year = sdf.format(new Date());
		 }else {
			 year = selectYear;
		 }
		 List<Integer> x = new ArrayList<>();
		 List<String> y = new ArrayList<>();
		 DecimalFormat df = new DecimalFormat("0.00");
		 for (int i=1; i<13;i++){
			 String sumPower = buDeviceRunTimeService.getSumPower(Integer.parseInt(year),i);
			 x.add(i);
			 if (sumPower == null){
				 y.add("0");
			 }else {
				 y.add((df.format(Double.valueOf(sumPower))));
			 }
		 }
		 obj.put("x",x);
		 obj.put("y",y);
		 obj.put("year",year);
		 return Result.OK(obj);
	 }

	 /**
	  * 根据设备类型展示设备能耗分析面积图（按月）
	  */
	 @GetMapping(value = "/devicePowerStatisticsByType")
	 public Result<?> devicePowerStatisticsByType(@RequestParam(name="selectYear", required = true) String selectYear,
												  @RequestParam(name="deviceType", required = true) String deviceType){
		 JSONObject obj = new JSONObject();
		 String year = "";
		 DecimalFormat df = new DecimalFormat("0.00");
		 if (selectYear == null || selectYear.equals("")){
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
			 year = sdf.format(new Date());
		 }else {
			 year = selectYear;
		 }
		 List<String> x = new ArrayList<>();
		 List<String> y = new ArrayList<>();
		 for (int i=1; i<13;i++){
			 String sumPower = buDeviceRunTimeService.getSumPowerByType(Integer.parseInt(year),i,deviceType);
			 x.add(String.valueOf(i));
			 if (sumPower == null){
				 y.add("0");
			 }else {
				 y.add((df.format(Double.valueOf(sumPower))));
			 }
		 }
		 obj.put("x",x);
		 obj.put("y",y);
		 return Result.OK(obj);
	 }

	 /**
	  * 根据设备id展示设备能耗分析面积图（按月）
	  */
	 @GetMapping(value = "/devicePowerStatisticsById")
	 public Result<?> devicePowerStatisticsById(@RequestParam(name="selectYear", required = true) String selectYear,
												@RequestParam(name="deviceId", required = true) String deviceId){
		 JSONObject obj = new JSONObject();
		 String year = "";
		 if (selectYear == null || selectYear.equals("")){
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
			 year = sdf.format(new Date());
		 }else {
			 year = selectYear;
		 }
		 List<String> x = new ArrayList<>();
		 List<String> y = new ArrayList<>();
		 DecimalFormat df = new DecimalFormat("0.00");
		 for (int i=1; i<13;i++){
			 String sumPower = buDeviceRunTimeService.getSumPowerByDevice(Integer.parseInt(year),i,deviceId);
			 x.add(String.valueOf(i));
			 if (sumPower == null){
				 y.add("0");
			 }else {
				 y.add((df.format(Double.valueOf(sumPower))));
			 }
		 }
		 obj.put("x",x);
		 obj.put("y",y);
		 return Result.OK(obj);
	 }


	 /**
	  * 第一次进页面，展示全设备当月运行状况分析柱形图（按天）
	  */
	 @GetMapping(value = "/getAllDeviceOperation")
	 public Result<?> getAllDeviceOperation(@RequestParam(name="selectMonth", required = true) String selectMonth){
		 JSONObject obj = new JSONObject();
		 int year = 0;String month = "0";
		 if (selectMonth == null || selectMonth.equals("")){
			 Calendar calendar = Calendar.getInstance();
			 year = calendar.get(Calendar.YEAR);
			 month = String.valueOf(calendar.get(Calendar.MONTH)+1);
		 }else {
			 String[] yearMonth = selectMonth.split("-");
			 year = Integer.parseInt(yearMonth[0]);
			 month = yearMonth[1];
		 }
		 List<Integer> x = new ArrayList<>();
		 List<String> y = new ArrayList<>();
		 DecimalFormat df = new DecimalFormat("0.00");
		 int length = 0;
		 if (month.equals("02")){
			 if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){
				 length = 29;
			 }else {
				 length = 28;
			 }
		 }else if (month.equals("04") || month.equals("06") || month.equals("09") || month.equals("11")){
			 length = 30;
		 }else {
			 length = 31;
		 }
		 for (int i=1; i<length+1;i++){
			 String sum = buDeviceRunTimeService.getSumTime(year, Integer.parseInt(month),i);
			 x.add(i);
			 if (sum == null){
				 y.add("0");
			 }else {
				 y.add((df.format(Double.parseDouble(sum) / 60)));
			 }
		 }
		 obj.put("x",x);
		 obj.put("y",y);
		 return Result.OK(obj);
	 }

	 /**
	  * 根据设备类型展示设备运行分析面积图（按天）
	  */
	 @GetMapping(value = "/getTypeOperation")
	 public Result<?> getTypeOperation(@RequestParam(name="deviceType", required = false) String deviceType,
									   @RequestParam(name="deviceId", required = false) String deviceId,
									   @RequestParam(name="startDate", required = false) String startDate,
									   @RequestParam(name="endDate", required = false) String endDate) {
		 JSONObject obj = new JSONObject();

		 // 如果提供了日期范围，则使用日期范围查询
		 if (startDate != null && !startDate.isEmpty() && endDate != null && !endDate.isEmpty()) {
			 try {
				 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				 Date start = sdf.parse(startDate);
				 Date end = sdf.parse(endDate);

				 List<String> x = new ArrayList<>();
				 List<String> y = new ArrayList<>();
				 DecimalFormat df = new DecimalFormat("0.00");

				 // 遍历日期范围内的每一天
				 Calendar calendar = Calendar.getInstance();
				 calendar.setTime(start);

				 while (!calendar.getTime().after(end)) {
					 String dateStr = sdf.format(calendar.getTime());
					 String sum = buDeviceRunTimeService.getSumTimeByTypeAndId(dateStr,deviceType,deviceId);
					 x.add(dateStr);
					 if (sum.equals("null")) {
						 y.add("0");
					 } else {
						 y.add((df.format(Double.parseDouble(sum) / 60)));
					 }
					 calendar.add(Calendar.DAY_OF_MONTH, 1);
				 }

				 obj.put("x", x);
				 obj.put("y", y);
				 return Result.OK(obj);
			 } catch (Exception e) {
				 return Result.error("日期格式错误");
			 }
		 }

		 return Result.error("日期格式错误");
	 }

	 /**
	  * 设备能耗分析面积图（按天）
	  */
	 @GetMapping(value = "/queryDeviceEnergyByTypeAndId")
	 public Result<?> queryDeviceEnergyByTypeAndId(@RequestParam(name="selectMonth", required = false) String selectMonth,
												   @RequestParam(name="deviceType", required = false) String deviceType,
												   @RequestParam(name="deviceId", required = false) String deviceId,
												   @RequestParam(name="startDate", required = false) String startDate,
												   @RequestParam(name="endDate", required = false) String endDate) {
		 JSONObject obj = new JSONObject();

		 // 如果提供了日期范围，则使用日期范围查询
		 if (startDate != null && !startDate.isEmpty() && endDate != null && !endDate.isEmpty()) {
			 try {
				 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				 Date start = sdf.parse(startDate);
				 Date end = sdf.parse(endDate);

				 List<String> x = new ArrayList<>();
				 List<String> y = new ArrayList<>();
				 DecimalFormat df = new DecimalFormat("0.00");

				 // 遍历日期范围内的每一天
				 Calendar calendar = Calendar.getInstance();
				 calendar.setTime(start);
				 while (!calendar.getTime().after(end)) {
					 String dateStr = sdf.format(calendar.getTime());
					 String sum = buDeviceRunTimeService.getPowerByTypeAndId(dateStr,deviceType,deviceId);
					 if (sum.equals("null")) {
						 y.add("0");
					 } else {
						 y.add(sum);
					 }
					 x.add(dateStr);
					 calendar.add(Calendar.DAY_OF_MONTH, 1);
				 }
				 obj.put("x", x);
				 obj.put("y", y);
				 return Result.OK(obj);
			 } catch (Exception e) {
				 return Result.error("日期格式错误");
			 }
		 }
		 return Result.error("日期格式错误");
	 }
	 /**
	  * 电能消耗导出
	  */
	 @GetMapping(value = "/exportpowerXls")
	 public ModelAndView exportDeviceRiskXls(@RequestParam(name="deviceType", required = false) String deviceType,
											 @RequestParam(name="deviceId", required = false) String deviceId,
											 @RequestParam(name="startDate", required = false) String startDate,
											 @RequestParam(name="endDate", required = false) String endDate) {
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 List<ExportDeviceRisk> exportData = new ArrayList<>();
		 // 如果提供了日期范围，则使用日期范围查询
		 if (startDate != null && !startDate.isEmpty() && endDate != null && !endDate.isEmpty()) {
			 try {
				 // 遍历日期范围内的每一天
				 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				 Date start = sdf.parse(startDate);
				 Date end = sdf.parse(endDate);

				 List<String> x = new ArrayList<>();
				 List<String> y = new ArrayList<>();
				 DecimalFormat df = new DecimalFormat("0.00");

				 // 遍历日期范围内的每一天
				 Calendar calendar = Calendar.getInstance();
				 calendar.setTime(start);
				 while (!calendar.getTime().after(end)) {
					 String dateStr = sdf.format(calendar.getTime());
					 String sum = buDeviceRunTimeService.getPowerByTypeAndId(dateStr,deviceType,deviceId);
					 if (sum.equals("null")) {
						 y.add("0");
					 } else {
						 y.add(sum);
					 }
					 x.add(dateStr);
					 calendar.add(Calendar.DAY_OF_MONTH, 1);
				 }
				 // 构造导出数据
				 for (int i = 0; i < x.size(); i++) {
					 exportData.add(new ExportDeviceRisk(x.get(i), y.get(i)));
				 }

			 } catch (Exception e) {
				 log.error("数据处理异常: ", e);
				 // 发生异常时返回错误信息
				 mv.addObject(NormalExcelConstants.DATA_LIST, new ArrayList<>());
			 }
		 }
		 // 设置导出参数
		 mv.addObject(NormalExcelConstants.FILE_NAME, "设备风险次数统计");
		 mv.addObject(NormalExcelConstants.CLASS, ExportPower.class);
		 ExportParams exportParams = new ExportParams("设备风险次数统计报表", "设备风险次数统计导出");
		 mv.addObject(NormalExcelConstants.PARAMS, exportParams);
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportData);
		 return mv;
	 }
	 /**
	  * 导出运行时间数据
	  */
	 @GetMapping(value = "/exportRuntimeXls")
	 public ModelAndView exportRuntimeXls(@RequestParam(name="deviceType", required = false) String deviceType,
										  @RequestParam(name="deviceId", required = false) String deviceId,
										  @RequestParam(name="startDate", required = false) String startDate,
										  @RequestParam(name="endDate", required = false) String endDate) {
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 List<ExportRunTime> exportData = new ArrayList<>();

		 // 如果提供了日期范围，则使用日期范围查询
		 if (startDate != null && !startDate.isEmpty() && endDate != null && !endDate.isEmpty()) {
			 try {
				 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				 Date start = sdf.parse(startDate);
				 Date end = sdf.parse(endDate);

				 List<String> x = new ArrayList<>();
				 List<String> y = new ArrayList<>();
				 DecimalFormat df = new DecimalFormat("0.00");

				 // 遍历日期范围内的每一天
				 Calendar calendar = Calendar.getInstance();
				 calendar.setTime(start);
				 while (!calendar.getTime().after(end)) {
					 String dateStr = sdf.format(calendar.getTime());
					 String sum = buDeviceRunTimeService.getSumTimeByTypeAndId(dateStr, deviceType,deviceId);
					 x.add(dateStr);
					 if (sum.equals("null")) {
						 y.add("0");
					 } else {
						 y.add((df.format(Double.parseDouble(sum) / 60)));
					 }
					 calendar.add(Calendar.DAY_OF_MONTH, 1);
				 }

				 // 构造导出数据
				 for (int i = 0; i < x.size(); i++) {
					 exportData.add(new ExportRunTime(x.get(i), y.get(i)));
				 }

			 } catch (Exception e) {
				 log.error("数据处理异常: ", e);
				 // 发生异常时返回错误信息
				 mv.addObject(NormalExcelConstants.DATA_LIST, new ArrayList<>());
			 }
		 }
		 // 设置导出参数
		 mv.addObject(NormalExcelConstants.FILE_NAME, "设备运行时间统计");
		 mv.addObject(NormalExcelConstants.CLASS, ExportRunTime.class);
		 ExportParams exportParams = new ExportParams("设备运行时间统计报表", "运行时间统计导出");
		 mv.addObject(NormalExcelConstants.PARAMS, exportParams);
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportData);
		 return mv;
	 }
	/**
	 *   添加
	 *
	 * @param buDeviceRunTime
	 * @return
	 */
	@AutoLog(value = "设备实际运行时间表-添加")
	@ApiOperation(value="设备实际运行时间表-添加", notes="设备实际运行时间表-添加")
	//@RequiresPermissions("org.jeecg.modules:bu_device_run_time:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BuDeviceRunTime buDeviceRunTime) {
		buDeviceRunTimeService.save(buDeviceRunTime);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param buDeviceRunTime
	 * @return
	 */
	@AutoLog(value = "设备实际运行时间表-编辑")
	@ApiOperation(value="设备实际运行时间表-编辑", notes="设备实际运行时间表-编辑")
	//@RequiresPermissions("org.jeecg.modules:bu_device_run_time:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BuDeviceRunTime buDeviceRunTime) {
		buDeviceRunTimeService.updateById(buDeviceRunTime);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "设备实际运行时间表-通过id删除")
	@ApiOperation(value="设备实际运行时间表-通过id删除", notes="设备实际运行时间表-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:bu_device_run_time:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		buDeviceRunTimeService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "设备实际运行时间表-批量删除")
	@ApiOperation(value="设备实际运行时间表-批量删除", notes="设备实际运行时间表-批量删除")
	//@RequiresPermissions("org.jeecg.modules:bu_device_run_time:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.buDeviceRunTimeService.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<BuDeviceRunTime> queryById(@RequestParam(name="id",required=true) String id) {
		BuDeviceRunTime buDeviceRunTime = buDeviceRunTimeService.getById(id);
		if(buDeviceRunTime==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(buDeviceRunTime);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param buDeviceRunTime
    */
    //@RequiresPermissions("org.jeecg.modules:bu_device_run_time:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BuDeviceRunTime buDeviceRunTime) {
        return super.exportXls(request, buDeviceRunTime, BuDeviceRunTime.class, "设备实际运行时间表");
    }

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

}
