package com.jiayue.ipfcst.console.service;

import cn.hutool.core.util.RuntimeUtil;
import com.jiayue.ipfcst.common.data.constant.enums.UploadProtocolEnum;
import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
import com.jiayue.ipfcst.common.data.entity.UploadObject;
import com.jiayue.ipfcst.common.data.entity.gathertunnelinfo.Gather104TcpTunnelInfo;
import com.jiayue.ipfcst.common.data.entity.gathertunnelinfo.GatherCdtRtuTunnelInfo;
import com.jiayue.ipfcst.common.data.entity.gathertunnelinfo.GatherModbusRtuTunnelInfo;
import com.jiayue.ipfcst.common.data.entity.gathertunnelinfo.GatherModbusTcpTunnelInfo;
import com.jiayue.ipfcst.common.data.entity.sendertunnelinfo.Sender104TcpTunnelInfo;
import com.jiayue.ipfcst.common.data.entity.sendertunnelinfo.SenderModbusTcpTunnelInfo;
//import com.jiayue.ipfcst.common.data.repository.InspectionReportRepository;
import com.jiayue.ipfcst.common.data.repository.UploadFileChannelRepository;
import com.jiayue.ipfcst.common.data.repository.UploadObjectRepository;
import com.jiayue.ipfcst.dataexchange.repository.gathertunnelrepository.Gather104TcpTunnelRepository;
import com.jiayue.ipfcst.dataexchange.repository.gathertunnelrepository.GatherCdtRtuTunnelRepository;
import com.jiayue.ipfcst.dataexchange.repository.gathertunnelrepository.GatherModbusRtuTunnelRepository;
import com.jiayue.ipfcst.dataexchange.repository.gathertunnelrepository.GatherModbusTcpTunnelRepository;
import com.jiayue.ipfcst.dataexchange.repository.sendertunnelrepository.Sender104TcpTunnelRepository;
import com.jiayue.ipfcst.dataexchange.repository.sendertunnelrepository.SenderCdtRtuTunnelRepository;
import com.jiayue.ipfcst.dataexchange.repository.sendertunnelrepository.SenderModbusRtuTunnelRepository;
import com.jiayue.ipfcst.dataexchange.repository.sendertunnelrepository.SenderModbusTcpTunnelRepository;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.sound.sampled.Port;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class InspectionReportService {
  //  @Autowired
//  InspectionReportRepository inspectionReportRepository;
  @Autowired
  UploadFileChannelRepository uploadFileChannelRepository;
  @Autowired
  UploadObjectRepository uploadObjectRepository;
  @Autowired
  private Gather104TcpTunnelRepository gather104TcpTunnelRepository;
  @Autowired
  private Sender104TcpTunnelRepository sender104TcpTunnelRepository;
  @Autowired
  private GatherModbusTcpTunnelRepository gatherModbusTcpTunnelRepository;
  @Autowired
  private SenderModbusTcpTunnelRepository senderModbusTcpTunnelRepository;
  @Autowired
  private GatherModbusRtuTunnelRepository gatherModbusRtuTunnelRepository;
  @Autowired
  private SenderModbusRtuTunnelRepository senderModbusRtuTunnelRepository;
  @Autowired
  private GatherCdtRtuTunnelRepository gatherCdtRtuTunnelRepository;
  @Autowired
  private SenderCdtRtuTunnelRepository senderCdtRtuTunnelRepository;



  public Map<String, List<String>> check() {
    Map<String, List<String>> map = new HashMap<>();
    List<String> listForIp = new ArrayList<>();
    List<String> listForPing = new ArrayList<>();
    List<String> listForNetstat = new ArrayList<>();

    List<UploadObject> uploadObjects = uploadObjectRepository.findAll();
    //取出所有上报通道，都ping一边
    List<UploadFileChannel> uploadFileChannels = uploadFileChannelRepository.findAll();

    List<String> listIfconfig = RuntimeUtil.execForLines("ipconfig");
    listForIp.add("查看本机网卡信息 ifconfig：");
    listForIp.addAll(listIfconfig);

    for (UploadObject uploadObject : uploadObjects) {
      List<UploadFileChannel> filterUploadFileChannels = uploadFileChannels.stream().filter(s -> s.getUploadObjectId() == uploadObject.getId()).collect(Collectors.toList());
      if (uploadObject.getUploadProtocolEnum().getCode().equals("102s") || uploadObject.getUploadProtocolEnum().getCode().equals("102m_sd_client") || uploadObject.getUploadProtocolEnum().getCode().equals("102m_sd_server") || uploadObject.getUploadProtocolEnum().getCode().equals("zj102_client")) {
        for (UploadFileChannel uploadFileChannel : filterUploadFileChannels) {
          listForPing.add("---------------------------------------------------------------------");
          List<String> listPing = RuntimeUtil.execForLines("ping " + uploadFileChannel.getRemoteIp());
          listForPing.add("上报通道[" + uploadFileChannel.getChannelName() + "]ping远端ip：ping " + uploadFileChannel.getRemoteIp());
          listForPing.addAll(listPing);
          if (uploadFileChannel.getLocalPort() != null) {
            listForPing.add("---------------------------------------------------------------------");
            List<String> listNetstat = RuntimeUtil.execForLines("netstat anlp | grep " + uploadFileChannel.getLocalPort());
            listForNetstat.add("上报通道[" + uploadFileChannel.getChannelName() + "] " + "netstat anlp | grep " + uploadFileChannel.getLocalPort());
            listForNetstat.addAll(listNetstat);
          }
        }
      } else {
        for (UploadFileChannel uploadFileChannel : filterUploadFileChannels) {
          listForPing.add("---------------------------------------------------------------------");
          List<String> listPing = RuntimeUtil.execForLines("ping " + uploadFileChannel.getRemoteIp());
          listForPing.add("上报通道[" + uploadFileChannel.getChannelName() + "]ping远端ip：ping " + uploadFileChannel.getRemoteIp());
          listForPing.addAll(listPing);
        }
      }
    }

    List<Gather104TcpTunnelInfo> gather104TcpTunnelInfos = gather104TcpTunnelRepository.findAll();
    for (Gather104TcpTunnelInfo gather104TcpTunnelInfo : gather104TcpTunnelInfos) {
      listForPing.add("---------------------------------------------------------------------");
      List<String> listPing = RuntimeUtil.execForLines("ping " + gather104TcpTunnelInfo.getRemoteIp());
      listForPing.add("数据接入通道[" + gather104TcpTunnelInfo.getTunnelName() + "]ping远端ip：" +"ping " + gather104TcpTunnelInfo.getRemoteIp());
      listForPing.addAll(listPing);
      if (gather104TcpTunnelInfo.getRemoteSpareIp()!=null){
        listForPing.add("---------------------------------------------------------------------");
        List<String> listPingBy = RuntimeUtil.execForLines("ping " + gather104TcpTunnelInfo.getRemoteIp());
        listForPing.add("数据接入通道[" + gather104TcpTunnelInfo.getTunnelName() + "]ping远端备用ip：" +"ping " + gather104TcpTunnelInfo.getRemoteIp());
        listForPing.addAll(listPingBy);
      }
    }

    List<GatherModbusTcpTunnelInfo> gatherModbusTcpTunnelInfos = gatherModbusTcpTunnelRepository.findAll();
    for (GatherModbusTcpTunnelInfo gatherModbusTcpTunnelInfo : gatherModbusTcpTunnelInfos) {
      listForPing.add("---------------------------------------------------------------------");
      List<String> listPing = RuntimeUtil.execForLines("ping " + gatherModbusTcpTunnelInfo.getRemoteIp());
      listForPing.add("数据接入通道[" + gatherModbusTcpTunnelInfo.getTunnelName() + "]ping远端ip：" + "ping " + gatherModbusTcpTunnelInfo.getRemoteIp());
      listForPing.addAll(listPing);
      if (gatherModbusTcpTunnelInfo.getRemoteSpareIp()!=null){
        listForPing.add("---------------------------------------------------------------------");
        List<String> listPingBy = RuntimeUtil.execForLines("ping " + gatherModbusTcpTunnelInfo.getRemoteIp());
        listForPing.add("数据接入通道[" + gatherModbusTcpTunnelInfo.getTunnelName() + "]ping远端备用ip：" +"ping " + gatherModbusTcpTunnelInfo.getRemoteIp());
        listForPing.addAll(listPingBy);
      }
    }

    List<Sender104TcpTunnelInfo> sender104TcpTunnelInfos = sender104TcpTunnelRepository.findAll();
    for (Sender104TcpTunnelInfo sender104TcpTunnelInfo : sender104TcpTunnelInfos) {
      if (sender104TcpTunnelInfo.getSelfPort() != null) {
        listForNetstat.add("---------------------------------------------------------------------");
        List<String> listNetstat = RuntimeUtil.execForLines("netstat anlp | grep " + sender104TcpTunnelInfo.getSelfPort());
        listForNetstat.add("数据上送通道[" + sender104TcpTunnelInfo.getSelfPort() + "] " + "etstat anlp | grep " + sender104TcpTunnelInfo.getSelfPort());
        listForNetstat.addAll(listNetstat);
      }
    }

    List<SenderModbusTcpTunnelInfo> senderModbusTcpTunnelInfos = senderModbusTcpTunnelRepository.findAll();
    for (SenderModbusTcpTunnelInfo senderModbusTcpTunnelInfo : senderModbusTcpTunnelInfos) {
      if (senderModbusTcpTunnelInfo.getSelfPort() != null) {
        listForNetstat.add("---------------------------------------------------------------------");
        List<String> listNetstat = RuntimeUtil.execForLines("netstat anlp | grep " + senderModbusTcpTunnelInfo.getSelfPort());
        listForNetstat.add("数据上送通道[" + senderModbusTcpTunnelInfo.getSelfPort() + "] " + "etstat anlp | grep " + senderModbusTcpTunnelInfo.getSelfPort());
        listForNetstat.addAll(listNetstat);
      }
    }
    map.put("ip", listForIp);
    map.put("ping", listForPing);
    map.put("nestat", listForNetstat);
    return map;
  }

  public List<String> checkIp() {
    List<String> listForIp = new ArrayList<>();
    List<String> listIfconfig = RuntimeUtil.execForLines("ifconfig");
    listForIp.add("本机网卡信息 ifconfig：");
    listForIp.addAll(listIfconfig);
    return listForIp;
  }

  public List<String> checkPing(String rmId) {
    List<String> listForPing = new ArrayList<>();
    List<String> listPing = RuntimeUtil.execForLines("ping " + rmId +" -c4");
    listForPing.add("ping "+rmId +" -c4：");
    listForPing.addAll(listPing);
    return listForPing;
  }


  public List<String> checkNetstat(String lcId) {
    List<String> listForNetstat = new ArrayList<>();
    List<String> listNetstat = RuntimeUtil.execForLines("netstat -anp | grep " + lcId);
    listForNetstat.add("netstat -anp | grep " + lcId+"：");
    listForNetstat.addAll(listNetstat);
    return listForNetstat;
  }

  public List<String> checkLsof(String lcId) {
    List<String> listForNetstat = new ArrayList<>();
    List<String> listNetstat = RuntimeUtil.execForLines("lsof -i tcp:" + lcId);
    listForNetstat.add("lsof -i tcp:" + lcId + "：");
    listForNetstat.addAll(listNetstat);
    return listForNetstat;
  }


//  //本地ip与填写ip比对，查看本地端口是否开启服务，检查远端端口是否可以ping通
//  private List<String> case102s(UploadFileChannel uploadFileChannel) {
//
//    List<String> msgs = new ArrayList<>();
//    try {
//      String hostName = InetAddress.getLocalHost().getHostAddress();
//      //检测本地ip
//      msgs.add("本地ip："+hostName);
//      msgs.add("通道填写本地ip："+uploadFileChannel.getLocalIp());
////      String callCmd = "netstat -tunlp |grep "+uploadFileChannel.getLocalPort();
//
//
//      String callCmd = "telnet 127.0.0.1 "+uploadFileChannel.getLocalPort();
//      System.out.println("发出命令："+callCmd);
//      msgs.addAll(callCmd(callCmd));
//
//      String callCmd1 = "ping "+uploadFileChannel.getRemoteIp();
//      System.out.println("发出命令："+callCmd1);
//      msgs.addAll(callCmd(callCmd1));
//    } catch (UnknownHostException e) {
//      e.printStackTrace();
//    }
//
//    return msgs;
//    //查看本地端口是否启动
//
//  }

//  //本地ip与填写ip比对，查看本地端口是否开启服务，检查远端端口是否可以ping通
//  private List<String> caseFtp(UploadFileChannel uploadFileChannel) {
//    List<String> msgs = new ArrayList<>();
//    try {
//      String hostName = InetAddress.getLocalHost().getHostAddress();
//      //检测本地ip
//      msgs.add("本地ip："+hostName);
//      msgs.add("通道填写本地ip："+uploadFileChannel.getLocalIp());
////      String callCmd = "netstat -tunlp |grep "+uploadFileChannel.getLocalPort();
//
//
//      String callCmd = "telnet 127.0.0.1 "+uploadFileChannel.getLocalPort();
//      System.out.println("发出命令："+callCmd);
//      msgs.addAll(callCmd(callCmd));
//
//      String callCmd1 = "ping "+uploadFileChannel.getRemoteIp();
//      System.out.println("发出命令："+callCmd1);
//      msgs.addAll(callCmd(callCmd1));
//    } catch (UnknownHostException e) {
//      e.printStackTrace();
//    }
//
//    return msgs;
//    //查看本地端口是否启动
//
//
//  }

//  /*
//   *  终端命令
//   *
//   * @param cmd 命令内容
//   * @throws InterruptedException 线程中断异常
//   */
//  private List<String> callCmd(String cmd) {
//    List<String> list = new ArrayList<>();
//    try {
//      if (SystemUtils.IS_OS_LINUX) {
//        try {
//          // 使用Runtime来执行command，生成Process对象
//          Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd});
//          int exitCode = process.waitFor();
//          // 取得命令结果的输出流
//          InputStream is = process.getInputStream();
//          // 用一个读输出流类去读
//          InputStreamReader isr = new InputStreamReader(is, "gb2312");
//          // 用缓冲器读行
//          BufferedReader br = new BufferedReader(isr);
//          String line = null;
//          StringBuilder sb = new StringBuilder();
//          while ((line = br.readLine()) != null) {
//            list.add("msg for linux:"+line);
//            sb.append(line);
//          }
//          is.close();
//          isr.close();
//          br.close();
//
//        } catch (NullPointerException e) {
//          System.err.println("NullPointerException " + e.getMessage());
//        } catch (IOException e) {
//          System.err.println("IOException " + e.getMessage());
//        }
//
//      }
//
//      if (SystemUtils.IS_OS_WINDOWS) {
//        Process process;
//        try {
//          //process = new ProcessBuilder(cmd).start();
//          String[] param_array = cmd.split("[\\s]+");
//          ProcessBuilder pb = new ProcessBuilder(param_array);
//          process = pb.start();
//          /*process=Runtime.getRuntime().exec(cmd);*/
//          int exitCode = process.waitFor();
//          InputStream is = process.getInputStream();
//          InputStreamReader isr = new InputStreamReader(is, "gb2312");
//          BufferedReader br = new BufferedReader(isr);
//          String line;
//          StringBuilder sb = new StringBuilder();
//
//          while ((line = br.readLine()) != null) {
//            list.add("msg for windows:"+line);
//            sb.append(line);
//          }
//          is.close();
//          isr.close();
//          br.close();
//
//        } catch (IOException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//        }
//
//      }
//    } catch (InterruptedException e) {
//      e.printStackTrace();
//    }
//
//    return list;
//  }



}
