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.AppStrategyRunDao;
import com.skr.mdm.entity.AppStrategyRunDO;
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 AppStrategyRunServiceImpl implements AppStrategyInfoService {

    @Autowired
    private AppStrategyRunDao appStrategyRunDao;

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

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

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

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

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