package com.jiayue.ipfcst.controller;

import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import com.jiayue.ipfcst.common.data.entity.DisplayConfig;
import com.jiayue.ipfcst.common.data.entity.ElectricField;
import com.jiayue.ipfcst.common.data.repository.SysParameterRepository;
import com.jiayue.ipfcst.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
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.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * 实时对比查询restful接口
 *
 * @author tl
 * @version 1.0
 * @since 2019/8/7 10:12
 */
@RestController
@Slf4j
public class RealTimeComprehensiveContrastController {
  private final PowerStationStatusDataService powerStationStatusDataService;
  private final WeatherStationStatusDataService weatherStationStatusDataService;
  private final WindTowerStatusDataService windTowerStatusDataService;
  private final DisplayConfigService displayConfigService;
  private final SysParameterRepository sysParameterRepository;
  private final ForecastPowerShortTermService forecastPowerShortTermService;
  private final ForecastPowerUltraShortTermService forecastPowerUltraShortTermService;
  private final NwpService nwpService;
  private final RealTimeComprehensiveContrastService realTimeComprehensiveContrastService;
  private final ElectricFieldService electricFieldService;

  @Autowired
  public RealTimeComprehensiveContrastController(PowerStationStatusDataService powerStationStatusDataService,
                                                 WeatherStationStatusDataService weatherStationStatusDataService,
                                                 WindTowerStatusDataService windTowerStatusDataService,
                                                 DisplayConfigService displayConfigService,
                                                 SysParameterRepository sysParameterRepository,
                                                 ForecastPowerUltraShortTermService forecastPowerUltraShortTermService,
                                                 ForecastPowerShortTermService forecastPowerShortTermService,
                                                 NwpService nwpService,
                                                 RealTimeComprehensiveContrastService realTimeComprehensiveContrastService,
                                                 ElectricFieldService electricFieldService) {

    this.powerStationStatusDataService = powerStationStatusDataService;
    this.weatherStationStatusDataService = weatherStationStatusDataService;
    this.windTowerStatusDataService = windTowerStatusDataService;
    this.displayConfigService = displayConfigService;
    this.sysParameterRepository = sysParameterRepository;
    this.forecastPowerShortTermService = forecastPowerShortTermService;
    this.forecastPowerUltraShortTermService = forecastPowerUltraShortTermService;
    this.nwpService = nwpService;
    this.realTimeComprehensiveContrastService = realTimeComprehensiveContrastService;
    this.electricFieldService = electricFieldService;
  }

  /**
   * 综合数据对比查询
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @param no
   * @return
   */
  @GetMapping(value = "realTimeComprehensiveContrast/{startTime}/{endTime}/{no}/{otherType}/{jgTime}")
  public ResponseVO realTimeComprehensiveQueryForcharts(@PathVariable("startTime") Long startTime,
                                                        @PathVariable("endTime") Long endTime,
                                                        @PathVariable("no") Integer no,
                                                        @PathVariable("otherType") String otherType,
                                                        @PathVariable("jgTime") Long jgTime

  ) throws Exception {
    return ResponseVO.success(realTimeComprehensiveContrastService.realTimeComprehensiveContrast(startTime, endTime, no, otherType, jgTime));
  }


  /**
   * 综合数据对比查询
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @param no
   * @return
   */
  @GetMapping(value = "realTimeComprehensiveContrastExport/{startTime}/{endTime}/{no}/{otherType}/{jgTime}")
  public ResponseVO export(@PathVariable("startTime") Long startTime,
                           @PathVariable("endTime") Long endTime,
                           @PathVariable("no") Integer no,
                           @PathVariable("otherType") String otherType,
                           @PathVariable("jgTime") Long jgTime,
                           HttpServletResponse response

  ) throws Exception {

    Map<String, Object> map = realTimeComprehensiveContrastService.realTimeComprehensiveContrast(startTime, endTime, no, otherType, jgTime);

    BufferedOutputStream bos = null;
    try {
      StringBuilder templateContent = new StringBuilder();
      response.setCharacterEncoding("UTF-8");
      ElectricField electricField = electricFieldService.get();
      DisplayConfig displayConfig = null;
      if (electricField.getElectricFieldTypeEnum().getCode() == 1) {
        displayConfig = displayConfigService.findByDisplayCode("rtWeatherStationInfos");
        String showCode = displayConfig.getShowCode();
        String[] split = showCode.split(",");
        String header = "\"时间\",";

        String displayKyLl = (String) map.get("displayKyLl");

        for (int i = 0; i < split.length; i++) {
          switch (split[i]) {
            case "realValue":
              header += "\"实际功率\",";
              if (displayKyLl.equals("1")) {
                header += "\"可用功率\",\"理论功率\",\"参照功率（样板机）\",\"参照功率（测风、测光）\",";
              }
              break;
            case "rDq":
              header += "\"实时短期\",";
              break;
            case "rCdq":
              header += "\"实时超短期\",";
              break;
            case "globalR":
              header += "\"总辐射\",";
              break;
            case "directR":
              header += "\"直辐射\",";
              break;
            case "diffuseR":
              header += "\"散辐射\",";
              break;
            case "obliqueR":
              header += "\"斜辐射\",";
              break;
            case "directRadiation":
              header += "\"nwp直辐射\",";
              break;
            case "diffuseRadiation":
              header += "\"nwp散辐射\",";
              break;
            case "swr":
              header += "\"nwp总辐射\",";
              break;
          }
        }
        header += "\r\n";

        List<Map<String, Float>> tableResult = (List<Map<String, Float>>) map.get("tableResult");
        List<Map<String, Float>> resultList = (List<Map<String, Float>>) map.get("resultList");

        templateContent.append(header);
        for (int i = 0; i < tableResult.size(); i++) {
          StringBuilder content = new StringBuilder();

          content.append(tableResult.get(i).get("time") + ",");

          for (int n = 0; n < split.length; n++) {
            switch (split[n]) {
              case "realValue":
                content.append(tableResult.get(i).get("realValue") + ",");

                if (displayKyLl.equals("1")) {
                  content.append(tableResult.get(i).get("ableValue") + ",");
                  content.append(tableResult.get(i).get("theoryValue") + ",");
                  content.append(tableResult.get(i).get("referencePowerBySample") + ",");
                  content.append(tableResult.get(i).get("referencePowerByMeasuring") + ",");
                }
                break;
              case "rDq":
                content.append(tableResult.get(i).get("rDq") + ",");
                break;
              case "rCdq":
                content.append(tableResult.get(i).get("rCdq") + ",");
                break;
              case "globalR":
                content.append(resultList.get(i).get("globalR") + ",");
                break;
              case "directR":
                content.append(resultList.get(i).get("directR") + ",");
                break;
              case "diffuseR":
                content.append(resultList.get(i).get("diffuseR") + ",");
                break;
              case "obliqueR":
                content.append(resultList.get(i).get("obliqueR") + ",");
                break;
              case "directRadiation":
                content.append(resultList.get(i).get("directRadiation") + ",");
                break;
              case "diffuseRadiation":
                content.append(resultList.get(i).get("diffuseRadiation") + ",");
                break;
              case "swr":
                content.append(resultList.get(i).get("swr") + ",");
                break;
            }
          }
          content.append("\r\n");
          templateContent.append(content.toString());
        }

      } else {

        displayConfig = displayConfigService.findByDisplayCode("rtWindTowerInfos");
        String showCode = displayConfig.getShowCode();
        String[] split = showCode.split(",");
        String header = "\"时间\",";

        String displayKyLl = (String) map.get("displayKyLl");

        for (int i = 0; i < split.length; i++) {
          switch (split[i]) {
            case "realValue":
              header += "\"实际功率\",";
              if (displayKyLl.equals("1")) {
                header += "\"可用功率\",\"理论功率\",\"参照功率（样板机）\",\"参照功率（测风、测光）\",";
              }
              break;
            case "wsInst10":
              header += "\"10米风速\",";
              break;
            case "wsInst30":
              header += "\"30米风速\",";
              break;
            case "wsInst50":
              header += "\"50米风速\",";
              break;
            case "wsInst60":
              header += "\"60米风速\",";
              break;
            case "wsInst70":
              header += "\"70米风速\",";
              break;
            case "wsInst80":
              header += "\"80米风速\",";
              break;
            case "wsInst90":
              header += "\"90米风速\",";
              break;
            case "wsInst100":
              header += "\"100米风速\",";
              break;
            case "wsInst110":
              header += "\"110米风速\",";
              break;
            case "wsInst120":
              header += "\"120米风速\",";
              break;
            case "wsInstHubHeight":
              header += "\"轮毂风速\",";
              break;
            case "ws10":
              header += "\"nwp10米风速\",";
              break;
            case "ws30":
              header += "\"nwp30米风速\",";
              break;
            case "ws50":
              header += "\"nwp50米风速\",";
              break;
            case "ws70":
              header += "\"nwp70米风速\",";
              break;
            case "ws80":
              header += "\"nwp80米风速\",";
              break;
            case "ws90":
              header += "\"nwp90米风速\",";
              break;
            case "ws110":
              header += "\"nwp100米风速\",";
              break;
            case "ws170":
              header += "\"nwp170米风速\",";
              break;
            case "rDq":
              header += "\"实时短期\",";
              break;
            case "rCdq":
              header += "\"实时超短期\",";
              break;
          }
        }
        header += "\r\n";
        List<Map<String, Float>> tableResult = (List<Map<String, Float>>) map.get("tableResult");
        List<Map<String, Float>> resultList = (List<Map<String, Float>>) map.get("resultList");

        templateContent.append(header);
        for (int i = 0; i < tableResult.size(); i++) {
          StringBuilder content = new StringBuilder();

          content.append(tableResult.get(i).get("time") + ",");

          for (int n = 0; n < split.length; n++) {
            switch (split[n]) {
              case "realValue":
                content.append(tableResult.get(i).get("realValue") + ",");

                if (displayKyLl.equals("1")) {
                  content.append(tableResult.get(i).get("ableValue") + ",");
                  content.append(tableResult.get(i).get("theoryValue") + ",");
                  content.append(tableResult.get(i).get("referencePowerBySample") + ",");
                  content.append(tableResult.get(i).get("referencePowerByMeasuring") + ",");
                }
                break;
              case "wsInst10":
                content.append(resultList.get(i).get("wsInst10") + ",");
                break;
              case "wsInst30":
                content.append(resultList.get(i).get("wsInst30") + ",");
                break;
              case "wsInst50":
                content.append(resultList.get(i).get("wsInst50") + ",");
                break;
              case "wsInst60":
                content.append(resultList.get(i).get("wsInst60") + ",");
                break;
              case "wsInst70":
                content.append(resultList.get(i).get("wsInst70") + ",");
                break;
              case "wsInst80":
                content.append(resultList.get(i).get("wsInst80") + ",");
                break;
              case "wsInst90":
                content.append(resultList.get(i).get("wsInst90") + ",");
                break;
              case "wsInst100":
                content.append(resultList.get(i).get("wsInst100") + ",");
                break;
              case "wsInst110":
                content.append(resultList.get(i).get("wsInst110") + ",");
                break;
              case "wsInst120":
                content.append(resultList.get(i).get("wsInst120") + ",");
                break;
              case "wsInstHubHeight":
                content.append(resultList.get(i).get("wsInstHubHeight") + ",");
                break;
              case "ws10":
                content.append(resultList.get(i).get("ws10") + ",");
                break;
              case "ws30":
                content.append(resultList.get(i).get("ws30") + ",");
                break;
              case "ws50":
                content.append(resultList.get(i).get("ws50") + ",");
                break;
              case "ws70":
                content.append(resultList.get(i).get("ws70") + ",");
                break;
              case "ws80":
                content.append(resultList.get(i).get("ws80") + ",");
                break;
              case "ws90":
                content.append(resultList.get(i).get("ws90") + ",");
                break;
              case "ws110":
                content.append(resultList.get(i).get("ws110") + ",");
                break;
              case "ws170":
                content.append(resultList.get(i).get("ws170") + ",");
                break;
              case "rDq":
                content.append(tableResult.get(i).get("rDq") + ",");
                break;
              case "rCdq":
                content.append(tableResult.get(i).get("rCdq") + ",");
                break;
            }
          }
          content.append("\r\n");
          templateContent.append(content.toString());
        }
      }

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

      response.setContentType("application/x-msdownload;charset=UTF-8");// 文件下载必须配置为application/x-msdownload
      response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(sdf.format(startTime) + "至" + sdf.format(endTime) + "实时预测查询导出文件" + ".csv", "UTF-8"));// 中文文件名必须使用URLEncoder.encode进行转码
      byte[] templateContentBytes = templateContent.toString().getBytes("UTF-8");
      bos = new BufferedOutputStream(response.getOutputStream());// 向response中写入文件流
      bos.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});// 指定csv文件用UTF-8字符集打开
      bos.write(templateContentBytes);
      response.flushBuffer();
      templateContent = null;

    } catch (Exception e) {
      log.error("系统错误：" + e.getMessage(), e);
      throw new RuntimeException(e);
    } finally {
      if (bos != null) {
        try {
          bos.close();
        } catch (IOException e) {
          log.error("系统错误：" + e.getMessage(), e);
        }
      }
    }


    return ResponseVO.success();
  }

  @PostMapping(value = "/ComprehensiveContrastExports")
  public ResponseVO exportExcelForImg(Long startTime,
                                              Long endTime,
                                              Integer no,
                                              String otherType,
                                              Long jgTime,
                                              String base64) throws Exception
  {
    //创建Excel工作簿，xls格式用HSSFWorkbook，xlsx格式用SXSSFWorkbook
    HSSFWorkbook wb = new HSSFWorkbook();
    //创建sheet页
    HSSFSheet sheet = wb.createSheet();
    //创建绘图(画布)，注明：一个sheet只能创建一个画布，但一个画布中可以添加多张图片
    HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
    String fileContent;
    // 图片编码只要‘base64,’后面的部分
    fileContent = URLDecoder.decode(base64,"UTF-8").substring(22);

    //#########################插入数据#########################
    Map<String, Object> map = realTimeComprehensiveContrastService.realTimeComprehensiveContrast(startTime, endTime, no, otherType, jgTime);
    BufferedOutputStream bos = null;
    StringBuilder templateContent = new StringBuilder();
    ElectricField electricField = electricFieldService.get();
    DisplayConfig displayConfig = null;
    if (electricField.getElectricFieldTypeEnum().getCode() == 1) {
      displayConfig = displayConfigService.findByDisplayCode("rtWeatherStationInfos");
      String showCode = displayConfig.getShowCode();
      String[] split = showCode.split(",");
      //创建第一行 0为第一行
      HSSFRow row1=sheet.createRow(0);
      //设置第一个单元格
      row1.createCell(0).setCellValue("时间");
      String displayKyLl = (String) map.get("displayKyLl");
      int flag = 1 ;
      for (int i = 0; i < split.length; i++) {
        switch (split[i]) {
          case "realValue":
            row1.createCell(flag).setCellValue("实际功率");
            flag++;
            if (displayKyLl.equals("1")) {
              row1.createCell(flag).setCellValue("可用功率");
              flag++;
              row1.createCell(flag).setCellValue("理论功率");
              flag++;
              row1.createCell(flag).setCellValue("参照功率（样板机）");
              flag++;
              row1.createCell(flag).setCellValue("参照功率（测风、测光）");
              flag++;
            }
            break;
          case "rDq":
            row1.createCell(flag).setCellValue("实时短期");
            flag++;
            break;
          case "rCdq":
            row1.createCell(flag).setCellValue("实时超短期");
            flag++;
            break;
          case "globalR":
            row1.createCell(flag).setCellValue("总辐射");
            flag++;
            break;
          case "directR":
            row1.createCell(flag).setCellValue("直辐射");
            flag++;
            break;
          case "diffuseR":
            row1.createCell(flag).setCellValue("散辐射");
            flag++;
            break;
          case "obliqueR":
            row1.createCell(flag).setCellValue("斜辐射");
            flag++;
            break;
          case "directRadiation":
            row1.createCell(flag).setCellValue("nwp直辐射");
            flag++;
            break;
          case "diffuseRadiation":
            row1.createCell(flag).setCellValue("nwp散辐射");
            flag++;
            break;
          case "swr":
            row1.createCell(flag).setCellValue("nwp总辐射");
            flag++;
            break;
        }
      }

      List<Map<String, Float>> tableResult = (List<Map<String, Float>>) map.get("tableResult");
      List<Map<String, Float>> resultList = (List<Map<String, Float>>) map.get("resultList");

      for (int i = 0; i < tableResult.size(); i++) {
        int flags = 0;
        HSSFRow row=sheet.createRow(i+1);
        row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("time")));
        flags++;
        for (int n = 0; n < split.length; n++) {
          switch (split[n]) {
            case "realValue":
              row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("realValue")));
              flags++;
              if (displayKyLl.equals("1")) {
                row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("ableValue")));
                flags++;
                row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("theoryValue")));
                flags++;
                row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("referencePowerBySample")));
                flags++;
                row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("referencePowerByMeasuring")));
                flags++;
              }
              break;
            case "rDq":
              row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("rDq")));
              flags++;
              break;
            case "rCdq":
              row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("rCdq")));
              flags++;
              break;
            case "globalR":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("globalR")));
              flags++;
              break;
            case "directR":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("directR")));
              flags++;
              break;
            case "diffuseR":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("diffuseR")));
              flags++;
              break;
            case "obliqueR":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("obliqueR")));
              flags++;
              break;
            case "directRadiation":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("directRadiation")));
              flags++;
              break;
            case "diffuseRadiation":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("diffuseRadiation")));
              flags++;
              break;
            case "swr":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("swr")));
              flags++;
              break;
          }
        }
      }

    } else {

      displayConfig = displayConfigService.findByDisplayCode("rtWindTowerInfos");
      String showCode = displayConfig.getShowCode();
      String[] split = showCode.split(",");
      //创建第一行 0为第一行
      HSSFRow row1=sheet.createRow(0);
      //设置第一个单元格
      row1.createCell(0).setCellValue("时间");
      int flag = 1 ;
      String displayKyLl = (String) map.get("displayKyLl");

      for (int i = 0; i < split.length; i++) {
        switch (split[i]) {
          case "realValue":
            row1.createCell(flag).setCellValue("实际功率");
            flag++;
            if (displayKyLl.equals("1")) {
              row1.createCell(flag).setCellValue("可用功率");
              flag++;
              row1.createCell(flag).setCellValue("理论功率");
              flag++;
              row1.createCell(flag).setCellValue("参照功率（样板机）");
              flag++;
              row1.createCell(flag).setCellValue("参照功率（测风、测光）");
              flag++;
            }
            break;
          case "wsInst10":
            row1.createCell(flag).setCellValue("10米风速");
            flag++;
            break;
          case "wsInst30":
            row1.createCell(flag).setCellValue("30米风速");
            flag++;
            break;
          case "wsInst50":
            row1.createCell(flag).setCellValue("50米风速");
            flag++;
            break;
          case "wsInst60":
            row1.createCell(flag).setCellValue("60米风速");
            flag++;
            break;
          case "wsInst70":
            row1.createCell(flag).setCellValue("70米风速");
            flag++;
            break;
          case "wsInst80":
            row1.createCell(flag).setCellValue("80米风速");
            flag++;
            break;
          case "wsInst90":
            row1.createCell(flag).setCellValue("90米风速");
            flag++;
            break;
          case "wsInst100":
            row1.createCell(flag).setCellValue("100米风速");
            flag++;
            break;
          case "wsInst110":
            row1.createCell(flag).setCellValue("110米风速");
            flag++;
            break;
          case "wsInst120":
            row1.createCell(flag).setCellValue("120米风速");
            flag++;
            break;
          case "wsInstHubHeight":
            row1.createCell(flag).setCellValue("轮毂风速");
            flag++;
            break;
          case "ws10":
            row1.createCell(flag).setCellValue("nwp10米风速");
            flag++;
            break;
          case "ws30":
            row1.createCell(flag).setCellValue("nwp30米风速");
            flag++;
            break;
          case "ws50":
            row1.createCell(flag).setCellValue("nwp50米风速");
            flag++;
            break;
          case "ws70":
            row1.createCell(flag).setCellValue("nwp70米风速");
            flag++;
            break;
          case "ws80":
            row1.createCell(flag).setCellValue("nwp80米风速");
            flag++;
            break;
          case "ws90":
            row1.createCell(flag).setCellValue("nwp90米风速");
            flag++;
            break;
          case "ws100":
            row1.createCell(flag).setCellValue("nwp100米风速");
            flag++;
            break;
          case "ws170":
            row1.createCell(flag).setCellValue("nwp170米风速");
            flag++;
            break;
          case "rDq":
            row1.createCell(flag).setCellValue("实时短期");
            flag++;
            break;
          case "rCdq":
            row1.createCell(flag).setCellValue("实时超短期");
            flag++;
            break;
        }
      }
      List<Map<String, Float>> tableResult = (List<Map<String, Float>>) map.get("tableResult");
      List<Map<String, Float>> resultList = (List<Map<String, Float>>) map.get("resultList");

      for (int i = 0; i < tableResult.size(); i++) {
        int flags=0;
        HSSFRow row=sheet.createRow(i+1);
        row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("time")));
        flags++;
        for (int n = 0; n < split.length; n++) {
          switch (split[n]) {
            case "realValue":
              row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("realValue")));
              flags++;
              if (displayKyLl.equals("1")) {
                row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("ableValue")));
                flags++;
                row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("theoryValue")));
                flags++;
                row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("referencePowerBySample")));
                flags++;
                row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("referencePowerByMeasuring")));
                flags++;
              }
              break;
            case "wsInst10":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("wsInst10")));
              flags++;
              break;
            case "wsInst30":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("wsInst30")));
              flags++;
              break;
            case "wsInst50":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("wsInst50")));
              flags++;
              break;
            case "wsInst60":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("wsInst60")));
              flags++;
              break;
            case "wsInst70":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("wsInst70")));
              flags++;
              break;
            case "wsInst80":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("wsInst80")));
              flags++;
              break;
            case "wsInst90":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("wsInst90")));
              flags++;
              break;
            case "wsInst100":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("wsInst100")));
              flags++;
              break;
            case "wsInst110":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("wsInst110")));
              flags++;
              break;
            case "wsInst120":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("wsInst120")));
              flags++;
              break;
            case "wsInstHubHeight":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("wsInstHubHeight")));
              flags++;
              break;
            case "ws10":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("ws10")));
              flags++;
              break;
            case "ws30":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("ws30")));
              flags++;
              break;
            case "ws50":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("ws50")));
              flags++;
              break;
            case "ws70":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("ws70")));
              flags++;
              break;
            case "ws80":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("ws80")));
              flags++;
              break;
            case "ws90":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("ws90")));
              flags++;
              break;
            case "ws100":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("ws100")));
              flags++;
              break;
            case "ws170":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("ws170")));
              flags++;
              break;
            case "rDq":
              row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("rDq")));
              flags++;
              break;
            case "rCdq":
              row.createCell(flags).setCellValue(String.valueOf(tableResult.get(i).get("rCdq")));
              flags++;
              break;
          }
        }
      }
    }
    //画图
    createPictureInExcel(fileContent, patriarch, wb);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String filename = sdf.format(startTime) + "至" + sdf.format(endTime) + "实时预测查询导出文件" + ".xls";
    File filepath = new File("/home/syjy/ipfcstV3/reportForm/");
    File file = new File("/home/syjy/ipfcstV3/reportForm/",filename);
    //File file = new File("/Users/wanghongchen/"+filename);
    if (!filepath.exists()){
      filepath.mkdir();
    }
    if(!file.exists()){
      file.createNewFile();
    }
    OutputStream out = new FileOutputStream(file);
    wb.write(out);
    wb.close();
    return ResponseVO.success(filename);
    //将文件生成到本地 读取本地文件调用浏览器下载
  }

  public static void createPictureInExcel(String dataChart, HSSFPatriarch patriarch, HSSFWorkbook wb) throws Exception{
    //用于将BASE64编码格式转为byte数组
    BASE64Decoder base64Decoder = new BASE64Decoder();
    ByteArrayOutputStream dataChartoutStream = new ByteArrayOutputStream();
    //将dataChartStringin作为输入流，读取图片存入image中
    ByteArrayInputStream dataChartin = new ByteArrayInputStream(base64Decoder.decodeBuffer(dataChart));

    BufferedImage dataChartbufferImg = ImageIO.read(dataChartin);
    //利用HSSFPatriarch将图片写入EXCEL
    ImageIO.write(dataChartbufferImg, "png", dataChartoutStream);
    /*
     * 指定绘图区域位置及大小
     * HSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2)
     * 参数说明：
     * dx1 dy1 起始单元格中的x,y坐标.
     * dx2 dy2 结束单元格中的x,y坐标.
     * col1,row1 指定起始的单元格，下标从0开始.
     * col2,row2 指定结束的单元格 ，下标从0开始.
     */
    HSSFClientAnchor anchorCostStr = new HSSFClientAnchor(10, 10, 255, 255,(short) 10, 10, (short) 20, 28);
    //画图
    patriarch.createPicture(anchorCostStr, wb.addPicture(dataChartoutStream.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
  }
  /**
   * 文件下载
   *
   * @param request  HttpServletRequest
   * @param response HttpServletResponse
   * @param path     路径
   * @param name     文件名
   * @param type     文件类型
   */
  @PostMapping(value = "/downLoadFile")
  public void downLoadFile(HttpServletRequest request,
                           HttpServletResponse response,
                           String path,
                           String name,
                           String type) {
    response.setContentType("text/html;charset=utf-8");
    try {
      request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e1) {
      log.error("系统错误：" + e1.getMessage(), e1);
    }

    String downLoadPath = path + File.separator + name;
    if (name.isEmpty()) {//传入name为空，说明是一级目录，路径中已经包涵最后一级目录
      name = path.substring(path.lastIndexOf(File.separator) + 1, path.length());
      downLoadPath = path;
    }
    try {
      File df = new File(downLoadPath);
      InputStream ins = new FileInputStream(df);
      BufferedInputStream bins = new BufferedInputStream(ins);
      OutputStream outs = response.getOutputStream();
      BufferedOutputStream bouts = new BufferedOutputStream(outs);
      response.setHeader("Content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(name, "UTF-8"));
      response.setContentType("application/x-msdownload; charset=utf-8");
      int bytesRead = 0;
      byte[] buffer = new byte[8192];
      while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
        bouts.write(buffer, 0, bytesRead);
      }
      bouts.flush();
      ins.close();
      bins.close();
      bouts.close();
      File deleteFile = new File(downLoadPath);
      deleteFile.delete();
    } catch (Exception e) {
      log.error("系统错误：" + e.getMessage(), e);
    }
  }
}
