package com.jiayue.ipfcst.service;

import com.jiayue.ipfcst.common.core.exception.BusinessException;
import com.jiayue.ipfcst.common.data.entity.ElectricField;
import com.jiayue.ipfcst.common.data.service.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 导出
 *
 * @author yh
 * @version 1.0
 * @since 2019/8/5 16:02
 */
@Service
@Slf4j
public class ExportFileService extends BaseService {

  /**
   * 导出短期数据
   * @param map 短期map
   * @throws BusinessException 业务异常
   */
  public void exportForForecastPowerShortTerm(Map<String, Object> map, HttpServletResponse response) throws Exception {

    BufferedOutputStream bos = null;
    try {
      StringBuilder templateContent = new StringBuilder();
      response.setCharacterEncoding("UTF-8");
      ElectricField electricField = getElectricField();
      String header =  "\"场站名称\"" + "," + "\"时间\"" + "," + "\"预测功率\"" + "\r\n";
      List<String> times = (List<String>)map.get("times");
      List<Float> datas = (List<Float>)map.get("datas");
      templateContent.append(header);
      for (int i = 0; i <times.size() ; i++) {
        StringBuilder content = new StringBuilder();
        content.append(electricField.getName() + ",");

        content.append(times.get(i) + ",");

        if(datas.get(i) == null){
          content.append(","+"\r\n");
        }else{
          content.append(datas.get(i)  + "\r\n");
        }

        templateContent.append(content.toString());
      }

      response.setContentType("application/x-msdownload;charset=UTF-8");// 文件下载必须配置为application/x-msdownload
      response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("实时短期数据"+".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);
        }
      }
    }

  }


}
