package com.skr.mdm.observer;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.baomidou.mybatisplus.extension.toolkit.AopUtils;
import com.skr.mdm.event.DataBaseCleanEvent;
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.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author nfq
 * @date 2023-03-10 14:47
 */
@Component
@Slf4j
public class DataBaseCleanObserver implements ApplicationListener<DataBaseCleanEvent> {

    private final String COUNT_QUERY_METHOD = "countAll";

    private final String DELETE_ID_QUERY_METHOD = "listDelId";

    private final String DELETE_ID_METHOD = "deleteBatchIds";

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(DataBaseCleanEvent event) {
        log.info("监听到数据库清理事件 最大限制数量:{}万", event.getMaxLimit());
        if (event.getMaxLimit() == null || event.getMaxLimit().equals(0)) {
            return;
        }
        Integer maxLimit = event.getMaxLimit() * 10000;
        TimeInterval timer = DateUtil.timer();
        AtomicInteger delAllCount = new AtomicInteger(0);
        // 获取所有DAO bean
        Map<String, Object> repositoryBeanMap = applicationContext.getBeansWithAnnotation(Repository.class);
        repositoryBeanMap.forEach((k, v) -> {
            try {
                if (ClassUtils.hasMethod(v.getClass(), COUNT_QUERY_METHOD)) {
                    log.info("数据库清理bean:{}", k);
                    Method method = ClassUtils.getMethod(v.getClass(), COUNT_QUERY_METHOD);
                    Integer countAll = (Integer) method.invoke(AopUtils.getTargetObject(v));
                    // 超出最大数量限制
                    if (countAll > maxLimit) {
                        log.info("数据库清理bean:{}超出最大限制数量：{}", k, countAll);
                        Integer delCount = countAll - maxLimit;
                        if (ClassUtils.hasMethod(v.getClass(), DELETE_ID_QUERY_METHOD, Integer.class)) {
                            Method listDelIdMethod = ClassUtils.getMethod(v.getClass(), DELETE_ID_QUERY_METHOD, Integer.class);
                            List<Integer> listDelId = (List<Integer>) listDelIdMethod.invoke(AopUtils.getTargetObject(v), delCount);
                            if (CollectionUtils.isNotEmpty(listDelId)) {
                                Method deleteMethod = ClassUtils.getMethod(v.getClass(), DELETE_ID_METHOD, List.class);
                                deleteMethod.invoke(AopUtils.getTargetObject(v), listDelId);
                                log.info("数据库清理bean:{}执行删除{}条数据", k, delCount);
                                delAllCount.set(delAllCount.get() + delCount);
                            }
                        }
                    }
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                log.error("数据库清理异常", e);
            }
        });
        log.info("数据库清理成功 清理：{}条数据 耗时：{}毫秒", delAllCount, timer.intervalMs());
    }
}
