package com.skr.mdm.observer.global;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.google.common.collect.Lists;
import com.skr.mdm.dao.*;
import com.skr.mdm.entity.*;
import com.skr.mdm.enums.StrategyDeptTypeEnum;
import com.skr.mdm.event.UserActiveEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 用户激活全局应用发布新增
 *
 * @author nfq
 * @date 2023-01-10 17:37
 */
@Component
@Slf4j
public class GlobalAppPublishObserver implements ApplicationListener<UserActiveEvent> {

    @Autowired
    private DeviceEquipmentDao equipmentDao;
    @Autowired
    private MdmStrategyUserDao strategyUserDao;
    @Autowired
    private MdmAppStoreUserDao appStoreUserDao;

    @Override
    public void onApplicationEvent(UserActiveEvent event) {
        try {
            DeviceEquipmentDO deviceEquipmentDO = equipmentDao.selectById(event.getEquipmentId());
            // 获取公司下所有的的全局策略
            List<MdmStrategyUserDO> appPublishDOList = getGlobalAppPublishDOList(deviceEquipmentDO.getUserId());
                List<MdmAppStoreUserDO> mdmAppStoreUserDOList = Lists.newArrayListWithCapacity(appPublishDOList.size());
                for (MdmStrategyUserDO mdmStrategyUserDO : appPublishDOList) {
                    mdmAppStoreUserDOList.add(saveAppUser(event.getEquipmentId(),mdmStrategyUserDO.getStrategyId()));
                }
            if (CollectionUtils.isNotEmpty(mdmAppStoreUserDOList)) {
                appStoreUserDao.insertBatch(mdmAppStoreUserDOList);
            }
        } catch (Exception e) {
            log.error("设备激活全局应用发布添加异常：" + event.getEquipmentId(), e);
        }
    }

    private List<MdmStrategyUserDO> getGlobalAppPublishDOList(Integer userId) {
        // 获取用户的用户全局策略
        List<MdmStrategyUserDO> strategyUserDOList = new LambdaQueryChainWrapper<>(strategyUserDao)
                .eq(MdmStrategyUserDO::getUserId, userId)
                .eq(MdmStrategyUserDO::getStrategyType, StrategyDeptTypeEnum.APP_PUSH.getStrategyType())
                .list();
        return strategyUserDOList;
    }

    private MdmAppStoreUserDO saveAppUser(Integer userId, Integer appId) {
     return MdmAppStoreUserDO.builder()
                            .appId(appId)
                            .equipmentId(StrategyDeptTypeEnum.APP_STORE.getStrategyType())
                            .build();
    }

}