package com.jiayue.ipfcst.controller;

import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import com.jiayue.ipfcst.common.data.entity.WeatherStationStatusData;
import com.jiayue.ipfcst.service.WeatherStationStatusDataService;
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.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 WeatherStationStatusDataController {

  private final WeatherStationStatusDataService weatherStationStatusDataService;

  @Autowired
  public WeatherStationStatusDataController(WeatherStationStatusDataService weatherStationStatusDataService){
    this.weatherStationStatusDataService=weatherStationStatusDataService;
  }

  /**
   * 根据开始时间和结束时间查询 气象数据
   * @param startTime 开始时间
   * @param endTime 结束时间
   * @return 结果集
   */
  @GetMapping(value = "/weatherStationStatusData/{startTime}/{endTime}/{no}")
  public ResponseVO findByTimeBetweenAndEquipmentNo(@PathVariable("startTime") Long startTime,
                                      @PathVariable("endTime") Long endTime,
                                      @PathVariable("no") Integer no){
    Map<String,Object> map = new HashMap<>();
    try{
      map = weatherStationStatusDataService.findByTimeBetweenAndEquipmentNo(new Date(startTime),new Date(endTime),no);
      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 = "/weatherStationStatusData/{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){
    Map<String,Object> map = new HashMap<>();
    try{
      map =  weatherStationStatusDataService.findByTimeBetweenForPaging(new Date(startTime),new Date(endTime),page,size,no,sortOrder);
      return ResponseVO.success(map);
    }catch(Exception e){
      e.printStackTrace();
      log.error("气象数据分页查询错误");
      return ResponseVO.fail(e.toString());
    }
  }

  @GetMapping(value = "/weatherStationStatusData/{startTime}/{endTime}/{no}/{jgTime}")
  public ResponseVO findByTimeBetweenAndNoAndTimeStep(@PathVariable("startTime") Long startTime,
                                               @PathVariable("endTime") Long endTime,
                                               @PathVariable("no") Integer no,
                                                      @PathVariable("jgTime")Long jgTime,
                                                      String sortOrder){
    Map<String,Object> map = new HashMap<>();
    try{
      map =  weatherStationStatusDataService.findByTimeBetweenAndNoAndTimeStep(new Date(startTime),new Date(endTime),no,jgTime,sortOrder);
      return ResponseVO.success(map);
    }catch(Exception e){
      e.printStackTrace();
      log.error("气象数据分页查询错误");
      return ResponseVO.fail(e.toString());
    }
  }

  /**
   * 统计查询 气象站数据
   * @param startTime 开始时间
   * @param endTime 结束时间
   * @return
   */
  @GetMapping(value = "/weatherData/{startTime}/{endTime}/{no}/{dateType}/{dataType}")
  public ResponseVO findWeatherData(@PathVariable("startTime") Long startTime,
                                               @PathVariable("endTime") Long endTime,
                                               @PathVariable("no") Integer no,
                                               @PathVariable("dateType") String dateType,
                                                @PathVariable("dataType") String dataType){

    try{
      List<Map<String, Object>> weatherData = weatherStationStatusDataService.findWeatherData(startTime, endTime, no, dateType,dataType);
      return ResponseVO.success(weatherData);
    }catch(Exception e){
      e.printStackTrace();
      log.error("气象数据分页查询错误");
      return ResponseVO.fail(e.toString());
    }
  }

  /**
   * 气象站数据表格导出
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @return
   */
  @GetMapping(value = "export/weatherStationStatusData/{startTime}/{endTime}/{no}/{jgTime}")
  public ResponseVO export(@PathVariable("startTime") Long startTime,
                           @PathVariable("endTime") Long endTime,
                           @PathVariable("no") Integer no,
                           @PathVariable("jgTime")Long jgTime,
                           String sortOrder,
                           HttpServletResponse response

  ) {
    BufferedOutputStream bos = null;
    try {
      Map<String,Object> map =  weatherStationStatusDataService.findByTimeBetweenAndNoAndTimeStep(new Date(startTime),new Date(endTime),no,jgTime,sortOrder);
      SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      List<WeatherStationStatusData> weatherStationStatusDataList = (List<WeatherStationStatusData>)map.get("content");
      StringBuilder templateContent = new StringBuilder();
      response.setCharacterEncoding("UTF-8");
      String header = "\"接收时间\"," + "\"总辐射\"," + "\"直接辐射\"," + "\"散射辐射\"," + "\"斜面辐射\"," + "\"环境温度\"," + "\"气压\"," + "\"湿度\"," + "\"背板温度\"," + "\"风速\"," + "\"风向\"," + "\"日照小时数\"," + "\"总辐射日累积\"," + "\"直接辐射日累积\"," + "\"散射辐射日累积\"," + "\"斜面辐射日累积\","+"\r\n";

      StringBuilder content = new StringBuilder();
      for (WeatherStationStatusData w : weatherStationStatusDataList) {
        content.append(sdf1.format(w.getTime())+","+w.getGlobalR()+","+w.getDirectR()+","+w.getDiffuseR()+","+w.getObliqueR()+","+w.getAirT()+","+w.getP()+","+w.getRh()+","+w.getCellT()+","+w.getWs()+","+w.getWd()+","+w.getHourDA()+","+w.getGlobalRDA()+","+w.getDirectRDA()+","+w.getDiffuseRDA()+","+w.getObliqueRDA()+"\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) + "气象站数据导出文件" + ".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();
  }


}
