package com.jiayue.ipfcst.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import com.jiayue.ipfcst.service.EnvironmentalDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("environmentalData")
public class EnvironmentalDataController {
  private final EnvironmentalDataService environmentalDataService;

  @Autowired
  public EnvironmentalDataController(EnvironmentalDataService environmentalDataService) {
    this.environmentalDataService = environmentalDataService;
  }

  @GetMapping("/findEnvironmentalData/{startTime}/{endTime}/{eqId}")
  public ResponseVO findEnvironmentalData(@PathVariable Long startTime, @PathVariable Long endTime, @PathVariable Integer eqId) {
    Map<String, Object> byRealTime = environmentalDataService.getData(startTime, endTime, eqId,1);
    return ResponseVO.success(byRealTime);
  }


  @GetMapping("/findEnvironmentalData")
  public ResponseVO getEqAttribute() {
    return ResponseVO.success(environmentalDataService.eqAttribute());
  }

  @GetMapping("/findEnvironmentalData/{eqId}")
  public ResponseVO getEqAttributeById(@PathVariable Integer eqId) {
    return ResponseVO.success(environmentalDataService.getEqAttributeById(eqId));
  }

  /**
   * 环境数据导出
   *
   * @param response
   */
  @RequestMapping(value = "/export")
  public void export(HttpServletResponse response, Long startTime, Long endTime, Integer eqId) {
    try {
      Map<String, Object> maps = environmentalDataService.getData(startTime, endTime, eqId,1);

      List<Map<String, String>> tableColumns = (List<Map<String, String>>) maps.get("tableColumn");

      List<Map<String, BigDecimal>> dayLists = (List<Map<String, BigDecimal>>) maps.get("dayList");

      List<Map<String, BigDecimal>> monthLists = (List<Map<String, BigDecimal>>) maps.get("monthList");

      List<Map<String, BigDecimal>> yearLists = (List<Map<String, BigDecimal>>) maps.get("yearList");

      Map<String, Object> footerDatas = (Map<String, Object>) maps.get("footerData");

      List<String> rowFoot = CollUtil.newArrayList();
      List<String> rowFootDay = CollUtil.newArrayList();
      rowFoot.add("统计列极值");
      for (Map<String, String> tableColumn : tableColumns) {
        if (tableColumn.get("sum") != null) {
          rowFootDay.add(footerDatas.get(tableColumn.get("sum")) + "");

          rowFoot.add(footerDatas.get(tableColumn.get("maxAvgValue")) + "");
          rowFoot.add(footerDatas.get(tableColumn.get("sum")) + "");
          rowFoot.add(footerDatas.get(tableColumn.get("max")) + "");
          rowFoot.add(footerDatas.get(tableColumn.get("maxTime")) + "");
          rowFoot.add(footerDatas.get(tableColumn.get("min")) + "");
          rowFoot.add(footerDatas.get(tableColumn.get("minTime")) + "");
          rowFoot.add(footerDatas.get(tableColumn.get("avg")) + "");
        } else {
          rowFoot.add(footerDatas.get(tableColumn.get("maxAvgValue")) + "");
          rowFoot.add(footerDatas.get(tableColumn.get("max")) + "");
          rowFoot.add(footerDatas.get(tableColumn.get("maxTime")) + "");
          rowFoot.add(footerDatas.get(tableColumn.get("min")) + "");
          rowFoot.add(footerDatas.get(tableColumn.get("minTime")) + "");
          rowFoot.add(footerDatas.get(tableColumn.get("avg")) + "");
        }
      }

      List<String> header = new ArrayList();
      header.add("时间");
      List<String> headerDay = new ArrayList();
      headerDay.add("时间");
      for (Map<String, String> tableColumn : tableColumns) {
        header.add(tableColumn.get("title") + "极大值(" + tableColumn.get("unit")+")");
        header.add(tableColumn.get("title") + "最大值(" + tableColumn.get("unit")+")");
        header.add(tableColumn.get("title") + "最大值时刻");
        header.add(tableColumn.get("title") + "最小值(" + tableColumn.get("unit")+")");
        header.add(tableColumn.get("title") + "最小值时刻");
        header.add(tableColumn.get("title") + "平均值(" + tableColumn.get("unit")+")");
        if (tableColumn.get("title").equals("总辐射日累计") || tableColumn.get("title").equals("直辐射日累计") || tableColumn.get("title").equals("散射辐射日累计") || tableColumn.get("title").equals("斜面辐射日累计") || tableColumn.get("title").equals("日照小时数")) {
          headerDay.add(tableColumn.get("title") + "统计值(" + tableColumn.get("unit")+")");

          header.add(tableColumn.get("title") + "统计值(" + tableColumn.get("unit")+")");
        } else {
          headerDay.add(tableColumn.get("title") + "极大值(" + tableColumn.get("unit")+")");
          headerDay.add(tableColumn.get("title") + "最大值(" + tableColumn.get("unit")+")");
          headerDay.add(tableColumn.get("title") + "最大值时刻");
          headerDay.add(tableColumn.get("title") + "最小值(" + tableColumn.get("unit")+")");
          headerDay.add(tableColumn.get("title") + "最小值时刻");
          headerDay.add(tableColumn.get("title") + "平均值(" + tableColumn.get("unit")+")");
        }

      }

      ExcelWriter writer = ExcelUtil.getWriter(true);
      writer.renameSheet(0, "日");

      List<String> rowHeather = CollUtil.newArrayList(header);
      List<String> rowHeatherDay = CollUtil.newArrayList(headerDay);
      List<List<String>> rowsDay = CollUtil.newArrayList();
      rowsDay.add(rowHeatherDay);
      for (Map<String, BigDecimal> dayList : dayLists) {
        List<String> rowContent = CollUtil.newArrayList();
        rowContent.add(dayList.get("times") + "");
        for (Map<String, String> tableColumn : tableColumns) {
          if (tableColumn.get("sum") != null) {
            rowContent.add(dayList.get(tableColumn.get("sum")) + "");
          } else {
            rowContent.add(dayList.get(tableColumn.get("maxAvgValue")) + "");
            rowContent.add(dayList.get(tableColumn.get("max")) + "");
            rowContent.add(dayList.get(tableColumn.get("maxTime")) + "");
            rowContent.add(dayList.get(tableColumn.get("min")) + "");
            rowContent.add(dayList.get(tableColumn.get("minTime")) + "");
            rowContent.add(dayList.get(tableColumn.get("avg")) + "");
          }
        }
        rowsDay.add(rowContent);
      }
      rowsDay.add(rowFootDay);

      writer.write(rowsDay, true);

      ExcelWriter monthSheet = writer.setSheet("月");

      List<List<String>> rowsMonth = CollUtil.newArrayList();
      rowsMonth.add(rowHeather);
      for (Map<String, BigDecimal> monthList : monthLists) {
        List<String> rowContent = CollUtil.newArrayList();
        rowContent.add(monthList.get("times") + "");
        for (Map<String, String> tableColumn : tableColumns) {
          rowContent.add(monthList.get(tableColumn.get("maxAvgValue")) + "");
          rowContent.add(monthList.get(tableColumn.get("max")) + "");
          rowContent.add(monthList.get(tableColumn.get("maxTime")) + "");
          rowContent.add(monthList.get(tableColumn.get("min")) + "");
          rowContent.add(monthList.get(tableColumn.get("minTime")) + "");
          rowContent.add(monthList.get(tableColumn.get("avg")) + "");
          if (tableColumn.get("sum") != null) {
            rowContent.add(monthList.get(tableColumn.get("sum")) + "");
          }
        }
        rowsMonth.add(rowContent);
      }
      rowsMonth.add(rowFoot);
      monthSheet.write(rowsMonth, true);

      ExcelWriter yearSheet = writer.setSheet("年");

      List<List<String>> rowsYear = CollUtil.newArrayList();
      rowsYear.add(rowHeather);
      for (Map<String, BigDecimal> yearList : yearLists) {
        List<String> rowContent = CollUtil.newArrayList();
        rowContent.add(yearList.get("times") + "");
        for (Map<String, String> tableColumn : tableColumns) {
          rowContent.add(yearList.get(tableColumn.get("maxAvgValue")) + "");
          rowContent.add(yearList.get(tableColumn.get("max")) + "");
          rowContent.add(yearList.get(tableColumn.get("maxTime")) + "");
          rowContent.add(yearList.get(tableColumn.get("min")) + "");
          rowContent.add(yearList.get(tableColumn.get("minTime")) + "");
          rowContent.add(yearList.get(tableColumn.get("avg")) + "");
          if (tableColumn.get("sum") != null) {
            rowContent.add(yearList.get(tableColumn.get("sum")) + "");
          }
        }
        rowsYear.add(rowContent);
      }
      rowsYear.add(rowFoot);
      yearSheet.write(rowsYear, true);

      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

      String fileName = "环境数据信息" + simpleDateFormat.format(startTime) + "至" + simpleDateFormat.format(endTime) + ".xlsx";
      response.setContentType("application/x-msdownload;charset=utf-8");
      response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
      ServletOutputStream out = null;
      out = response.getOutputStream();
      writer.flush(out, true);
      // 关闭writer，释放内存
      writer.close();
      //此处记得关闭输出Servlet流
      IoUtil.close(out);
    } catch (IOException e) {
      e.printStackTrace();
    }

  }
}
