package com.jpsoft.shinestar.scheduled;

import com.jpsoft.ehome.config.EHomeParamConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.File;

@Slf4j
@Component
public class CleanEhomePicTask {
    @Autowired
    private EHomeParamConfig eHomeParamConfig;

    @Scheduled(cron="0 0 0/6 * * ?")
    public void run(){
        log.warn("开始清理海康威视上传的临时图片");

        String picPath = eHomeParamConfig.getPicPath();

        File dir = new File(picPath);

        if (dir.exists()) {
            long maxInterval = 6 * 3600 * 1000;

            File[] files = dir.listFiles((file) -> {
                long time = file.lastModified();

                long intervalMillis = System.currentTimeMillis() - time;

                return intervalMillis > maxInterval;
            });

            //删除过期文件
            int affectCount = 0;
            for (File file : files) {
                if (file.delete()) {
                    affectCount++;
                }
            }

            log.warn("清理海康威视上传的临时图片共{}张，已删除{}张", files.length, affectCount);
        }
        else{
            log.warn("文件夹不存在!" + dir.getAbsolutePath());
        }
    }

    public static void main(String[] args){
        CleanEhomePicTask task  =new CleanEhomePicTask();
        task.run();
    }
}
