package com.tofly.common.task;

import com.tofly.common.core.util.io.IOUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;

/**
 * @author tuonbed
 * @date 2020/4/1  15:16
 */
@EnableScheduling
@EnableAsync
@Slf4j
@Component
public class DelTempFileTask {

    @Async
    @Scheduled(cron="0 0/5 *  * * ? ")   //间隔5分钟
    @SneakyThrows
    public void run(){
        log.info("开始清除临时文件");
        //每5分钟清除一次临时文件
        File file=new File(IOUtil.TEMP_FILEPATH);
        if(file.isDirectory()){
            File[] files = file.listFiles();
            Arrays.stream(files).forEach(file1 -> {
                if(System.currentTimeMillis()-file1.lastModified()>1000*60*5){
                    Instant instant = Instant.ofEpochMilli(file1.lastModified());
                    ZoneId zone = ZoneId.systemDefault();
                    LocalDateTime localDateTime1 = LocalDateTime.ofInstant(instant, zone);
                    deleteDirectory(file1);
                    log.info("删除文件："+file1.getName()+",改文件最后修改时间为："+ localDateTime1);
                }
            });
        }
    }

    @PostConstruct
    public void mkdir(){
        File file=new File(IOUtil.TEMP_FILEPATH);
        if(!file.exists()){
            file.mkdir();
        }
    }

    private void deleteDirectory(File file) {
        if (file.isDirectory()) {
            File[] subFiles = file.listFiles();
            for (int i = 0; i < subFiles.length; i++) {
                deleteDirectory(subFiles[i]);
            }
        }else{
            file.delete();
        }
    }
}
