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.AppStrategyQO;
import com.skr.mdm.bean.vo.app.AppStrategyInfoVO;
import com.skr.mdm.dao.AppStrategyNotUninstallDao;
import com.skr.mdm.entity.AppStrategyNotUninstallDO;
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 AppStrategyNotUninstallServiceImpl implements AppStrategyInfoService {

    @Autowired
    private AppStrategyNotUninstallDao appStrategyNotUninstallDao;

    @Override
    public AppStrategyInfoVO setAppStrategyInfoVO(AppStrategyInfoVO appStrategyInfoVO, Integer strategyId) {
        appStrategyInfoVO.setNotUninstallAppConfigVOList(appStrategyNotUninstallDao.listAppConfigVO(strategyId));
        return appStrategyInfoVO;
    }

    @Override
    public void saveAppStrategy(AppStrategyQO appStrategyQO, Integer strategyId) {
        saveAppNotUninstall(appStrategyQO, strategyId);
    }

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

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

    /**
     * 保存应用防卸载
     *
     * @param appStrategyQO
     * @param strategyId
     */
    private void saveAppNotUninstall(AppStrategyQO appStrategyQO, Integer strategyId) {
        if (CollectionUtils.isNotEmpty(appStrategyQO.getNotUninstallAppIdList())) {
            List<AppStrategyNotUninstallDO> appStrategyNotUninstallDOList = appStrategyQO.getNotUninstallAppIdList()
                    .stream()
                    .map(appId -> AppStrategyNotUninstallDO.builder()
                            .strategyId(strategyId)
                            .appId(appId)
                            .build())
                    .collect(Collectors.toList());
            appStrategyNotUninstallDao.insertBatch(appStrategyNotUninstallDOList);
        }
    }
}
