package com.skr.mdm.service.impl.reload.handler;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.skr.mdm.annotation.MdmReloadHandler;
import com.skr.mdm.bean.so.ReloadSO;
import com.skr.mdm.bean.so.app.AppStrategySO;
import com.skr.mdm.dao.AppStrategyUserDao;
import com.skr.mdm.entity.AppStrategyUserDO;
import com.skr.mdm.enums.StrategyEquipmentStateEnum;
import com.skr.mdm.manager.AppStrategyManager;
import com.skr.mdm.service.impl.reload.ReloadHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * @author nfq
 * @date 2022/06/10 14:53
 */
@MdmReloadHandler
@Slf4j
public class AppStrategyReloadHandler implements ReloadHandler {

    @Autowired
    private AppStrategyUserDao appStrategyUserDao;
    @Autowired
    private AppStrategyManager appStrategyManager;

    @Override
    public void doHandler(ReloadSO reloadSO, Integer equipmentId) {
        try {
            List<AppStrategyUserDO> appStrategyUserDOList = new LambdaQueryChainWrapper<>(appStrategyUserDao)
                    .eq(AppStrategyUserDO::getEquipmentId, equipmentId)
                    .ne(AppStrategyUserDO::getState, StrategyEquipmentStateEnum.ISSUING.getState())
                    .list();
            if (CollectionUtils.isNotEmpty(appStrategyUserDOList)) {
                List<Integer> strategyIdList = appStrategyUserDOList.stream().map(AppStrategyUserDO::getStrategyId).collect(Collectors.toList());
                List<AppStrategySO> appStrategySOList = appStrategyManager.getAppStrategySOList(strategyIdList);
                // 更新下发时间
                if (CollectionUtils.isNotEmpty(appStrategySOList)) {
                    appStrategySOList.forEach(appStrategySO -> {
                        for (AppStrategyUserDO appStrategyUserDO : appStrategyUserDOList) {
                            if (appStrategyUserDO.getStrategyId().equals(appStrategySO.getId())) {
                                appStrategySO.setSendTime(appStrategyUserDO.getIssuedTime());
                                break;
                            }
                        }
                    });
                }
                reloadSO.setAppStrategyList(appStrategySOList);
            }
        } catch (Exception e) {
            log.error("卸载重装应用策略异常：" + equipmentId, e);
        }
    }

}