package com.jiayue.ipfcst.controller;

import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import com.jiayue.ipfcst.common.data.entity.WindTurbineInfo;
import com.jiayue.ipfcst.common.data.entity.WindTurbineStatusData;
import com.jiayue.ipfcst.service.WindTurbineInfoService;
import com.jiayue.ipfcst.service.WindTurbineStatusDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
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.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class WindTurbineStatusDataController {

  private final WindTurbineStatusDataService windTurbineStatusDataService;
  private final WindTurbineInfoService windTurbineInfoService;
  @Autowired
  public WindTurbineStatusDataController(WindTurbineStatusDataService windTurbineStatusDataService,WindTurbineInfoService windTurbineInfoService){
    this.windTurbineStatusDataService = windTurbineStatusDataService;
    this.windTurbineInfoService = windTurbineInfoService;
  }


  /**
   * 分页查询 所有风机功率状态
   * @param startTime 开始时间
   * @param endTime 结束时间
   * @param page 页码
   * @param size 条数
   * @param timeSortOrder 时间排序
   * @param noSortOrder 设备编号排序
   * @return
   */
  @GetMapping(value = "/windTurbineStatusData/{startTime}/{endTime}/{page}/{size}")
  public ResponseVO findByTimeBetweenForPaging(@PathVariable("startTime") Long startTime,
                                               @PathVariable("endTime") Long endTime,
                                               @PathVariable("page") Integer page,
                                               @PathVariable("size") Integer size,
                                               String timeSortOrder,String noSortOrder){
    Map<String,Object> map = new HashMap<>();
    try{
      map =  windTurbineStatusDataService.findByTimeBetweenForPaging(new Date(startTime),new Date(endTime),page,size,timeSortOrder,noSortOrder);
      return ResponseVO.success(map);
    }catch(Exception e){
      e.printStackTrace();
      log.error("风机分页查询错误");
      return ResponseVO.fail(e.toString());
    }
  }

  /**
   * 分页查询  按设备编号查询风机状态
   * @param startTime 开始时间
   * @param endTime 结束时间
   * @param page 页码
   * @param size 条数
   * @return
   */
  @GetMapping(value = "/windTurbineStatusData/{startTime}/{endTime}/{page}/{size}/{no}")
  public ResponseVO findByTimeBetweenForPaging(@PathVariable("startTime") Long startTime,
                                               @PathVariable("endTime") Long endTime,
                                               @PathVariable("page") Integer page,
                                               @PathVariable("size") Integer size,
                                               @PathVariable("no") Integer[] no,
                                               String timeSortOrder,String noSortOrder){
    Map<String,Object> map = new HashMap<>();
    try{
      map =  windTurbineStatusDataService.findByTimeBetweenAndNoForPaging(new Date(startTime),new Date(endTime),page,size,no,timeSortOrder,noSortOrder);
      return ResponseVO.success(map);
    }catch(Exception e){
      e.printStackTrace();
      log.error("按设备号风机分页查询错误");
      return ResponseVO.fail(e.toString());
    }
  }



  @GetMapping(value = "/export/windTurbineStatusData/{startTime}/{endTime}/{no}")
  public ResponseVO findByTimeBetweenAndNoIn(@PathVariable("startTime") Long startTime,
                                             @PathVariable("endTime") Long endTime,
                                             @PathVariable("no") Integer[] no,
                                             HttpServletResponse response
  ) {
    BufferedOutputStream bos = null;
    try {
      List<WindTurbineInfo> inverterInfos = windTurbineInfoService.findAllByOrderByIdAsc();
      Map<Integer, String> map = new HashMap<>();

      inverterInfos.forEach(s -> {
        map.put(s.getId(), s.getName());
      });

      StringBuilder templateContent = new StringBuilder();
      response.setCharacterEncoding("UTF-8");
      List<WindTurbineStatusData> windTurbineStatusDatas = windTurbineStatusDataService.findByTimeAndNoIn(new Date(startTime), new Date(endTime), no);

      List<WindTurbineStatusData> windTurbineStatusDataList = windTurbineStatusDatas.stream().sorted(Comparator.comparing(WindTurbineStatusData::getEquipmentNo)).sorted(Comparator.comparing(WindTurbineStatusData::getTime)).collect(Collectors.toList());
      String header = "\"时间\"," + "\"设备编号\"," + "\"有功(KW)\"," + "\"无功(KW)\"," + "\"功率因数\"," + "\"电压(V)\"," + "\"电流(A)\"," + "\"当日发电量(kW-h)\"," + "\"当日并网小时\"," + "\"转速(rpm)\"," + "\"风速(m/s)\"," + "\"风向(°)\"," + "\"温度(℃)\"," + "\"桨距角(°)\"," + "\"状态\"" + "\r\n";
      templateContent.append(header);

      StringBuilder content = new StringBuilder();
      for (WindTurbineStatusData s : windTurbineStatusDataList) {
        content.append(DateFormatUtils.format(s.getTime(), "yyyy-MM-dd HH:mm:ss") + "," + map.get(s.getEquipmentNo()) + "," + s.getActivePower() + "," + s.getReactivePower() + "," + s.getPowerFactor() + "," + s.getVoltage() + "," + s.getElectricalCurrent() + "," + s.getDayElectricQuantity() + "," + s.getDayGridConnectedHours() + "," + s.getWindWheelRatedSpeed() + "," + s.getWs() + "," + s.getWd() + "," + s.getT() + "," + s.getPitchAngle() + "," + s.getStatus() + "\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();
  }
}
