package com.jiayue.ipfcst.controller;

import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import com.jiayue.ipfcst.common.data.entity.InverterInfo;
import com.jiayue.ipfcst.common.data.entity.InverterStatusData;
import com.jiayue.ipfcst.service.InverterInfoService;
import com.jiayue.ipfcst.service.InverterStatusDataService;
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 InverterStatusDataController {

  private final InverterStatusDataService inverterStatusDataService;
  private final InverterInfoService inverterInfoService;

  @Autowired
  public InverterStatusDataController(InverterStatusDataService inverterStatusDataService,InverterInfoService inverterInfoService) {
    this.inverterStatusDataService = inverterStatusDataService;
    this.inverterInfoService = inverterInfoService;
  }


  /**
   * 分页查询 所有逆变器功率状态
   *
   * @param startTime     开始时间
   * @param endTime       结束时间
   * @param page          页码
   * @param size          条数
   * @param timeSortOrder 时间排序
   * @param noSortOrder   设备编号排序
   * @return
   */
  @GetMapping(value = "/inverterStatusData/{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 = inverterStatusDataService.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      条数
   * @param sortOrder 排序
   * @return
   */
  @GetMapping(value = "/inverterStatusData/{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 sortOrder,
                                               String timeSortOrder, String noSortOrder) {
    Map<String, Object> map = new HashMap<>();
    try {
      map = inverterStatusDataService.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());
    }
  }


  /**
   * 分页查询  按设备编号查询逆变器状态
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @return
   */
  @GetMapping(value = "/export/inverterStatusData/{startTime}/{endTime}/{no}")
  public ResponseVO findByTimeBetweenAndNo(@PathVariable("startTime") Long startTime,
                                           @PathVariable("endTime") Long endTime,
                                           @PathVariable("no") Integer[] no,
                                           HttpServletResponse response
  ) {
    BufferedOutputStream bos = null;
    try {
      List<InverterInfo> inverterInfos = inverterInfoService.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<InverterStatusData> inverterStatusDatas = inverterStatusDataService.findByTimeBetweenAndNo(startTime, endTime, no);

      List<InverterStatusData> inverterStatusDataList = inverterStatusDatas.stream().sorted(Comparator.comparing(InverterStatusData::getEquipmentNo)).sorted(Comparator.comparing(InverterStatusData::getTime)).collect(Collectors.toList());
      String header = "\"时间\"," + "\"设备编号\"," + "\"有功(KW)\"," + "\"无功(KW)\"," + "\"功率因数\"," + "\"电压(V)\"," + "\"电流(A)\"," + "\"当日发电量(kW-h)\"," + "\"当日并网小时\"," + "\"状态\"" + "\r\n";
      templateContent.append(header);

      StringBuilder content = new StringBuilder();
      for (InverterStatusData s : inverterStatusDataList) {
        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.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();
  }


}
