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.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.toolkit.AopUtils;
import com.skr.mdm.dao.AuUserDao;
import com.skr.mdm.dao.DeviceEquipmentDao;
import com.skr.mdm.entity.DeviceEquipmentDO;
import com.skr.mdm.enums.SendCmdConfigEnum;
import com.skr.mdm.event.CompanyDeleteEvent;
import com.skr.mdm.handle.IssuedUserHandler;
import com.skr.mdm.manager.DeviceManager;
import com.skr.mdm.publish.MdmEventPublisher;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.NotNull;
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.stream.Collectors;

/**
 * 删除公司所有相关数据
 *
 * @author nfq
 * @date 2022-12-12 10:38
 */
@Component
@Slf4j
public class CompanyDataDeleteObserver implements ApplicationListener<CompanyDeleteEvent> {

    private final String DELETE_USER_METHOD = "deleteByCompanyId";

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private MdmEventPublisher mdmEventPublisher;
    @Autowired
    private DeviceEquipmentDao equipmentDao;
    @Autowired
    private AuUserDao userDao;
    @Autowired
    private DeviceManager deviceManager;
    @Autowired
    private IssuedUserHandler issuedUserHandler;

    @Override
    public void onApplicationEvent(CompanyDeleteEvent event) {
        log.info("监听到公司删除事件：{}", event.getCompanyId());
        TimeInterval timer = DateUtil.timer();
        // 发送用户删除事件
        List<Integer> userIdList = userDao.listUserIdByCompanyId(event.getCompanyId());
        if (CollectionUtils.isNotEmpty(userIdList)) {
            mdmEventPublisher.publishUserDeleteEvent(userIdList);
        }
        // 设备删除处理
        List<Integer> equipmentIdList = getEquipmentIdList(event);
        deleteEquipment(event, equipmentIdList);
        // 获取所有DAO bean
        Map<String, Object> repositoryBeanMap = applicationContext.getBeansWithAnnotation(Repository.class);
        repositoryBeanMap.forEach((k, v) -> {
            try {
                if (ClassUtils.hasMethod(v.getClass(), DELETE_USER_METHOD, Integer.class)) {
                    Method method = ClassUtils.getMethod(v.getClass(), DELETE_USER_METHOD, Integer.class);
                    method.invoke(AopUtils.getTargetObject(v), event.getCompanyId());
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                log.error("公司相关数据删除异常" + event.getCompanyId(), e);
            }
        });
        log.info("公司数据删除成功:{} 耗时：{}毫秒", event.getCompanyId(), timer.intervalMs());
    }

    private void deleteEquipment(CompanyDeleteEvent event, List<Integer> equipmentIdList) {
        if (CollectionUtils.isNotEmpty(equipmentIdList)) {
            // 删除高德猎鹰终端
            List<Integer> deviceIdList = deviceManager.deleteGaodeTerminal(equipmentIdList, event.getCompanyId());
            // 下发删除指令
            if (CollectionUtils.isNotEmpty(deviceIdList)) {
                equipmentIdList.removeAll(deviceIdList);
                issuedUserHandler.issuedUser(deviceIdList, event.getCompanyId(), SendCmdConfigEnum.DELETE_USER_EQUIPMENT.getCmd(), "");
                // 发布设备删除事件
                deviceManager.deleteDevice(deviceIdList);
            }
            if (CollectionUtils.isNotEmpty(equipmentIdList)) {
                log.warn("高德终端删除失败设备：{}", JSONUtil.toJsonStr(equipmentIdList));
            }
        }
    }

    @NotNull
    private List<Integer> getEquipmentIdList(CompanyDeleteEvent event) {
        return new LambdaQueryChainWrapper<>(equipmentDao)
                .eq(DeviceEquipmentDO::getCompanyId, event.getCompanyId())
                .list()
                .stream()
                .map(DeviceEquipmentDO::getId)
                .collect(Collectors.toList());
    }
}
