package com.jiayue.ipfcst.fileupload.service;

import com.jiayue.ipfcst.common.core.exception.BusinessException;
import com.jiayue.ipfcst.common.core.util.DateTimeUtil;
import com.jiayue.ipfcst.common.data.constant.enums.FileStatusEnum;
import com.jiayue.ipfcst.common.data.constant.enums.FileTypeEnum;
import com.jiayue.ipfcst.common.data.entity.*;
import com.jiayue.ipfcst.common.data.repository.*;
import com.jiayue.ipfcst.common.data.service.uploadfilerule.IUploadFileRuleService;
import com.jiayue.ipfcst.console.service.ElectricFieldService;
import com.jiayue.ipfcst.console.service.SysParameterService;
import com.jiayue.ipfcst.fileupload.util.FileConstant;
import com.jiayue.ipfcst.fileupload.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.Predicate;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @author xsl
 * @version 3.0
 */
@Service
@Slf4j
public class UploadFileLogService {
  @Autowired
  private Map<String, IUploadFileRuleService> uploadFileRuleServiceMap;
  @Autowired
  private Map<String, IUploadFileService> uploadFileServiceMap;
  @Autowired
  private ElectricFieldService electricFieldService;
  @Autowired
  private UploadFileLogRepository uploadFileLogRepository;
  @Autowired
  private UploadObjectRepository uploadObjectRepository;
  @Autowired
  private UploadFileChannelRepository uploadFileChannelRepository;
  @Autowired
  private QuartzRepository quartzRepository;
  @Autowired
  private ManualUploadLogRepository manualUploadLogRepository;
  @Autowired
  private SysParameterService sysParameterService;


  /**
   * 文件日志查询
   *
   * @param uploadObjectId
   * @param createTime
   * @param fileType
   * @param isUploadSuccess
   * @return
   */
  public List<UploadFileLog> queryFileLog(Integer uploadObjectId, String createTime, String fileType, String isUploadSuccess) {
    if ("ALL".equals(fileType)) {
      fileType = "";
    }

    Specification<UploadFileLog> specification = this.getQuerySpecification(uploadObjectId, createTime, fileType);
    List<UploadFileLog> uploadFileLogList = uploadFileLogRepository.findAll(specification);

    // 定义查询结果List
    List<UploadFileLog> resultList = new ArrayList<>();
    List<UploadObject> uploadObjectList = new ArrayList<>();
    if (!"1".equals(isUploadSuccess)) {
      if ("0".equals(isUploadSuccess)) {
        resultList.addAll(uploadFileLogList.stream().filter(uploadFileLog -> !uploadFileLog.getFileStatusEnum().equals(FileStatusEnum.E2) && !uploadFileLog.getFileStatusEnum().equals(FileStatusEnum.E5)).collect(toList()));
      } else {
        resultList.addAll(uploadFileLogList);
      }
      // 获取未生成的文件信息
      if (uploadFileRuleServiceMap != null) {
        String pro = "";
        ElectricField electricField = electricFieldService.get();
        if (electricField != null) {
          pro = electricField.getProvinceEnum().name();
        }
        IUploadFileRuleService uploadFileRuleService = uploadFileRuleServiceMap.get(pro.toLowerCase() + "UploadFileRuleService");
        if (uploadFileRuleService instanceof IUploadFileRuleService) {
          if (uploadObjectId.intValue() > 0) {
            UploadObject uploadObject = uploadObjectRepository.findById(uploadObjectId).get();
            uploadObjectList.add(uploadObject);
          } else {
            uploadObjectList = uploadObjectRepository.findAll();
          }

          List<Quartz> quartzList = quartzRepository.findAll();
          for (UploadObject uploadObject : uploadObjectList) {
            if (!"".equals(fileType)) {
              String executeClass = "com.jiayue.ipfcst.fileupload.job.UploadFile" + fileType + "Job";
              List<Quartz> quartzs = quartzList.stream().filter(u -> executeClass.equals(u.getExecuteClass())).collect(Collectors.toList());
              String cronStr = "";
              if (quartzs.size() > 0) {
                cronStr = quartzs.get(0).getCronExpression();
              }
              // 此类型应该上报的文件名称
              List<String> shoudFileNameList = uploadFileRuleService.getShouldFile(electricField, new Date(Long.parseLong(createTime)), fileType, cronStr);
              // 已经生成的文件
              String finalFileType = fileType;
              List<UploadFileLog> filterList = uploadFileLogList.stream().filter(uploadFileLog -> uploadFileLog.getFileTypeEnum().equals(FileTypeEnum.valueOf(finalFileType))).collect(toList());
              // 过滤出未生成的文件名称
              List<String> noCreateFileNameList = shoudFileNameList.stream().filter(item ->
                !filterList.stream().map(e -> e.getFileName())
                  .collect(Collectors.toList()).contains(item)).collect(Collectors.toList());

              for (String noCreateFileName : noCreateFileNameList) {
                UploadFileLog noCreateFileLog = new UploadFileLog();
                noCreateFileLog.setUploadObjectNo(uploadObject.getObjectNo());
                noCreateFileLog.setUploadObjectName(uploadObject.getUploadObjectName());
                noCreateFileLog.setFileStatusEnum(FileStatusEnum.E4);
                noCreateFileLog.setFileTypeEnum(FileTypeEnum.valueOf(fileType));
                noCreateFileLog.setFileName(noCreateFileName);
                noCreateFileLog.setUploadProtocolEnum(uploadObject.getUploadProtocolEnum());
                resultList.add(noCreateFileLog);
              }
            } else {
              // 查询所有类型
              String[] uploadFileTypes = uploadObject.getUploadFileType().split(",");
              for (int i = 0; i < uploadFileTypes.length; i++) {
                String executeClass = "com.jiayue.ipfcst.fileupload.job.UploadFile" + uploadFileTypes[i] + "Job";
                List<Quartz> quartzs = quartzList.stream().filter(u -> executeClass.equals(u.getExecuteClass())).collect(Collectors.toList());
                String cronStr = "";
                if (quartzs.size() > 0) {
                  cronStr = quartzs.get(0).getCronExpression();
                }
                // 此类型应该上报的文件名称
                List<String> shoudFileNameList = uploadFileRuleService.getShouldFile(electricField, new Date(Long.parseLong(createTime)), uploadFileTypes[i], cronStr);
                String uploadFileType = uploadFileTypes[i];
                // 已经生成的文件
                List<UploadFileLog> filterList = uploadFileLogList.stream().filter(uploadFileLog -> uploadFileLog.getFileTypeEnum().equals(FileTypeEnum.valueOf(uploadFileType))).collect(toList());
                // 过滤出未生成的文件名称
                List<String> noCreateFileNameList = shoudFileNameList.stream().filter(item ->
                  !filterList.stream().map(e -> e.getFileName())
                    .collect(Collectors.toList()).contains(item)).collect(Collectors.toList());

                for (String noCreateFileName : noCreateFileNameList) {
                  UploadFileLog noCreateFileLog = new UploadFileLog();
                  noCreateFileLog.setUploadObjectNo(uploadObject.getObjectNo());
                  noCreateFileLog.setUploadObjectName(uploadObject.getUploadObjectName());
                  noCreateFileLog.setFileStatusEnum(FileStatusEnum.E4);
                  noCreateFileLog.setFileTypeEnum(FileTypeEnum.valueOf(uploadFileType));
                  noCreateFileLog.setFileName(noCreateFileName);
                  noCreateFileLog.setUploadProtocolEnum(uploadObject.getUploadProtocolEnum());
                  resultList.add(noCreateFileLog);
                }
              }
            }
          }
        }
      }
    } else {
      // 上报成功的条件
      resultList = uploadFileLogList.stream().filter(uploadFileLog -> uploadFileLog.getFileStatusEnum().equals(FileStatusEnum.E2) || uploadFileLog.getFileStatusEnum().equals(FileStatusEnum.E5)).collect(toList());
    }

    if (uploadObjectList.size() <= 0) {
      uploadObjectList = uploadObjectRepository.findAll();
    }
    List<UploadFileLog> returnUploadFileList = new ArrayList<>();
    if (resultList.size() > 0) {
      for (UploadObject uploadObject : uploadObjectList) {
        String[] uploadType = uploadObject.getUploadFileType().split(",");
        for (int j = 0; j < uploadType.length; j++) {
          String ut = uploadType[j];
          List<UploadFileLog> filterTypeList = resultList.stream().filter(uploadFileLog -> uploadFileLog.getFileTypeEnum().equals(FileTypeEnum.valueOf(ut)) && uploadFileLog.getUploadObjectNo().equals(uploadObject.getObjectNo())).collect(toList());
          returnUploadFileList.addAll(filterTypeList);
        }
      }
    }

    List<UploadFileLog> sortResultList = returnUploadFileList.stream()
      .sorted(Comparator.comparing((UploadFileLog p) -> p.getUploadObjectNo())
        .thenComparing(UploadFileLog::getFileTypeEnum).thenComparing(UploadFileLog::getFileName)).collect(Collectors.toList());

    return sortResultList;
  }

  /**
   * 封装文件日志查询条件
   *
   * @param uploadObjectId
   * @param createTime
   * @param fileType
   * @return
   */
  private Specification<UploadFileLog> getQuerySpecification(Integer uploadObjectId, String createTime, String fileType) {
    return (Specification<UploadFileLog>) (root, criteriaQuery, cb) -> {
      List<Predicate> predicates = new ArrayList<>();
      if (uploadObjectId.intValue() > 0) {
        predicates.add(cb.equal(root.get("uploadObjectId").as(Integer.class), uploadObjectId));
      }

      if (StringUtils.isNotBlank(createTime)) {
        //大于或等于传入时间
        predicates.add(cb.greaterThanOrEqualTo(root.get("createTime").as(String.class), DateFormatUtils.format(Long.valueOf(createTime), "yyyy-MM-dd HH:mm:ss'")));
        predicates.add(cb.lessThanOrEqualTo(root.get("createTime").as(String.class), DateFormatUtils.format(Long.valueOf(createTime) + 1000 * 60 * 60 * 24 - 1, "yyyy-MM-dd HH:mm:ss'")));
      }

      if (StringUtils.isNotBlank(fileType)) {
        predicates.add(cb.equal(root.get("fileTypeEnum").as(String.class), fileType));
      }

      return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
  }

  @Transactional(propagation = Propagation.SUPPORTS)
  public void updateD5000FileStatus(final String remoteIp, final String fileName, final String uploadStatus) throws BusinessException {
    List<UploadFileChannel> uploadFileChannelList = this.uploadFileChannelRepository.findByRemoteIp(remoteIp);
    if (uploadFileChannelList.size() > 0) {
      UploadFileChannel uploadFileChannel = uploadFileChannelList.get(0);
      Long st = DateTimeUtil.getMillisecondsSubDay();
      //明日凌晨
      Long et = DateTimeUtil.getMillisecondsSubDay() + 1000 * 60 * 60 * 24 - 1;
      UploadFileLog uploadFileLog = uploadFileLogRepository.findByUploadObjectIdAndFileNameAndCreateTimeBetween(uploadFileChannel.getUploadObjectId(), fileName, new Date(st), new Date(et));
      FileStatusEnum fileStatusEnum = null;
      if ("1".equals(uploadStatus)) {
        // D5000上报成功
        fileStatusEnum = FileStatusEnum.E2;
      } else {
        // D5000上报失败
        fileStatusEnum = FileStatusEnum.E3;
      }
      uploadFileLog.setFileStatusEnum(fileStatusEnum);
      this.uploadFileLogRepository.save(uploadFileLog);
      log.info("回写D5000文件状态完成,通道：" + uploadFileChannel.getChannelName() + ",文件名：" + fileName + ",返回状态：" + uploadStatus);
    } else {
      throw new BusinessException("远程IP不存在,无法更新D5000文件状态!");
    }
  }

  @Transactional(propagation = Propagation.SUPPORTS)
  public boolean uploadFile(Integer objectId, String fileType, MultipartFile file) {
    Long st = DateTimeUtil.getMillisecondsSubDay();
    //明日凌晨
    Long et = DateTimeUtil.getMillisecondsSubDay() + 1000 * 60 * 60 * 24 - 1;
    UploadFileLog uploadFileLog = uploadFileLogRepository.findByUploadObjectIdAndFileNameAndCreateTimeBetween(objectId, file.getOriginalFilename(), new Date(st), new Date(et));
    try {
      UploadObject uploadObject = uploadObjectRepository.findById(objectId).get();
      String destFileDir = null;
      // 上报文件目录
      destFileDir = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + uploadObject.getObjectNo() + File.separator + fileType;
      File destDir = new File(destFileDir);
      if (!destDir.exists()) {// 如果目录不存在则创建目录
        boolean b = destDir.mkdirs();
        if (!b) // 如果创建失败则抛出异常
          throw new RuntimeException(destFileDir + " 目录创建失败");
      }

      File destFirFile = new File(destFileDir + File.separator + file.getOriginalFilename());
      if (destFirFile.exists()) {
        File reNameFile = new File(destFileDir + File.separator + file.getOriginalFilename() + "（被替换文件）");
        if (reNameFile.exists()) {
          reNameFile.delete();
        }
        boolean b = destFirFile.renameTo(reNameFile);
        if (!b) {
          return false;
        }
      }
      file.transferTo(destFirFile);
      if (uploadFileLog == null) {
        UploadFileLog newUploadFileLog = new UploadFileLog();
        newUploadFileLog.setUploadObjectId(uploadObject.getId());
        newUploadFileLog.setUploadObjectName(uploadObject.getUploadObjectName());
        newUploadFileLog.setUploadObjectNo(uploadObject.getObjectNo());
        newUploadFileLog.setFileName(file.getOriginalFilename());
        newUploadFileLog.setFileTypeEnum(FileTypeEnum.valueOf(fileType));
        newUploadFileLog.setFileStatusEnum(FileStatusEnum.E1);
        newUploadFileLog.setUploadProtocolEnum(uploadObject.getUploadProtocolEnum());
        newUploadFileLog.setUploadCounter(0);
        newUploadFileLog.setUploadFileEndTime(null);
        newUploadFileLog.setFileRemarks("手动上传文件");
        uploadFileLog = this.uploadFileLogRepository.save(newUploadFileLog);
        String readyFileKey = uploadObject.getObjectNo() + "@" + fileType + "@" + file.getOriginalFilename();
        FileConstant.readyUploadFileMap.put(readyFileKey, newUploadFileLog);
        FileConstant.fileShouldMomentMap.put(readyFileKey, uploadFileLog.getId());
        log.info("上报对象编号：" + uploadObject.getObjectNo() + ",上传文件" + file.getOriginalFilename() + "成功");
      } else {
        uploadFileLog.setUploadCounter(0);
        String readyFileKey = uploadObject.getObjectNo() + "@" + fileType + "@" + file.getOriginalFilename();
        FileConstant.readyUploadFileMap.put(readyFileKey, uploadFileLog);
        FileConstant.fileShouldMomentMap.put(readyFileKey, uploadFileLog.getId());
        log.info("上报对象编号：" + uploadObject.getObjectNo() + ",覆盖上传文件" + file.getOriginalFilename() + "成功");
      }
      ManualUploadLog manualUploadLog = new ManualUploadLog();
      manualUploadLog.setFileName(uploadFileLog.getFileName());
      manualUploadLog.setFileTypeEnum(uploadFileLog.getFileTypeEnum());
      manualUploadLog.setUploadEquipmentID(uploadFileLog.getUploadEquipmentID());
      manualUploadLog.setUploadObjectId(uploadFileLog.getUploadObjectId());
      manualUploadLog.setUploadObjectName(uploadFileLog.getUploadObjectName());
      manualUploadLog.setUploadObjectNo(uploadFileLog.getUploadObjectNo());
      manualUploadLog.setUploadCatalog(destFileDir);
      manualUploadLog.setUploadDate(new Date());
      manualUploadLogRepository.save(manualUploadLog);
      return true;
    } catch (IOException e) {
      log.info("手动上传上报文件发生错误！");
      e.printStackTrace();
      return false;
    }
  }

  /*
   * 根据id删除日志
   */
  public void deleteById(Integer id) {
    try {
      Optional<UploadFileLog> uploadFileLogOptional = uploadFileLogRepository.findById(id);
      if (uploadFileLogOptional.isPresent()) {
        UploadFileLog uploadFileLog = uploadFileLogOptional.get();
        UploadObject uploadObject = uploadObjectRepository.findById(uploadFileLog.getUploadObjectId()).get();
        String destFileDir = null;
        // 上报文件目录
        destFileDir = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + uploadObject.getObjectNo() + File.separator + uploadFileLog.getFileTypeEnum().name();
        File destDir = new File(destFileDir);
        if (destDir.exists()) {
          File[] files = destDir.listFiles();
          for (File file : files) {
            if (uploadFileLog.getFileName().equals(file.getName())) {
              file.delete();
            }
          }
        }
        String yyyyMMdd = DateFormatUtils.format(uploadFileLog.getCreateTime(), "yyyyMMdd");
        String errorFileDir = null;
        // 错误文件目录
        errorFileDir = FileUtil.getFileUploadPath() + File.separator + "error" + File.separator + yyyyMMdd + File.separator + uploadObject.getObjectNo() + File.separator + uploadFileLog.getFileTypeEnum().name();
        File errDir = new File(errorFileDir);
        if (errDir.exists()) {
          File[] files = errDir.listFiles();
          for (File file : files) {
            if (uploadFileLog.getFileName().equals(file.getName())) {
              file.delete();
            }
          }
        }



        String backFileDir = null;
        // 备份文件目录
        backFileDir = FileUtil.getFileUploadPath() + File.separator + "backups" + File.separator + yyyyMMdd + File.separator + uploadObject.getObjectNo() + File.separator + uploadFileLog.getFileTypeEnum().name();
        File backDir = new File(backFileDir);
        if (backDir.exists()) {
          File[] files = backDir.listFiles();
          for (File file : files) {
            if (uploadFileLog.getFileName().equals(file.getName())) {
              file.delete();
            }
          }
        }
      }

      uploadFileLogRepository.deleteById(id);
    } catch (Exception e) {
      log.info("删除上报日志异常:" + e);
    }
  }

  /*
   * 清理缓存
   */
  public void cleanCache(UploadFileLog uploadFileLog) {
    try {
      String key = uploadFileLog.getUploadObjectNo() + "@" + uploadFileLog.getFileTypeEnum() + "@" + uploadFileLog.getFileName();
      /*待上报文件的缓存变量*/
      FileConstant.readyUploadFileMap.remove(key);
      FileConstant.fileShouldMomentMap.remove(key);
      /*文件上报次数累计的缓存变量*/
      FileConstant.uploadCountMap.remove(key);
      /*文件内容缓存变量*/
      FileConstant.fileContentMap.remove(key);
      /*文件内容及内容位置缓存变量*/
      FileConstant.fileContentByIdxMap.remove(key);
      /*遇到不正常回复时，将文件暂时放入再次上报变量*/
      FileConstant.againUploadFileMap.remove(key);
    } catch (Exception e) {
      log.info("上报日志清除缓存异常:" + e);
    }

  }


  /*
   * 文件补报
   */
  public void report(UploadFileLog uploadFileLog) {

    // 获取未生成的文件信息
    if (uploadFileRuleServiceMap != null) {
      String pro = "";
      ElectricField electricField = electricFieldService.get();
      if (electricField != null) {
        pro = electricField.getProvinceEnum().name();
      }
      IUploadFileRuleService uploadFileRuleService = uploadFileRuleServiceMap.get(pro.toLowerCase() + "UploadFileRuleService");
      if (uploadFileRuleService instanceof IUploadFileRuleService) {

        List<Quartz> quartzList = quartzRepository.findAll();

        String executeClass = "com.jiayue.ipfcst.fileupload.job.UploadFile" + uploadFileLog.getFileTypeEnum().name() + "Job";
        List<Quartz> quartzs = quartzList.stream().filter(u -> executeClass.equals(u.getExecuteClass())).collect(Collectors.toList());
        String cronStr = "";
        if (quartzs.size() > 0) {
          cronStr = quartzs.get(0).getCronExpression();
        }
        // 应该上报的文件名称集合
        List<String> shoudFileNameList = uploadFileRuleService.getShouldFile(electricField, uploadFileLog.getCreateTime(), uploadFileLog.getFileTypeEnum().name(), cronStr);

        if (shoudFileNameList.size() > 0) {
          int n = -1;
          for (int i = 0; i < shoudFileNameList.size(); i++) {
            if (shoudFileNameList.get(i).equals(uploadFileLog.getFileName())) {
              n = i;
              break;
            }
          }
          BigDecimal bigDecimal;
          if (DateTimeUtil.isNow((uploadFileLog.getCreateTime()))) {
            //计算文件上报的时间间隔
            BigDecimal subtract = new BigDecimal(new Date().getTime()).subtract(new BigDecimal(uploadFileLog.getCreateTime().getTime()));
            BigDecimal[] bigDecimals = subtract.divideAndRemainder(new BigDecimal(60000));
            BigDecimal[] divide = bigDecimals[0].divideAndRemainder(new BigDecimal(shoudFileNameList.size()));
            bigDecimal = divide[0].add(new BigDecimal(1));
            bigDecimal = bigDecimal.subtract(bigDecimal.divideAndRemainder(new BigDecimal(5))[1]);
            if (bigDecimal.compareTo(new BigDecimal(0)) == 0) {
              bigDecimal = new BigDecimal(1);
            }
          } else {
            bigDecimal = new BigDecimal(1440).divide(new BigDecimal(shoudFileNameList.size()));
          }


          List<FileTypeEnum> cdq = FileTypeEnum.getCDQ();
          int cdq_up_min = sysParameterService.getTranSysParameter("CDQ_UP_MIN", "0");

          BigDecimal cdqAdd = new BigDecimal(0);
          if(cdq.stream().filter(c -> c.equals(uploadFileLog.getFileTypeEnum())).collect(toList()).size()>0){
            int a = cdq_up_min%15>0?cdq_up_min - cdq_up_min%15 + 15:cdq_up_min;

            cdqAdd = new BigDecimal(a*60000);

          }

          if (n != -1) {
            //得到文件应该生成的时间
            BigDecimal multiply = bigDecimal.multiply(new BigDecimal(n)).multiply(new BigDecimal(60000));
            BigDecimal add = new BigDecimal(uploadFileLog.getCreateTime().getTime()).add(multiply).add(cdqAdd);

            long l = add.longValue();

            IUploadFileService uploadFileService = uploadFileServiceMap.get(pro.toLowerCase() + "UploadFileService");
            if (uploadFileService instanceof IUploadFileService) {
              uploadFileService.generateFile(uploadFileLog.getFileTypeEnum().name(), new Date(l));
            }
          }
        }
      }
    }
  }

  /*
   * 一键文件补报
   */
  public void quickReport(List<UploadFileLog> uploadFileLogList) {

    for (UploadFileLog uploadFileLog : uploadFileLogList
    ) {
      // 获取未生成的文件信息
      if (uploadFileRuleServiceMap != null) {
        String pro = "";
        ElectricField electricField = electricFieldService.get();
        if (electricField != null) {
          pro = electricField.getProvinceEnum().name();
        }
        IUploadFileRuleService uploadFileRuleService = uploadFileRuleServiceMap.get(pro.toLowerCase() + "UploadFileRuleService");
        if (uploadFileRuleService instanceof IUploadFileRuleService) {

          List<Quartz> quartzList = quartzRepository.findAll();

          String executeClass = "com.jiayue.ipfcst.fileupload.job.UploadFile" + uploadFileLog.getFileTypeEnum().name() + "Job";
          List<Quartz> quartzs = quartzList.stream().filter(u -> executeClass.equals(u.getExecuteClass())).collect(Collectors.toList());
          String cronStr = "";
          if (quartzs.size() > 0) {
            cronStr = quartzs.get(0).getCronExpression();
          }
          // 应该上报的文件名称集合
          List<String> shoudFileNameList = uploadFileRuleService.getShouldFile(electricField, uploadFileLog.getCreateTime(), uploadFileLog.getFileTypeEnum().name(), cronStr);

          if (shoudFileNameList.size() > 0) {
            int n = -1;
            for (int i = 0; i < shoudFileNameList.size(); i++) {
              if (shoudFileNameList.get(i).equals(uploadFileLog.getFileName())) {
                n = i;
                break;
              }
            }
            BigDecimal bigDecimal = null;
            if (DateTimeUtil.isNow((uploadFileLog.getCreateTime()))) {
              //计算文件上报的时间间隔
              BigDecimal subtract = new BigDecimal(new Date().getTime()).subtract(new BigDecimal(uploadFileLog.getCreateTime().getTime()));
              BigDecimal[] bigDecimals = subtract.divideAndRemainder(new BigDecimal(60000));
              BigDecimal[] divide = bigDecimals[0].divideAndRemainder(new BigDecimal(shoudFileNameList.size()));
              bigDecimal = divide[0].add(new BigDecimal(1));
              bigDecimal = bigDecimal.subtract(bigDecimal.divideAndRemainder(new BigDecimal(5))[1]);
            } else {
              bigDecimal = new BigDecimal(1440).divide(new BigDecimal(shoudFileNameList.size()));
            }

            if (n != -1) {
              //得到文件应该生成的时间
              BigDecimal multiply = bigDecimal.multiply(new BigDecimal(n)).multiply(new BigDecimal(60000));
              BigDecimal add = new BigDecimal(uploadFileLog.getCreateTime().getTime()).add(multiply);

              long l = add.longValue();

              IUploadFileService uploadFileService = uploadFileServiceMap.get(pro.toLowerCase() + "UploadFileService");
              if (uploadFileService instanceof IUploadFileService) {
                uploadFileService.generateFile(uploadFileLog.getFileTypeEnum().name(), new Date(l));
              }
            }
          }
        }
      }
    }
  }

}
