package com.jiayue.ipfcst.fileupload.config;

import com.jiayue.ipfcst.common.core.util.DateMomentUtil;
import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
import com.jiayue.ipfcst.console.service.SysParameterService;
import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
import com.jiayue.ipfcst.fileupload.util.FileConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.persistence.criteria.Predicate;
import java.util.*;

/**
 * 启动netty服务端
 *
 * @author xsl
 * @version 3.0
 */
@Component
@Order(100)
@Slf4j
public class FileUploadConfig {
  @Autowired
  UploadFileChannelService uploadFileChannelService;
  @Autowired
  SysParameterService sysParameterService;
  @Autowired
  UploadFileLogRepository uploadFileLogRepository;
  /**
   * 开启102s服务端
   */
  @Bean
  public void startIec102Server() {
    uploadFileChannelService.startAllChannel();
  }

  /**
   * 启动将fileupload/process目录里的文件加载到文件缓存变量中
   */
  @Bean
  public void loadUploadFileConstant() {
    // 查询文件日志数据库，将未上报成功的查询出来
    Specification<UploadFileLog> specification = this.getQuerySpecification();
    List<UploadFileLog> uploadFileLogList = uploadFileLogRepository.findAll(specification);
    for (UploadFileLog uploadFileLog:uploadFileLogList){
      String readyFileKey = uploadFileLog.getUploadObjectNo()+"@"+uploadFileLog.getFileTypeEnum().toString()+"@"+uploadFileLog.getFileName();
      FileConstant.readyUploadFileMap.put(readyFileKey, uploadFileLog);
      FileConstant.fileShouldMomentMap.put(readyFileKey, uploadFileLog.getId());
    }
//    try {
//      Files.walkFileTree(Paths.get(FileUtil.getFileUploadPath() + File.separator + "process"), new SimpleFileVisitor<Path>() {
//        // 访问文件时自动调用此方法,attrs参数可以获取到文件大小
//        @Override
//        public FileVisitResult visitFile(Path vfile, BasicFileAttributes attrs) {
//          try {
//            File file = vfile.toFile();
//            int processIdx = file.getPath().indexOf("process");
//            if (processIdx > -1) {
//              String separator = "/|\\\\";
//              String[] dirs = file.getPath().substring(processIdx).split(separator);
//              String readyFileKey = dirs[dirs.length - 3].toString() + "-" + dirs[dirs.length - 2].toString() + "-" + dirs[dirs.length - 1].toString();
//              FileConstant.readyUploadFileMap.put(readyFileKey, file.getPath());
//              log.info("上报文件：" + file.getPath() + "存入缓存,缓存中数量：" + FileConstant.readyUploadFileMap.size());
//            }
//          } catch (Exception e) {
//            log.error("启动加载上报文件失败：" + vfile.toFile().getPath());
//          }
//          return FileVisitResult.CONTINUE;
//        }
//
//        // 访问文件夹之前自动调用此方法
//        @Override
//        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
//          return FileVisitResult.CONTINUE;
//        }
//
//        //访问文件失败时自动调用此方法
//        @Override
//        public FileVisitResult visitFileFailed(Path file, IOException e) {
//          return FileVisitResult.CONTINUE;
//        }
//
//        //访问文件夹之后自动调用此方法
//        @Override
//        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
//          return FileVisitResult.CONTINUE;
//        }
//      });
//    } catch (Exception e) {
//      log.error("启动加载上报文件到缓存中失败：", e);
//    }
  }

  /**
   * 封装文件日志查询条件
   * @return
   */
  private Specification<UploadFileLog> getQuerySpecification() {
    return (Specification<UploadFileLog>) (root, criteriaQuery, cb) -> {
      Long startTime = DateMomentUtil.getDayStartTime(new Date().getTime());
      // 结束时间（开始加24小时再减去1秒）
      Long endTime = startTime + 1000 *60 * 60 *24 -1;

      List<Predicate> predicates = new ArrayList<>();
      predicates.add(cb.equal(root.get("fileStatusEnum").as(String.class), "E1"));
      predicates.add(cb.greaterThanOrEqualTo(root.get("createTime").as(String.class), DateFormatUtils.format(startTime, "yyyy-MM-dd HH:mm:ss'")));
      predicates.add(cb.lessThanOrEqualTo(root.get("createTime").as(String.class), DateFormatUtils.format(endTime, "yyyy-MM-dd HH:mm:ss'")));
      return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
  }
}
