package com.youlai.boot.system.schedule;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youlai.boot.common.constant.SystemConstants;
import com.youlai.boot.module.file.service.FileService;
import com.youlai.boot.system.model.entity.DirectoryTree;
import com.youlai.boot.system.model.entity.Record;
import com.youlai.boot.system.service.ConfigService;
import com.youlai.boot.system.service.RecordService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Component
@RequiredArgsConstructor
public class AutoDeleteTask {

    private static final Logger log = LoggerFactory.getLogger(AutoDeleteTask.class);
    private final RecordService recordService;

    private final ConfigService configService;

    @Value("${server.auto-delete}")
    private Boolean serverAutoDelete;


    @Scheduled(cron ="*/30 * * * * ?")
    private void autoDelete() {
        if (! serverAutoDelete) {return;}
        String rootPath = configService.getSystemConfig(SystemConstants.UPLOAD_PATH).toString();

        List<File> leafFolders = DirectoryTree.getLeafFolders(new File(rootPath));

        leafFolders.forEach(file->{
            log.info("旧文件自动删除任务检查，路径{}", file.getAbsolutePath());
            String absolutePath = file.getAbsolutePath();
            absolutePath = absolutePath.replace("\\","\\\\");
            LambdaQueryWrapper<Record> queryWrapper = new LambdaQueryWrapper<Record>().like(Record::getPath, absolutePath).orderByDesc(Record::getCreateTime);

            List<Record> records = recordService.getBaseMapper().selectList(queryWrapper);
            records.forEach(r->r.setAuto_delete(1));
            records.stream().findFirst().ifPresent(r-> r.setAuto_delete(0));

            records.forEach(r-> recordService.getBaseMapper().updateById(r));

                records.forEach(r->{
                    if (r.getAuto_delete()==1){
                        Path path = Paths.get(r.getPath().replace("\\","\\\\"));
                        boolean delete = new File(path.toString()).delete();
                        if (delete){
                            log.info("已删除文件 {}",r.getFileName());
                        }
                    }
                });

        });




    }
}
