package com.skr.mdm.observer;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.toolkit.AopUtils;
import com.skr.mdm.event.UserDeleteEvent;
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;

/**
 * 删除用户所有相关数据
 *
 * @author nfq
 * @date 2022-12-09 14:51
 */
@Component
@Slf4j
public class UserDataDeleteObserver implements ApplicationListener<UserDeleteEvent> {

    private final String DELETE_USER_METHOD = "deleteByUserIdList";

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(UserDeleteEvent event) {
        log.info("监听到用户删除事件:{}", JSONUtil.toJsonStr(event.getUserIdList()));
        if (CollectionUtils.isEmpty(event.getUserIdList())) {
            log.info("监听到用户删除事件用户ID为空：{}", event.getUserIdList());
            return;
        }
        TimeInterval timer = DateUtil.timer();
        // 获取所有DAO bean
        Map<String, Object> repositoryBeanMap = applicationContext.getBeansWithAnnotation(Repository.class);
        repositoryBeanMap.forEach((k, v) -> {
            try {
                if (ClassUtils.hasMethod(v.getClass(), DELETE_USER_METHOD, List.class)) {
                    Method method = ClassUtils.getMethod(v.getClass(), DELETE_USER_METHOD, List.class);
                    method.invoke(AopUtils.getTargetObject(v), event.getUserIdList());
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                log.error("用户相关数据删除异常" + JSONUtil.toJsonStr(event.getUserIdList()), e);
            }
        });
        log.info("用户:{}数据删除成功 耗时：{}毫秒", JSONUtil.toJsonStr(event.getUserIdList()), timer.intervalMs());
    }
}
