package com.skr.mdm.api.app.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.skr.mdm.api.app.service.AppStrategyInfoService;
import com.skr.mdm.bean.qo.app.AppStrategyInfoQO;
import com.skr.mdm.bean.qo.app.AppStrategyQO;
import com.skr.mdm.bean.vo.app.AppStrategyInfoVO;
import com.skr.mdm.dao.AppStrategyInstallDao;
import com.skr.mdm.entity.AppStrategyInstallDO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author nfq
 * @date 2023-03-27 9:30
 */
@Service
public class AppStrategyInstallServiceImpl implements AppStrategyInfoService {

    @Autowired
    private AppStrategyInstallDao appStrategyInstallDao;

    @Override
    public AppStrategyInfoVO setAppStrategyInfoVO(AppStrategyInfoVO appStrategyInfoVO, Integer strategyId) {
        appStrategyInfoVO.setAppStrategyInstallVO(appStrategyInstallDao.getAppStrategyConfigInfoVO(strategyId));
        return appStrategyInfoVO;
    }

    @Override
    public void saveAppStrategy(AppStrategyQO appStrategyQO, Integer strategyId) {
        saveAppStrategyInstall(appStrategyQO.getAppStrategyInstallQO(), strategyId);
    }

    @Override
    public void deleteAppStrategy(List<Integer> strategyIdList) {
        appStrategyInstallDao.delete(Wrappers.lambdaQuery(AppStrategyInstallDO.class)
                .in(AppStrategyInstallDO::getStrategyId, strategyIdList));
    }

    @Override
    public boolean checkAppExist(List<Integer> appIdList, boolean isExit) {
        if (!isExit) {
            return new LambdaQueryChainWrapper<>(appStrategyInstallDao)
                    .in(AppStrategyInstallDO::getAppId, appIdList)
                    .count() > 0;
        }
        return true;
    }

    /**
     * 保存应用安装黑白名单
     *
     * @param appStrategyInfoQO
     * @param strategyId
     */
    private void saveAppStrategyInstall(AppStrategyInfoQO appStrategyInfoQO, Integer strategyId) {
        if (appStrategyInfoQO != null && CollectionUtils.isNotEmpty(appStrategyInfoQO.getAppIdList())) {
            List<AppStrategyInstallDO> appStrategyInstallDOList = appStrategyInfoQO.getAppIdList()
                    .stream()
                    .map(appId -> AppStrategyInstallDO.builder()
                            .strategyId(strategyId)
                            .strategyType(appStrategyInfoQO.getStrategyType())
                            .appId(appId)
                            .build())
                    .collect(Collectors.toList());
            appStrategyInstallDao.insertBatch(appStrategyInstallDOList);
        }
    }
}
