package com.jiayue.ipfcst.fileupload.job;

import com.jiayue.ipfcst.common.core.util.DateTimeUtil;
import com.jiayue.ipfcst.common.data.constant.enums.ChannelStatusEnum;
import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
import com.jiayue.ipfcst.common.data.entity.UploadObject;
import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
import com.jiayue.ipfcst.common.data.service.BaseService;
import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
import com.jiayue.ipfcst.fileupload.service.UploadFileLogService;
import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
import com.jiayue.ipfcst.fileupload.util.FileConstant;
import com.jiayue.ipfcst.fileupload.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 监听上报通道
 *
 * @author xsl
 * @version 3.0
 * @since 2020/12/3 9:51
 */
@Slf4j
@Service
@EnableScheduling
public class ListenUploadJob {
  @Autowired
  UploadObjectService uploadObjectService;
  @Autowired
  UploadFileChannelService uploadFileChannelService;
  @Autowired
  UploadFileLogRepository uploadFileLogRepository;
  @Autowired
  BaseService baseService;

  @Scheduled(initialDelay = 300000,fixedDelay = 60000)
  public void execute() {
    // 获取参数是否执行监听上报长时间不交互重启console
    String jtsb = baseService.getSysParameter("jtsb","0");
    if ("1".equals(jtsb)){
      List<UploadObject> uploadObjectList = uploadObjectService.get();
      // 过滤出102的
      List<UploadObject> uploadObjects = uploadObjectList.stream().filter(s -> !"ftp".equals(s.getUploadProtocolEnum().getCode()) && !"sftp".equals(s.getUploadProtocolEnum().getCode())).collect(Collectors.toList());
      // 拼装上报通道状态
      Map<String, String> objectStatusMap = new HashMap<String, String>();
      for (Map.Entry<String, String> entry : FileConstant.channelStatusMap.entrySet()) {
        String[] statusKeys = entry.getKey().toString().split("-");
        if ("1".equals(entry.getValue().toString())) {
          // 将正常的通道获取
          objectStatusMap.put(statusKeys[0], "1");
        }
      }

      for (UploadObject o : uploadObjects) {
        if (objectStatusMap.get(o.getId())==null || "0".equals(objectStatusMap.get(o.getId()+""))){
          if (FileConstant.channelTimeMap.get(o.getId()+"")!=null){
            if (System.currentTimeMillis() - FileConstant.channelTimeMap.get(o.getId()+"")>600000){
              SimpleDateFormat formatter = new SimpleDateFormat("mm");
              int a =  Integer.parseInt(formatter.format(new Date(System.currentTimeMillis())));
              if (a % 5 == 0) {
                FileConstant.channelTimeMap.put(o.getId()+"",System.currentTimeMillis());
              }
              else{
                log.info("监听上报对象："+o.getUploadObjectName()+",在10分钟内没有通讯,重启console");
                try {
                  Process process = Runtime.getRuntime().exec("service console restart");
                  process.getInputStream().close();
                  process.getOutputStream().close();
                  process.destroy();
                } catch (IOException e) {
                  log.error("重启console执行失败",e);
                }
              }
            }
          }
          else{
            FileConstant.channelTimeMap.put(o.getId()+"",System.currentTimeMillis());
          }
        }
        else{
          FileConstant.channelTimeMap.remove(o.getId()+"");
        }
      }
    }
  }
}
