package com.jiayue.ipfcst.controller;

import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import com.jiayue.ipfcst.common.data.entity.NwpOne;
import com.jiayue.ipfcst.service.NwpOneService;
import lombok.extern.slf4j.Slf4j;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * NWP信息restful接口
 *
 * @author yh
 * @version 1.0
 * @since 2019/8/7 10:12
 */
@RestController
@Slf4j
public class NwpOneController {
  private final NwpOneService nwpOneService;

  @Autowired
  public NwpOneController(NwpOneService nwpOneService) {
    this.nwpOneService = nwpOneService;
  }

  /**
   * 按时间查询实时nwp yh
   * @param startTime 开始时间
   * @param endTime 结束时间
   * @return 结果集
   */
  @GetMapping(value = "/nwpOne/{startTime}/{endTime}")
  public ResponseVO findByForecastTimeBetween(@PathVariable("startTime") Long startTime,
                                          @PathVariable("endTime") Long endTime){
    Map<String,Object> map = new HashMap<>();
    try{
      map = nwpOneService.findByForecastTimeBetween(startTime,endTime);
      return ResponseVO.success(map);
    }catch(Exception e){
      e.printStackTrace();
      log.error("nwp实时查询错误");
      return ResponseVO.fail(e.toString());
    }
  }

  /**
   * 分页查询  实时nwp
   * @param startTime 开始时间
   * @param endTime 结束时间
   * @param page 页码
   * @param size 条数
   * @param sortOrder 排序
   * @return
   */
  @GetMapping(value = "/nwpOne/{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 =  nwpOneService.findByTimeBetweenAndNoForPaging(startTime,endTime,page,size,sortOrder);
      return ResponseVO.success(map);
    }catch(Exception e){
      e.printStackTrace();
      log.error("nwp实时分页查询错误");
      return ResponseVO.fail(e.toString());
    }
  }

  /**
   * nwp数据表格导出
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @return
   */
  @GetMapping(value = "export/nwpOne/{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<NwpOne> nwpList = nwpOneService.findByTimeBetween(startTime, endTime);
      SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

      String header = "\"预测时间\"," + "\"生成时间\"," + "\"温度\"," + "\"湿度\"," + "\"气压\"," + "\"总辐射\"," + "\"直辐射\"," + "\"散辐射\"," + "\"10米风速\"," + "\"30米风速\"," + "\"50米风速\"," + "\"70米风速\"," + "\"80米风速\"," + "\"90米风速\"," + "\"100米风速\"," + "\"170米风速\"," + "\"10米风向\"," + "\"30米风向\"," + "\"50米风向\"," + "\"70米风向\"," + "\"80米风向\"," + "\"90米风向\"," + "\"100米风向\"," + "\"170米风向\"," + "\r\n";
      StringBuilder content = new StringBuilder();
      nwpList.forEach(n ->{
        content.append(sdf1.format(n.getPreTime())+","+n.getScTime()+","+n.getT()+","+n.getRh()+","+n.getPressure()+","+n.getLwr()+","+n.getDirectRadiation()+","+n.getDiffuseRadiation()+","+n.getWs10()+","+n.getWs30()+","+n.getWs50()+","+n.getWs70()+","+n.getWs80()+","+n.getWs90()+","+n.getWs100()+","+n.getWs170()+","+n.getWd10()+","+n.getWd30()+","+n.getWd50()+","+n.getWd70()+","+n.getWd80()+","+n.getWd90()+","+n.getWd100()+","+n.getWd170() + "\r\n");
      });


      templateContent.append(header);
      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) + "nwp导出文件" + ".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();
  }

  @GetMapping(value = "nwpOne/getNwpDay")
  public ResponseVO getNwpDay(){
    return ResponseVO.success(nwpOneService.getNwpDay());
  }
}
