package com.jiayue.ipfcst.controller;

import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import com.jiayue.ipfcst.service.EquipmentAttributeService;
import com.jiayue.ipfcst.service.WindTowerStatusDataService;
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 WindTowerStatusDataController {

  private final WindTowerStatusDataService windTowerStatusDataService;
  private final EquipmentAttributeService equipmentAttributeService;

  @Autowired
  public WindTowerStatusDataController(WindTowerStatusDataService windTowerStatusDataService, EquipmentAttributeService equipmentAttributeService) {
    this.windTowerStatusDataService = windTowerStatusDataService;
    this.equipmentAttributeService = equipmentAttributeService;
  }

  /**
   * 分页查询 测风塔数据
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @param page      页码
   * @param size      条数
   * @param sortOrder 排序
   * @return
   */
  @GetMapping(value = "/windTowerStatusData/{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 = windTowerStatusDataService.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());
    }
  }

  /**
   * 时间查询测风塔数据
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @param no        设备编号
   * @return
   */
  @GetMapping(value = "/windTowerStatusData/{startTime}/{endTime}/{no}")
  public ResponseVO queryCharts(@PathVariable("startTime") Long startTime,
                                @PathVariable("endTime") Long endTime,
                                @PathVariable("no") Integer no) {
    Map<String, Object> map = new HashMap<>();
    try {
      map = windTowerStatusDataService.queryCharts(startTime, endTime, no);
      return ResponseVO.success(map);
    } catch (Exception e) {
      e.printStackTrace();
      log.error("测风塔数据查询错误");
      return ResponseVO.fail(e.toString());
    }

  }

  @GetMapping(value = "/windTowerStatusData/{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;
    try {
      map = windTowerStatusDataService.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   截止时间
   * @param dateType  数据类型
   * @param dateType  统计频率
   * @return 数据集合
   */
  @GetMapping(value = "queryAnemometerSpeed/{startTime}/{endTime}/{no}/{dateType}/{dataType}")
  public ResponseVO queryAnemometerSpeed(@PathVariable Long startTime,
                                         @PathVariable Long endTime,
                                         @PathVariable Integer no,
                                         @PathVariable String dateType,
                                         @PathVariable String dataType
  ) {

    List<Map<String, Object>> list = windTowerStatusDataService.queryAnemometerSpeed(startTime, endTime, dateType, no, dataType);

    return ResponseVO.success(list);
  }

  /**
   * 测风塔数据表格导出
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @return
   */
  @GetMapping(value = "export/windTowerStatusData/{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 = windTowerStatusDataService.findByTimeBetweenAndNoAndTimeStep(new Date(startTime), new Date(endTime), no, jgTime, sortOrder);
      Map<String, String> eqData = equipmentAttributeService.findByEquipmentTypeforWINDTOWER();
      List<String> newThList = (List<String>) map.get("tableHead");
      List<Map<String, Object>> dataResult = (List<Map<String, Object>>) map.get("content");
      StringBuilder templateContent = new StringBuilder();
      response.setCharacterEncoding("UTF-8");
      String header = "\"接入时间\"," + "\"设备编号\",";
      for (String s : newThList) {
        header += eqData.get(s) + ",";
      }

      header += "\r\n";
      StringBuilder content = new StringBuilder();
      for (Map<String, Object> dataMap : dataResult) {
        content.append(dataMap.get("time") + ",");
        content.append(dataMap.get("equipmentNo") + ",");
        for (String s : newThList) {
          content.append(dataMap.get(s) + ",");
        }
        content.append("\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();
  }


}
