package com.skr.mdm.observer;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.baomidou.mybatisplus.extension.toolkit.AopUtils;
import com.skr.mdm.event.MinIoFileCleanEvent;
import com.skr.mdm.manager.oss.MinIoManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.util.ClassUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author nfq
 * @date 2023-03-10 18:42
 */
@Component
@Slf4j
public class MinIoFileCleanObserver implements ApplicationListener<MinIoFileCleanEvent> {

    private final String COUNT_QUERY_METHOD = "listDelFileUrl";

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private MinIoManager minIoManager;

    @Override
    public void onApplicationEvent(MinIoFileCleanEvent event) {
        log.info("监听到MinIo文件清理事件 文件保留天数:{}天", event.getFileRetentionDays());
        if (event.getFileRetentionDays() == null || event.getFileRetentionDays().equals(0)) {
            return;
        }
        AtomicInteger delAllCount = new AtomicInteger(0);
        // 过期时间
        LocalDateTime expireDateTime = LocalDateTime.now().minus(event.getFileRetentionDays(), ChronoUnit.DAYS);
        String expireDate = DateUtil.format(expireDateTime, DatePattern.NORM_DATE_PATTERN);
        TimeInterval timer = DateUtil.timer();
        // 获取所有DAO bean
        Map<String, Object> repositoryBeanMap = applicationContext.getBeansWithAnnotation(Repository.class);
        repositoryBeanMap.forEach((k, v) -> {
            try {
                if (ClassUtils.hasMethod(v.getClass(), COUNT_QUERY_METHOD, String.class)) {
                    log.info("MinIo文件清理bean:{}", k);
                    Method method = ClassUtils.getMethod(v.getClass(), COUNT_QUERY_METHOD, String.class);
                    List<String> listDelFileUrl = (List<String>) method.invoke(AopUtils.getTargetObject(v), expireDate);
                    if (CollectionUtils.isNotEmpty(listDelFileUrl)) {
                        log.info("MinIo文件清理bean:{} 文件{}", k, listDelFileUrl);
                        minIoManager.removeObject(listDelFileUrl);
                        delAllCount.set(delAllCount.get() + listDelFileUrl.size());
                    }
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                log.error("MinIo文件清理异常", e);
            }
        });
        log.info("MinIo文件清理成功 清理：{}个文件 耗时：{}毫秒", delAllCount, timer.intervalMs());
    }
}