package com.jiayue.ipfcst.controller;

import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import com.jiayue.ipfcst.common.data.entity.PowerStationStatusDataOne;
import com.jiayue.ipfcst.common.data.entity.SysParameter;
import com.jiayue.ipfcst.common.data.repository.SysParameterRepository;
import com.jiayue.ipfcst.service.PowerStationStatusDataOneService;
import com.jiayue.ipfcst.service.PowerStationStatusDataService;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 实际功率restful接口
 *
 * @author yh
 * @version 1.0
 * @since 2019/8/7 10:12
 */
@RestController
@Slf4j
public class PowerStationStatusDataOneController {

  private final PowerStationStatusDataOneService powerStationStatusDataOneService;
  private final SysParameterRepository sysParameterRepository;

  @Autowired
  public PowerStationStatusDataOneController(PowerStationStatusDataService powerStationStatusDataService, PowerStationStatusDataOneService powerStationStatusDataOneService, SysParameterRepository sysParameterRepository) {
    this.powerStationStatusDataOneService = powerStationStatusDataOneService;
    this.sysParameterRepository = sysParameterRepository;
  }

  /**
   * 根据开始时间和结束时间查询 场站功率状态
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @return 结果集
   */
  @GetMapping(value = "/powerStationStatusOne/{startTime}/{endTime}")
  public ResponseVO findByTimeBetween(@PathVariable("startTime") Long startTime,
                                      @PathVariable("endTime") Long endTime) {
    Map<String, Object> map = new HashMap<>();
    try {
      map = powerStationStatusDataOneService.findByTimeBetween(new Date(startTime), new Date(endTime));
      return ResponseVO.success(map);
    } catch (Exception e) {
      e.printStackTrace();
      log.error("场站功率状态查询错误");
      return ResponseVO.fail(e.getMessage());
    }
  }

  /**
   * 分页查询 场站功率状态
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @param page      页码
   * @param size      条数
   * @param sortOrder 排序
   * @return
   */
  @GetMapping(value = "/powerStationStatusOne/{startTime}/{endTime}/{page}/{size}")
  public ResponseVO findByTimeBetweenForPaging(@PathVariable("startTime") Long startTime,
                                               @PathVariable("endTime") Long endTime,
                                               @PathVariable("page") Integer page,
                                               @PathVariable("size") Integer size,
                                               String sortOrder) {
    Map<String, Object> map = new HashMap<>();
    try {
      map = powerStationStatusDataOneService.findByTimeBetweenForPaging(new Date(startTime), new Date(endTime), page, size, sortOrder);
      return ResponseVO.success(map);
    } catch (Exception e) {
      e.printStackTrace();
      log.error("场站功率状态分页查询错误");
      return ResponseVO.fail(e.toString());
    }
  }

  /**
   * 分页查询 受阻电量
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @return
   */
  @GetMapping(value = "/balkPowerOne/{startTime}/{endTime}")
  public ResponseVO findBalkPower(@PathVariable("startTime") Long startTime,
                                  @PathVariable("endTime") Long endTime) {
    try {
      List<Map<String, Object>> balkPower = powerStationStatusDataOneService.findBalkPower(new Date(startTime), new Date(endTime));
      return ResponseVO.success(balkPower);
    } catch (Exception e) {
      e.printStackTrace();
      log.error("受阻电量查询错误");
      return ResponseVO.fail(e.toString());
    }


  }


  /**
   * 实际功率表格导出
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @return
   */
  @GetMapping(value = "export/powerStationStatusOne/{startTime}/{endTime}")
  public ResponseVO export(@PathVariable("startTime") Long startTime,
                           @PathVariable("endTime") Long endTime,
                           HttpServletResponse response

  ) {
    BufferedOutputStream bos = null;
    try {
      StringBuilder templateContent = new StringBuilder();
      response.setCharacterEncoding("UTF-8");
      List<PowerStationStatusDataOne> powerStationStatusDataList = powerStationStatusDataOneService.findByTimeBetween(startTime, endTime);

      String header = "\"时间\"," + "\"实际功率\"," + "\"开机容量\","+ "\"人工判断是否限电\","+ "\"系统判断是否限电\"," + "\"装机容量\"" + "\r\n";
      SysParameter sysParameter = sysParameterRepository.findBySysKeyEquals("DISPLAY_KY_LL");
      StringBuilder content = new StringBuilder();
      if (sysParameter != null && sysParameter.getSysValue().equals("1")) {
        header = "\"时间\"," + "\"实际功率\"," + "\"可用功率\",\"理论功率\",\"参照理论功率（样板机）\",\"参照理论功率（测风、测光）\",\"参照理论功率（机头风速）\",\"参照可用功率（样板机）\",\"参照可用功率（测风、测光）\",\"参照可用功率（机头风速）\"," + "\"开机容量\","+ "\"人工判断是否限电\","+ "\"系统判断是否限电\"," + "\"装机容量\"" + "\r\n";
        templateContent.append(header);
        powerStationStatusDataList.forEach(s -> {
          String isRationingByManualControl = "系统判断";
          if(s.getIsRationingByManualControl()==1){
            isRationingByManualControl ="限电";
          }else if (s.getIsRationingByManualControl()==2){
            isRationingByManualControl = "不限电";
          }
          String time = DateFormatUtils.format(s.getTime(),"yyyy-MM-dd HH:mm:ss");
            content.append(time + "," + s.getRealValue() + "," + s.getAbleValue() + "," + s.getTheoryValue() + "," + s.getReferencePowerBySample() + "," + s.getReferencePowerByMeasuring() + ","+ s.getReferencePowerByHubSpeed()+ "," + s.getAblePowerBySample() + "," + s.getAblePowerByMeasuring() +"," + s.getAblePowerByHubSpeed()+ "," + s.getOpenCapacity() + ","  + isRationingByManualControl + ","  + (s.getIsRationingByAutoControl()?"限电":"不限电") + ","+ s.getCapacity() + "\r\n");
        });
      } else {
        templateContent.append(header);
        powerStationStatusDataList.forEach(s -> {
          String isRationingByManualControl = "系统判断";
          if(s.getIsRationingByManualControl()==1){
            isRationingByManualControl ="限电";
          }else if (s.getIsRationingByManualControl()==2){
            isRationingByManualControl = "不限电";
          }
          String time = DateFormatUtils.format(s.getTime(),"yyyy-MM-dd HH:mm:ss");
          content.append(time+ "," + s.getRealValue() + "," + s.getOpenCapacity() + ","  + isRationingByManualControl + ","  + (s.getIsRationingByAutoControl()?"限电":"不限电") + "," + s.getCapacity() + "\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();
  }
}
