ConfigGroupServiceImpl.java 14.3 KB
package cn.fw.dalaran.service.data.impl;

import cn.fw.dalaran.common.constants.DalaranConstants;
import cn.fw.dalaran.common.exception.BusinessException;
import cn.fw.dalaran.dao.ConfigGroupDao;
import cn.fw.dalaran.domain.db.ActivityTheme;
import cn.fw.dalaran.domain.db.ConfigGroup;
import cn.fw.dalaran.domain.db.GlobalConfig;
import cn.fw.dalaran.domain.enums.BizTypeEnum;
import cn.fw.dalaran.domain.vo.ConfigGroupVo;
import cn.fw.dalaran.domain.vo.EvlIndexVO;
import cn.fw.dalaran.domain.vo.EvlSubIndexVO;
import cn.fw.dalaran.domain.vo.ValidConfigNewVo;
import cn.fw.dalaran.rpc.dto.StaffBaseInfoRpc;
import cn.fw.dalaran.rpc.ehr.EhrRpc;
import cn.fw.dalaran.rpc.erp.UserRoleRpcService;
import cn.fw.dalaran.rpc.erp.dto.ShopMsg;
import cn.fw.dalaran.service.biz.EvlSettingService;
import cn.fw.dalaran.service.data.ActivityThemeService;
import cn.fw.dalaran.service.data.ConfigGroupService;
import cn.fw.dalaran.service.data.GlobalConfigService;
import cn.fw.dalaran.service.data.ValidConfigNewService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wmy3969
 * @version 1.0
 * @date 2022-4-28 16:25:22
 * @Description 配置组业务
 */
@Service
@RequiredArgsConstructor
public class ConfigGroupServiceImpl extends ServiceImpl<ConfigGroupDao, ConfigGroup> implements ConfigGroupService {

    private final EvlSettingService evlSettingService;
    private final ValidConfigNewService validConfigNewService;
    private final GlobalConfigService globalConfigService;
    private final UserRoleRpcService userRoleRpcService;
    private final EhrRpc ehrRpc;

    // 懒加载, 解决bean循环依赖
    private ActivityThemeService activityThemeService;

    @Autowired
    public void activityThemeService(@Lazy ActivityThemeService activityThemeService) {
        this.activityThemeService = activityThemeService;
    }

    /**
     * 初始化一个配置组
     *
     * @param userId  用户id
     * @param groupId 集团id
     * @return
     */
    @Override
    @Transactional
    public ConfigGroupVo init(Long userId, Long groupId) {
        if (this.lambdaQuery()
                .eq(ConfigGroup::getGroupId, groupId)
                .eq(ConfigGroup::getUserId, userId)
                .eq(ConfigGroup::getAllShop, -2)
                .list().size() > 0)
            throw new BusinessException("该用户存在一个已初始化但未赋值修改的配置组");
        ConfigGroup configGroup = new ConfigGroup();
        configGroup.setUserId(userId);
        configGroup.setGroupId(groupId);
        configGroup.setEvlVideoId(-1L);
        configGroup.setEvlLiveId(-1L);
        configGroup.setAllShop(-2);
        final boolean result = this.save(configGroup);// 初始化配置组
        if (result)
            return this.processVo(configGroup, false);
        throw new BusinessException("初始化配置组失败");
    }

    /**
     * 更新配置组
     *
     * @param userId 用户id
     * @param param  参数封装
     * @return
     */
    @Override
    @Transactional
    public boolean update(Long userId, ConfigGroupVo param) {
        if (!Objects.equals(userId, param.getUserId()))
            throw new BusinessException("不允许修改别人的配置组");
        final Long configGroupId = param.getId();
        List<ConfigGroup> list = this.lambdaQuery()
                .eq(ConfigGroup::getGroupId, param.getGroupId())
                .ne(ConfigGroup::getAllShop, -2)
                .list();// 找到对应集团的所有生效的配置组
        Integer allShop = param.getAllShop();
        if (Objects.equals(allShop, 1)) {// 本次指定配置是否为全部门店
            if (list.size() > 0) throw new BusinessException("该集团已存在门店配置, 新配置不能设置为[全部门店]");
        } else if (list.stream().anyMatch(item -> Objects.equals(item.getAllShop(), 1))) {// 已存在的配置组是否有全部门店的
            throw new BusinessException("该集团已存在[全部门店]配置, 新配置不能生效");
        } else {
            List<Long> shopIds = param.getShopIds();// 本次配置指定生效门店
            List<String> shopNames = param.getShopNames();// 本次配置指定生效门店
            if (Objects.equals(allShop, -1)) {// 指定为授权门店
                List<ShopMsg> userRoleRange = userRoleRpcService.getUserRoleRange(param.getUserId(), DalaranConstants.ZBSZ_ROLE_CODE);// 查询用户角色授权范围
                shopIds.clear();
                shopNames.clear();
                for (ShopMsg shopMsg : userRoleRange) {
                    shopIds.add(shopMsg.getShopId());
                    shopNames.add(shopMsg.getShopName());
                }
                param.setShopIds(shopIds);
                param.setShopNames(shopNames);
            }
            if (list.stream()
                    .anyMatch(item -> !Objects.equals(item.getId(), param.getId()) &&
                            CollectionUtils.containsAny(
                                    Arrays.stream(item.getShopIds().split(","))
                                            .map(Long::valueOf)
                                            .collect(Collectors.toList()),
                                    shopIds
                            )// 除开自己本身, 任何一个配置门店信息和本次指定的门店有重合, 本次修改都不能生效
                    )
            ) throw new BusinessException("本次指定门店和集团已有配置门店重合, 修改失败");
            final Date yesterday = new Date(System.currentTimeMillis() - 24 * 3600 * 1000L);
            final String validConfigJson = activityThemeService.getValidConfigJson(configGroupId);
            activityThemeService.lambdaUpdate()
                    .set(!CollectionUtils.isEmpty(shopIds), ActivityTheme::getShopIds, this.processJsonString(JSON.toJSONString(shopIds)))
                    .set(!CollectionUtils.isEmpty(shopNames), ActivityTheme::getShopNames, this.processJsonString(JSON.toJSONString(shopNames)))
                    .set(Objects.nonNull(allShop), ActivityTheme::getAllShop, allShop)
                    .set(ActivityTheme::getValidConfigJson, validConfigJson)
                    .eq(ActivityTheme::getConfigGroupId, configGroupId)
                    .and(wrapper -> wrapper
                            .lt(ActivityTheme::getStartTime, yesterday)
                            .gt(ActivityTheme::getEndTime, yesterday)
                            .or()
                            .gt(ActivityTheme::getStartTime, yesterday)
                    )
                    .update();// 更新配置组下面的主题
        }
        ConfigGroup db = new ConfigGroup();
        BeanUtils.copyProperties(param, db);
        if (!Objects.equals(allShop, 1)) {
            final List<Long> shopIds = param.getShopIds();
            if (!CollectionUtils.isEmpty(shopIds))
                db.setShopIds(this.processJsonString(JSON.toJSONString(shopIds)));
            final List<String> shopNames = param.getShopNames();
            if (!CollectionUtils.isEmpty(shopNames))
                db.setShopNames(this.processJsonString(JSON.toJSONString(shopNames)));
        }
        this.updateById(db);// 更新配置组
        List<EvlIndexVO> videoAndLive = param.getVideoAndLiveEvlIndex();// 父指标
        if (!CollectionUtils.isEmpty(videoAndLive)) {
            evlSettingService.saveEvlIndex(videoAndLive.stream()
                    .map(EvlIndexVO::toIndex)
                    .collect(Collectors.toList()));
        }
        List<EvlSubIndexVO> videoEvlSubIndexConfigs = param.getVideoEvlSubIndexConfigs();// 子指标(视频)
        if (!CollectionUtils.isEmpty(videoEvlSubIndexConfigs)) {
            evlSettingService.saveEvlSubIndex(videoEvlSubIndexConfigs.stream()
                    .map(EvlSubIndexVO::toIndex)
                    .collect(Collectors.toList()));
        }
        List<EvlSubIndexVO> liveEvlSubIndexConfigs = param.getLiveEvlSubIndexConfigs();// 子指标(直播)
        if (!CollectionUtils.isEmpty(liveEvlSubIndexConfigs)) {
            evlSettingService.saveEvlSubIndex(liveEvlSubIndexConfigs.stream()
                    .map(EvlSubIndexVO::toIndex)
                    .collect(Collectors.toList()));
        }
        List<ValidConfigNewVo.singleVo> videoValidConfigs = param.getVideoValidConfigs();// 有效性配置(视频)
        if (!CollectionUtils.isEmpty(videoValidConfigs)) {
            validConfigNewService.updateConfig(videoValidConfigs);
        }
        List<ValidConfigNewVo.singleVo> liveValidConfigs = param.getLiveValidConfigs();// 有效性配置(直播)
        if (!CollectionUtils.isEmpty(liveValidConfigs)) {
            validConfigNewService.updateConfig(liveValidConfigs);
        }
        List<GlobalConfig.GlobalConfigVo> globalConfigs = param.getGlobalConfigs();
        if (!CollectionUtils.isEmpty(globalConfigs)) {
            globalConfigService.updateConfig(globalConfigs);
        }
        return true;
    }

    /**
     * 查询本集团的配置组列表
     *
     * @param userId  用户id
     * @param groupId 集团id
     * @return
     */
    @Override
    public List<ConfigGroupVo> queryList(Long userId, Long groupId) {
        List<ConfigGroupVo> collect = this.lambdaQuery()
                .eq(ConfigGroup::getGroupId, groupId)
                .list()
                .stream()
                .map(item -> this.processVo(item, true))
                .collect(Collectors.toList());
        Map<Long, List<ConfigGroupVo>> collectMap = collect.stream()
                .collect(Collectors.groupingBy(ConfigGroupVo::getUserId));
        List<ConfigGroupVo> vos = new ArrayList<>(Optional
                .ofNullable(collectMap.get(userId))
                .orElse(new ArrayList<>())
        );// 尝试获取属于登录用户的配置组
        collectMap.remove(userId);// 将属于该用户的配置从map中移除
        collectMap.forEach((k, v) -> vos.addAll(v));// 将其他人的配置组加入vo
        return vos;
    }

    /**
     * 处理视图层
     *
     * @param configGroup 配置组实体
     * @param query       是否为查询
     * @return
     */
    private ConfigGroupVo processVo(ConfigGroup configGroup, boolean query) {
        List<EvlIndexVO> list = evlSettingService.list(configGroup.getId());
        EvlIndexVO videoEvlIndex = list.stream()
                .filter(item -> Objects.equals(item.getType(), BizTypeEnum.VIDEO))
                .collect(Collectors.toList())
                .get(0);
        EvlIndexVO liveEvlIndex = list.stream()
                .filter(item -> Objects.equals(item.getType(), BizTypeEnum.LIVE))
                .collect(Collectors.toList())
                .get(0);
        Long videoEvlIndexId = videoEvlIndex.getId();// 获取视频父指标
        Long liveEvlIndexId = liveEvlIndex.getId();// 获取直播父指标
        List<EvlSubIndexVO> videoSubIndexList = evlSettingService.sublist(videoEvlIndexId);
        List<EvlSubIndexVO> liveSubIndexList = evlSettingService.sublist(liveEvlIndexId);
        ValidConfigNewVo videoValidConfig = validConfigNewService.queryList(configGroup.getId(), BizTypeEnum.VIDEO.getValue());
        ValidConfigNewVo liveValidConfig = validConfigNewService.queryList(configGroup.getId(), BizTypeEnum.LIVE.getValue());
        validConfigNewService.queryList(configGroup.getId(), 3);
        List<GlobalConfig> globalConfigs = globalConfigService.queryList(configGroup.getId());
        if (!query) {
            List<ValidConfigNewVo.singleVo> configDetails = new ArrayList<>(videoValidConfig.getDetails());
            configDetails.addAll(liveValidConfig.getDetails());
            configGroup.setValidIds(this.processJsonString(JSON.toJSONString(configDetails
                    .stream()
                    .map(ValidConfigNewVo.singleVo::getId)
                    .collect(Collectors.toList())
            )));
            configGroup.setId(configGroup.getId());
            configGroup.setEvlVideoId(videoEvlIndexId);
            configGroup.setEvlLiveId(liveEvlIndexId);
            configGroup.setConfigIds(this.processJsonString(JSON.toJSONString(globalConfigs
                    .stream()
                    .map(GlobalConfig::getId)
                    .collect(Collectors.toList())
            )));
            this.updateById(configGroup);// 更新配置组
        }
        ConfigGroupVo vo = new ConfigGroupVo();
        BeanUtils.copyProperties(configGroup, vo);
        vo.setUserName(Optional.ofNullable(ehrRpc.getStaffBaseInfo(configGroup.getUserId()))
                .orElse(new StaffBaseInfoRpc())
                .getName()
        );
        vo.setVideoAndLiveEvlIndex(Arrays.asList(videoEvlIndex, liveEvlIndex));// 视频/直播父指标
        vo.setVideoEvlSubIndexConfigs(videoSubIndexList);// 视频子指标
        vo.setLiveEvlSubIndexConfigs(liveSubIndexList);// 直播子指标
        vo.setVideoValidConfigs(videoValidConfig.getDetails());// 视频有效配置
        vo.setLiveValidConfigs(liveValidConfig.getDetails());// 直播有效配置
        vo.setGlobalConfigs(globalConfigs.stream()
                .map(GlobalConfig::toVO)
                .collect(Collectors.toList())
        );// 封面图/话题相似度配置
        String shopIds = configGroup.getShopIds();
        if (StringUtils.hasText(shopIds))
            vo.setShopIds(Arrays.stream(shopIds
                    .split(","))
                    .map(Long::valueOf)
                    .collect(Collectors.toList())
            );
        String shopNames = configGroup.getShopNames();
        if (StringUtils.hasText(shopNames))
            vo.setShopNames(Arrays.stream(shopNames
                    .split(","))
                    .collect(Collectors.toList())
            );
        return vo;
    }

    /**
     * 祛除JSON字符串中的 [ ] "
     */
    private String processJsonString(String jsonString) {
        return jsonString
                .replace("[", "")
                .replace("]", "")
                .replace("\"", "");
    }

}