package com.jiayue.ipfcst.console.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import com.jiayue.ipfcst.common.data.abst.equipmentinfo.AbstractEquipmentInfo;
import com.jiayue.ipfcst.common.data.constant.enums.ElectricFieldStatrsEnum;
import com.jiayue.ipfcst.common.data.constant.enums.FileTypeEnum;
import com.jiayue.ipfcst.common.data.entity.*;
import com.jiayue.ipfcst.console.service.*;
import com.jiayue.ipfcst.dataexchange.service.ProtocolGatherDataPointService;
import com.jiayue.ipfcst.dataexchange.service.ProtocolSenderDataPointService;
import com.jiayue.ipfcst.dataexchange.service.TunnelInfoService;
import com.jiayue.ipfcst.dataexchange.service.equipmentstatusdata.EquipmentInfoService;
import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 通信设备控制层
 *
 * @author zy
 * @version 3.0
 */
@RestController
@RequestMapping("communicationEquipment")
@Slf4j
public class CommunicationEquipmentController {
  @Autowired CommunicationEquipmentService communicationEquipmentService;
  @Autowired InverterInfoService inverterInfoService;
  @Autowired WindTurbineInfoService windTurbineInfoService;
  @Autowired WeatherStationInfoService weatherStationInfoService;
  @Autowired WindTowerInfoService windTowerInfoService;
  @Autowired UploadObjectService uploadObjectService;
  @Autowired UploadFileChannelService uploadFileChannelService;
  @Autowired ProtocolGatherDataPointService protocolGatherDataPointService;
  @Autowired ProtocolSenderDataPointService protocolSenderDataPointService;
  @Autowired ElectricFieldService electricFieldService;
  @Autowired EquipmentInfoService equipmentInfoService;
  @Autowired TunnelInfoService tunnelInfoService;
  /**
   * 查询所有通信设备
   */
  @GetMapping()
  public ResponseVO get(){
    try {
      return ResponseVO.success(communicationEquipmentService.get());
    }catch (Exception e){
      log.error("查询通信设备异常" + e);
      return ResponseVO.error(e);
    }
  }
  /**
   * 添加通信设备
   */
  @PostMapping()
  public ResponseVO save(@RequestBody CommunicationEquipment communicationEquipment){
    try {
      return ResponseVO.success(communicationEquipmentService.save(communicationEquipment));
    }catch (Exception e){
      log.error("保存通信设备异常" + e);
      return ResponseVO.error(e);
    }
  }
  @PutMapping()
  public ResponseVO putCommEq(@RequestBody CommunicationEquipment communicationEquipment){
    try {
      return ResponseVO.success(communicationEquipmentService.save(communicationEquipment));
    }catch (Exception e){
      log.error("修改通信设备异常" + e);
      return ResponseVO.error(e);
    }
  }
  @DeleteMapping("/{id}")
  public ResponseVO deleteCommEq(@PathVariable Integer id){
    try {
      communicationEquipmentService.delete(id);
      return ResponseVO.success(1);
    }catch (Exception e){
      log.error("删除通信设备异常" + e);
      return ResponseVO.error(e);
    }
  }

  @RequestMapping("/export")
  public void export(HttpServletResponse response) {
    try {
      ElectricField electricField = electricFieldService.get();
      ExcelWriter writer = ExcelUtil.getWriter();
      if((electricField.getStationStatusEnum()).equals(ElectricFieldStatrsEnum.E1)){
        writer.renameSheet(0,"逆变器");
        List<InverterInfo> inverterInfos =  inverterInfoService.getAll();
        List<String> row2 = CollUtil.newArrayList("逆变器名称", "是否组串式", "逆变器效率（%）", "额定功率（KW）", "箱式变压器", "集电线路", "光伏组件型号", "光伏组件数量（个）", "逆变器是否样板机");
        List<List<String>> rows1 = CollUtil.newArrayList();
        rows1.add(row2);
        for(int i=0;i<inverterInfos.size();i++){
          List<String> row = CollUtil.newArrayList();
          row.add(inverterInfos.get(i).getName());
          row.add( communicationEquipmentService.formateBoolen((inverterInfos.get(i).getGroupSeries()).toString()));
          row.add((inverterInfos.get(i).getEfficiency()).toString());
          row.add((inverterInfos.get(i).getCapacity()).toString());
          row.add(inverterInfos.get(i).getBox());
          row.add(inverterInfos.get(i).getCollectorCircuit());
          row.add(inverterInfos.get(i).getBatteryModel());
          row.add((inverterInfos.get(i).getBatteryNumber()).toString());
          row.add(communicationEquipmentService.formateBoolen((inverterInfos.get(i).getSample()).toString()));
          rows1.add(row);
          row = null;
        }
        writer.write(rows1,true);
        //气象站
        ExcelWriter qxzrSheet = writer.setSheet("气象站");
        List<WeatherStationInfo> weatherStationInfos = weatherStationInfoService.getAll();
        List<String> qxzRow = CollUtil.newArrayList("气象站名称", "生产商", "型号", "安装时间", "是否上报", "绑定通道", "入库间隔（/s）");
        List<List<String>> qxzRows = CollUtil.newArrayList();
        qxzRows.add(qxzRow);
        for(int i=0;i<weatherStationInfos.size();i++){
          List<String> row = CollUtil.newArrayList();
          row.add(weatherStationInfos.get(i).getName());
          row.add(weatherStationInfos.get(i).getManufacturer());
          row.add(weatherStationInfos.get(i).getModelNumber());
          row.add((weatherStationInfos.get(i).getInstallationTime()).toString());
          row.add(communicationEquipmentService.formateBoolen((weatherStationInfos.get(i).getReport()).toString()));
          row.add(weatherStationInfos.get(i).getBindTunnel());
          row.add((weatherStationInfos.get(i).getInterval()).toString());
          qxzRows.add(row);
          row = null;
        }
        qxzrSheet.write(qxzRows,true);
      }else{
        writer.renameSheet(0,"风机");
        List<WindTurbineInfo> windTurbineInfos = windTurbineInfoService.getAll();
        List<String> row1 = CollUtil.newArrayList("风机名称", "生产商", "型号", "安装时间", "是否上报", "是否样板机", "风机等级", "设计空气密度", "切入速度", "额定风速", "切出速度", "生存风速", "叶轮直径（m）", "最大转速（m）", "最小转速（m）", "额定转速（m）", "轮毂高度（m）", "并网日期（m）", "使用寿命", "最大功率", "风机是否样板机");
        List<List<String>> rows = CollUtil.newArrayList();
        rows.add(row1);
        for(int i=0;i<windTurbineInfos.size();i++){
          List<String> row = CollUtil.newArrayList();
          row.add(windTurbineInfos.get(i).getName());
          row.add(windTurbineInfos.get(i).getManufacturer());
          row.add(windTurbineInfos.get(i).getModelNumber());
          row.add((windTurbineInfos.get(i).getInstallationTime()).toString());
          row.add(communicationEquipmentService.formateBoolen((windTurbineInfos.get(i).getReport()).toString()));
          row.add( communicationEquipmentService.formateBoolen((windTurbineInfos.get(i).getSample()).toString()));
          row.add((windTurbineInfos.get(i).getGrade()).toString());
          row.add((windTurbineInfos.get(i).getAirDensity()).toString());
          row.add((windTurbineInfos.get(i).getCutInSpeed()).toString());
          row.add((windTurbineInfos.get(i).getRatedWindSpeed()).toString());
          row.add((windTurbineInfos.get(i).getCutOutSpeed()).toString());
          row.add((windTurbineInfos.get(i).getLiveWindSpeed()).toString());
          row.add((windTurbineInfos.get(i).getWindWheelDiameter()).toString());
          row.add((windTurbineInfos.get(i).getWindWheelMaxSpeed()).toString());
          row.add((windTurbineInfos.get(i).getWindWheelMinSpeed()).toString());
          row.add((windTurbineInfos.get(i).getWindWheelRatedSpeed()).toString());
          row.add((windTurbineInfos.get(i).getHubHeight()).toString());
          row.add((windTurbineInfos.get(i).getParallelInDate()).toString());
          row.add((windTurbineInfos.get(i).getLifeLength()).toString());
          row.add((windTurbineInfos.get(i).getMaxPower()).toString());
          row.add(communicationEquipmentService.formateBoolen((windTurbineInfos.get(i).getSample()).toString()));
          rows.add(row);
          row = null;
        }
        writer.write(rows,true);
        //测风塔
        ExcelWriter cftSheet = writer.setSheet("测风塔");
        List<WindTowerInfo> windTowerInfos = windTowerInfoService.getAll();
        List<String> cftRow = CollUtil.newArrayList("测风塔名称", "生产商", "型号", "安装时间", "是否上报", "是否样板机", "绑定通道", "入库间隔（/s）");
        List<List<String>> cftRows = CollUtil.newArrayList();
        cftRows.add(cftRow);
        for(int i=0;i<windTowerInfos.size();i++){
          List<String> row = CollUtil.newArrayList();
          row.add(windTowerInfos.get(i).getName());
          row.add(windTowerInfos.get(i).getManufacturer());
          row.add(windTowerInfos.get(i).getModelNumber());
          row.add((windTowerInfos.get(i).getInstallationTime()).toString());
          row.add(communicationEquipmentService.formateBoolen((windTowerInfos.get(i).getReport()).toString()));
          row.add( communicationEquipmentService.formateBoolen((windTowerInfos.get(i).getSample()).toString()));
          row.add(windTowerInfos.get(i).getBindTunnel());
          row.add((windTowerInfos.get(i).getInterval()).toString());
          cftRows.add(row);
          row = null;
        }
        cftSheet.write(cftRows, true);
      }


      //上报对象
      ExcelWriter objectSheet = writer.setSheet("上报对象");
      List<UploadObject> uploadObjects = uploadObjectService.get();
      List<String> objectRow = CollUtil.newArrayList("名称", "编号", "上报文件类型", "上报文件字符集", "上报协议", "上报嘉越D5000");
      List<List<String>> objectRows = CollUtil.newArrayList();
      objectRows.add(objectRow);

      for(int i = 0;i < uploadObjects.size(); i++){
        List<String> row = CollUtil.newArrayList();
        row.add(uploadObjects.get(i).getUploadObjectName());
        row.add(uploadObjects.get(i).getObjectNo());
        String str = uploadObjects.get(i).getUploadFileType();
        if(str.contains(",")){
          String[] fileType = str.split(",");
          String str1 = "";
          for(int k = 0 ;k< fileType.length; k++){
            str1 +=  FileTypeEnum.valueOf(FileTypeEnum.class, fileType[k]).getMessage();
            if(k != fileType.length -1){
              str1 += ",";
            }
          }
          row.add(str1);
        }else row.add(FileTypeEnum.valueOf(FileTypeEnum.class, uploadObjects.get(i).getUploadFileType()).getMessage());
        row.add(uploadObjects.get(i).getUploadFileCharSetEnum().getMessage());
        row.add(uploadObjects.get(i).getUploadProtocolEnum().getMessage());
        row.add(communicationEquipmentService.formateBoolen(uploadObjects.get(i).getUploadD5000()));
        objectRows.add(row);
        row = null;
      }
      objectSheet.write(objectRows,true);
      //上报通道
      ExcelWriter objectTunnelSheet = writer.setSheet("上报通道");
      List<UploadFileChannel> uploadFileChannels = uploadFileChannelService.get();
      List<String> objectTunnelRow = CollUtil.newArrayList("上报对象名称", "通道名称", "通道使用状态", "本地IP", "本地端口", "远端IP", "远端端口", "上报文件名称长度", "上报文件单次传输字节", "用户名", "密码", "服务端路径", "SFTP连接方式", "SFTP密钥路径", "SFTP密钥密码", "FTP模式");
      List<List<String>> objectTunnelRows = CollUtil.newArrayList();
      objectTunnelRows.add(objectTunnelRow);
      for(int i = 0; i<uploadFileChannels.size(); i++){
        List<String> row = CollUtil.newArrayList();
        String str = "";
        a:for(int j = 0 ;j <uploadObjects.size(); j++){
          if(uploadFileChannels.get(i).getUploadObjectId() == uploadObjects.get(j).getId()){
            str = uploadObjects.get(j).getUploadObjectName();
            break a;
          }
        }
        row.add(str);
        row.add(uploadFileChannels.get(i).getChannelName());
        row.add(uploadFileChannels.get(i).getChannelStatusEnum().getMessage());
        row.add(uploadFileChannels.get(i).getLocalIp());
        row.add(uploadFileChannels.get(i).getLocalPort());
        row.add(uploadFileChannels.get(i).getRemoteIp());
        row.add(uploadFileChannels.get(i).getRemotePort());
        if(uploadFileChannels.get(i).getUploadFileNameLengthEnum() != null){
          row.add(uploadFileChannels.get(i).getUploadFileNameLengthEnum().getMessage());
          row.add(uploadFileChannels.get(i).getUploadFileSingleByteEnum().getMessage());
        }else row.add("");
        row.add(uploadFileChannels.get(i).getUploadUserName());
        row.add(uploadFileChannels.get(i).getUploadPassword());
        row.add(uploadFileChannels.get(i).getPathService());
        if(uploadFileChannels.get(i).getSftpConnectModeEnum() != null){
          row.add(uploadFileChannels.get(i).getSftpConnectModeEnum().getMessage());
        }else row.add("");
        row.add(uploadFileChannels.get(i).getKeyFilePath());
        row.add(uploadFileChannels.get(i).getPassPhrase());
        row.add(uploadFileChannels.get(i).getChannelRemarks());
        if(uploadFileChannels.get(i).getFtpPassiveModeEnum() != null){
          row.add(uploadFileChannels.get(i).getFtpPassiveModeEnum().getMessage());
        }else row.add("");
        objectTunnelRows.add(row);
        row = null;
      }
      objectTunnelSheet.write(objectTunnelRows,true);
      //点表
      List<AbstractEquipmentInfo> infos = equipmentInfoService.getAllEquipmentInfo();
      List<BaseTunnelInfo> tunnelInfos = tunnelInfoService.getAllTunnel();
      ExcelWriter gatherPointSheet = writer.setSheet("采集点表");
      List<ProtocolGatherDataPoint> protocolGatherDataPoints = protocolGatherDataPointService.getAll();
      List<String> gatherPointRow = CollUtil.newArrayList("设备名称", "设备属性", "数据源", "倍率", "使用通道", "通道点位", "通道数据类型", "数据生成公式", "是否考核", "最大变化值", "最大值", "最小值", "最长持续时间（min）");
      List<List<String>> gatherPointRows = CollUtil.newArrayList();
      gatherPointRows.add(gatherPointRow);
      for(int i = 0; i<protocolGatherDataPoints.size();i++){
        List<String> row = CollUtil.newArrayList();
        Integer code = protocolGatherDataPoints.get(i).getEquipmentAttribute().getEquipmentType().getCode();
        if(code == 0){
          row.add(electricField.getName());
        }else{
          a:for (int j = 0; j<infos.size();j++){
            if(protocolGatherDataPoints.get(i).getEquipmentId() == infos.get(j).getId() && protocolGatherDataPoints.get(i).getEquipmentAttribute().getEquipmentType().getCode() == infos.get(j).getEquipmentType().getCode()){
              row.add(infos.get(j).getName());
              break a;
            }
          }
        }
        row.add(protocolGatherDataPoints.get(i).getEquipmentAttribute().getExplanation());
        row.add(protocolGatherDataPoints.get(i).getDataSource().getMessage());
        row.add((protocolGatherDataPoints.get(i).getMagnification()).toString());
        if((protocolGatherDataPoints.get(i).getDataSource().getMessage()).equals("外部接入")){
          for(int j = 0; j<tunnelInfos.size();j++){
            if((protocolGatherDataPoints.get(i).getTunnelId()).equals(tunnelInfos.get(j).getId())){
              row.add(tunnelInfos.get(j).getTunnelName());
            }
          }
          row.add((protocolGatherDataPoints.get(i).getProtocolPointNo()).toString());
          row.add(protocolGatherDataPoints.get(i).getProtocolPointType().getDescribe());
          row.add("");
        }else{
          for (int j = 0 ; j< 3 ;j++){
            row.add("");
          }
          row.add(protocolGatherDataPoints.get(i).getGenerationRegulation());
        }
        String str = (protocolGatherDataPoints.get(i).getNeedAudit()).toString();
        row.add(communicationEquipmentService.formateBoolen(str));
        if(protocolGatherDataPoints.get(i).getNeedAudit()){
          row.add((protocolGatherDataPoints.get(i).getMaxChangeValue()).toString());
          row.add((protocolGatherDataPoints.get(i).getMaxValue()).toString());
          row.add((protocolGatherDataPoints.get(i).getMinValue()).toString());
          row.add((protocolGatherDataPoints.get(i).getMaxDuration()).toString());
        }else {
          for (int j = 0 ; j< 4 ;j++){
            row.add("");
          }
        }
        gatherPointRows.add(row);
        row = null;
      }
      gatherPointSheet.write(gatherPointRows,true);

      ExcelWriter senderPointSheet = writer.setSheet("转发点表");
      List<ProtocolSenderDataPoint> protocolSenderDataPoints = protocolSenderDataPointService.get();
      List<String> senderPointRow = CollUtil.newArrayList("数据源", "倍率", "通道名", "通道点位", "通道数据类型", "设备名", "设备类型", "设备属性", "预测数据属性", "预测天数（天/时）", "预测数据的点位");
      List<List<String>> senderPointRows = CollUtil.newArrayList();
      senderPointRows.add(senderPointRow);
      for(int i = 0; i<protocolSenderDataPoints.size();i++){
        List<String> row = CollUtil.newArrayList();
        row.add(protocolSenderDataPoints.get(i).getDataSource().getMessage());
        row.add((protocolSenderDataPoints.get(i).getMagnification()).toString());
        for(int j = 0; j<tunnelInfos.size();j++){
          if((protocolSenderDataPoints.get(i).getTunnelId()).equals(tunnelInfos.get(j).getId())){
            row.add(tunnelInfos.get(j).getTunnelName());
          }
        }
        row.add((protocolSenderDataPoints.get(i).getProtocolPointNo()).toString());
        row.add(protocolSenderDataPoints.get(i).getProtocolPointType().getDescribe());
        if(protocolSenderDataPoints.get(i).getGatherPoint() == null){
          for (int j = 0 ; j< 3 ;j++){
            row.add("");
          }
          row.add(protocolSenderDataPoints.get(i).getForecastForSendAttribute().getForecastType().getDescribe());
          row.add((protocolSenderDataPoints.get(i).getForecastForSendAttribute().getForecastNode()).toString());
          row.add((protocolSenderDataPoints.get(i).getForecastForSendAttribute().getPointNumber()).toString());
        }else{
          ProtocolGatherDataPoint protocolGatherDataPoint = new ProtocolGatherDataPoint();
          for(int k= 0;k< protocolGatherDataPoints.size();k++){
            if((protocolSenderDataPoints.get(i).getGatherPoint()).equals(protocolGatherDataPoints.get(k).getId())){
              Integer code = protocolGatherDataPoints.get(k).getEquipmentAttribute().getEquipmentType().getCode();
              if(code == 0){
                row.add(electricField.getName());
              }else{
                a:for (int j = 0; j<infos.size();j++){
                  if(protocolGatherDataPoints.get(k).getEquipmentId() == infos.get(j).getId() && protocolGatherDataPoints.get(k).getEquipmentAttribute().getEquipmentType().getCode() == infos.get(j).getEquipmentType().getCode()){
                    row.add(infos.get(j).getName());
                    break a;
                  }
                }
              }
              row.add(protocolGatherDataPoints.get(k).getEquipmentAttribute().getEquipmentType().getMessage());
              row.add(protocolGatherDataPoints.get(k).getEquipmentAttribute().getExplanation());
              break ;
            }
          }
          for (int j = 0 ; j< 3 ;j++){
            row.add("");
          }
        }
        senderPointRows.add(row);
        row = null;
      }
      senderPointSheet.write(senderPointRows,true);

      ExcelWriter commEqSheet = writer.setSheet("通信设备");
      List<CommunicationEquipment> commEqList = communicationEquipmentService.get();
      List<String> commEqRow = CollUtil.newArrayList("通信设备", "网卡名称", "网卡Ip地址", "子网掩码", "网关", "端口","功率预测系统", "系统网卡名称", "系统网卡Ip地址", "系统子网掩码", "系统网关", "系统端口");
      List<List<String>> commEqRows = CollUtil.newArrayList();
      commEqRows.add(commEqRow);
      for(int i=0;i<commEqList.size();i++){
        List<String> row = CollUtil.newArrayList();
        row.add(commEqList.get(i).getName());
        row.add(commEqList.get(i).getNetCardName());
        row.add(commEqList.get(i).getNetCardIp());
        row.add(commEqList.get(i).getNetmask());
        row.add(commEqList.get(i).getGateway());
        row.add(commEqList.get(i).getPort());
        row.add(commEqList.get(i).getSystemName());
        row.add(commEqList.get(i).getSystemNetCardName());
        row.add(commEqList.get(i).getSystemNetCardIp());
        row.add(commEqList.get(i).getSystemNetmask());
        row.add(commEqList.get(i).getSystemGateway());
        row.add(commEqList.get(i).getSystemPort());
        commEqRows.add(row);
        row = null;
      }
      commEqSheet.write(commEqRows,true);
      String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
      String fileName = "信息数据" + now + ".xls";
      response.setContentType("application/x-msdownload;charset=utf-8");
      response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
      ServletOutputStream out= null;
      out = response.getOutputStream();
      writer.flush(out, true);
      // 关闭writer，释放内存
      writer.close();
      //此处记得关闭输出Servlet流
      IoUtil.close(out);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}
