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.AppStrategyShortcutsDao;
import com.skr.mdm.entity.AppStrategyShortcutsDO;
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 AppStrategyShortcutsAppServiceImpl implements AppStrategyInfoService {

    @Autowired
    private AppStrategyShortcutsDao appStrategyShortcutsDao;

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

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

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

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

    /**
     * 保存快捷应用
     *
     * @param appStrategyQO
     * @param strategyId
     */
    private void saveAppShortcuts(AppStrategyQO appStrategyQO, Integer strategyId) {
        if (CollectionUtils.isNotEmpty(appStrategyQO.getShortcutsAppIdList())) {
            List<AppStrategyShortcutsDO> appStrategyShortcutsDOList = appStrategyQO.getShortcutsAppIdList()
                    .stream()
                    .map(appId -> AppStrategyShortcutsDO.builder()
                            .strategyId(strategyId)
                            .appId(appId)
                            .build())
                    .collect(Collectors.toList());
            appStrategyShortcutsDao.insertBatch(appStrategyShortcutsDOList);
        }
    }
}
