package com.skr.mdm.observer.global;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.google.common.collect.Lists;
import com.skr.mdm.bean.so.client.ClientUpgradeSO;
import com.skr.mdm.dao.ClientUpgradeDao;
import com.skr.mdm.dao.ClientUpgradeUserDao;
import com.skr.mdm.dao.MdmStrategyDeptDao;
import com.skr.mdm.entity.ClientUpgradeDO;
import com.skr.mdm.entity.ClientUpgradeUserDO;
import com.skr.mdm.entity.MdmStrategyDeptDO;
import com.skr.mdm.enums.ClientUpgradeCmdEnum;
import com.skr.mdm.enums.IssuedTypeEnum;
import com.skr.mdm.enums.StrategyDeptTypeEnum;
import com.skr.mdm.enums.StrategyEquipmentStateEnum;
import com.skr.mdm.event.UserActiveEvent;
import com.skr.mdm.handle.IssuedUserHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户设备激活全局客户端升级下发
 *
 * @author nfq
 * @date 2022/06/09 9:50
 */
@Component
@Slf4j
public class GlobalClientUpgradeObserver implements ApplicationListener<UserActiveEvent> {

    @Autowired
    public ClientUpgradeDao clientUpgradeDao;
    @Autowired
    public ClientUpgradeUserDao clientUpgradeUserDao;
    @Autowired
    private IssuedUserHandler issuedUserHandler;
    @Autowired
    private MdmStrategyDeptDao strategyDeptDao;

    @Override
    public void onApplicationEvent(UserActiveEvent event) {
        try {
            List<ClientUpgradeDO> clientUpgradeDOList = getClientUpgradeDOList(event);
            if (CollectionUtils.isNotEmpty(clientUpgradeDOList)) {
                List<ClientUpgradeSO> clientUpgradeSOList = Lists.newArrayListWithCapacity(clientUpgradeDOList.size());
                clientUpgradeDOList.forEach(clientUpgradeDO -> {
                    Long counted = new LambdaQueryChainWrapper<>(clientUpgradeUserDao)
                            .eq(ClientUpgradeUserDO::getEquipmentId, event.getEquipmentId())
                            .eq(ClientUpgradeUserDO::getClientUpgradeId, clientUpgradeDO.getId())
                            .count();
                    if (counted == 0) {
                        ClientUpgradeUserDO clientUpgradeUserDO = ClientUpgradeUserDO.builder()
                                .clientUpgradeId(clientUpgradeDO.getId())
                                .equipmentId(event.getEquipmentId())
                                .state(StrategyEquipmentStateEnum.ISSUING.getState())
                                .pauseStatus(clientUpgradeDO.getIsPause())
                                .issuedTime(new Date())
                                .build();
                        clientUpgradeUserDao.insert(clientUpgradeUserDO);
                        ClientUpgradeSO clientUpgradeSO = ClientUpgradeSO.builder()
                                .sendTime(new Date())
                                .build();
                        BeanUtils.copyProperties(clientUpgradeDO, clientUpgradeSO);
                        clientUpgradeSOList.add(clientUpgradeSO);
                    }
                });
                if (CollectionUtils.isNotEmpty(clientUpgradeSOList)) {
                    issuedUserHandler.issuedUser(ListUtil.toList(event.getEquipmentId()), event.getCompanyId(),
                            ClientUpgradeCmdEnum.PUSH_CLIENT_UPGRADE.getCmd(), JSONUtil.toJsonStr(ListUtil.toList(clientUpgradeSOList)));
                }
            }
        } catch (Exception e) {
            log.error("设备激活全局客户端升级下发异常：" + event.getEquipmentId(), e);
        }
    }

    private List<ClientUpgradeDO> getClientUpgradeDOList(UserActiveEvent event) {
        // 获取全局策略
        List<ClientUpgradeDO> clientUpgradeDOList = new LambdaQueryChainWrapper<>(clientUpgradeDao)
                .eq(ClientUpgradeDO::getCompanyId, event.getCompanyId())
                .eq(ClientUpgradeDO::getGlobalType, IssuedTypeEnum.GLOBAL.getIssuedType())
                .list();
        // 获取用户的部门全局策略
        List<MdmStrategyDeptDO> strategyDeptDOList = new LambdaQueryChainWrapper<>(strategyDeptDao)
                .eq(MdmStrategyDeptDO::getDepartmentId, event.getDepartmentId())
                .eq(MdmStrategyDeptDO::getStrategyType, StrategyDeptTypeEnum.CLIENT_UPGRADE.getStrategyType())
                .list();
        // 合并全局策略
        if (CollectionUtils.isNotEmpty(strategyDeptDOList)) {
            List<Integer> clientUpgradeIdList = strategyDeptDOList.stream().map(MdmStrategyDeptDO::getStrategyId).collect(Collectors.toList());
            List<ClientUpgradeDO> clientUpgradeDOS = clientUpgradeDao.selectBatchIds(clientUpgradeIdList);
            if (CollectionUtils.isNotEmpty(clientUpgradeDOList)) {
                clientUpgradeDOList.addAll(clientUpgradeDOS);
            } else {
                clientUpgradeDOList = clientUpgradeDOS;
            }
        }
        return clientUpgradeDOList;
    }

}
