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.service.DisplayConfigService;
import com.jiayue.ipfcst.service.ElectricFieldService;
import com.jiayue.ipfcst.service.ReportWindTowerStatusDataService;
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 java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;


/**
 * 上报测风塔数据restful接口
 *
 * @author tl
 * @version 3.0
 * @since 2022/4/13 12:12
 */
@RestController
@Slf4j
public class ReportWindTowerStatusDataController {

  private final ReportWindTowerStatusDataService reportWindTowerStatusDataService;
  private final DisplayConfigService displayConfigService;
  private final ElectricFieldService electricFieldService;

  @Autowired
  public ReportWindTowerStatusDataController(ReportWindTowerStatusDataService reportWindTowerStatusDataService,
                                             DisplayConfigService displayConfigService,
                                             ElectricFieldService electricFieldService){
    this.reportWindTowerStatusDataService = reportWindTowerStatusDataService;
    this.displayConfigService = displayConfigService;
    this.electricFieldService = electricFieldService;
  }

  /**
   * 综合数据对比查询
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @param no
   * @return
   */
  @GetMapping(value = "reportWindTowerStatusData/{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(reportWindTowerStatusDataService.reportWindTowerStatusData(startTime, endTime, no, otherType, jgTime));
  }



  @PostMapping(value = "/reportWindTowerStatusDataExport")
  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 = reportWindTowerStatusDataService.reportWindTowerStatusData(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("reportWindTowerStatusData");
      String showCode = displayConfig.getShowCode();
      String[] split = showCode.split(",");
      //创建第一行 0为第一行
      HSSFRow row1=sheet.createRow(0);
      //设置第一个单元格
      row1.createCell(0).setCellValue("时间");
      int flag = 1 ;


      for (int i = 0; i < split.length; i++) {
        switch (split[i]) {

          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 "ws10":
            row1.createCell(flag).setCellValue("上报10米风速");
            flag++;
            break;
          case "ws30":
            row1.createCell(flag).setCellValue("上报30米风速");
            flag++;
            break;
          case "ws50":
            row1.createCell(flag).setCellValue("上报50米风速");
            flag++;
            break;
          case "ws60":
            row1.createCell(flag).setCellValue("上报60米风速");
            flag++;
            break;
          case "ws70":
            row1.createCell(flag).setCellValue("上报70米风速");
            flag++;
            break;
          case "ws80":
            row1.createCell(flag).setCellValue("上报80米风速");
            flag++;
            break;
          case "ws90":
            row1.createCell(flag).setCellValue("上报90米风速");
            flag++;
            break;
          case "ws100":
            row1.createCell(flag).setCellValue("上报100米风速");
            flag++;
            break;
          case "ws110":
            row1.createCell(flag).setCellValue("上报110米风速");
            flag++;
            break;
          case "ws120":
            row1.createCell(flag).setCellValue("上报120米风速");
            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 "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 "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 "ws60":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("ws60")));
              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 "ws110":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("ws110")));
              flags++;
              break;
            case "ws120":
              row.createCell(flags).setCellValue(String.valueOf(resultList.get(i).get("ws120")));
              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 filepath = new File("D:\\ipfcstV3\\reportForm\\");
    File file = new File("/home/syjy/ipfcstV3/reportForm/",filename);
    //File file = new File("D:\\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));
  }

}
