ActivityThemeServiceImpl.java 18.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
package cn.fw.dalaran.service.data.impl;

import cn.fw.common.page.AppPage;
import cn.fw.common.web.auth.LoginAuthBean;
import cn.fw.dalaran.common.constants.DalaranConstants;
import cn.fw.dalaran.common.exception.BusinessException;
import cn.fw.dalaran.common.utils.DateUtil;
import cn.fw.dalaran.common.utils.ImageUtils;
import cn.fw.dalaran.dao.ActivityThemeDao;
import cn.fw.dalaran.domain.db.ActivityTheme;
import cn.fw.dalaran.domain.db.ConfigGroup;
import cn.fw.dalaran.domain.db.ThemeFile;
import cn.fw.dalaran.domain.enums.BizTypeEnum;
import cn.fw.dalaran.domain.enums.FileTypeEnum;
import cn.fw.dalaran.domain.enums.ValidLiveEnum;
import cn.fw.dalaran.domain.enums.ValidVideoEnum;
import cn.fw.dalaran.domain.param.ActivityThemePageParams;
import cn.fw.dalaran.domain.param.AddThemeCoverParams;
import cn.fw.dalaran.domain.param.AddThemeTopicParams;
import cn.fw.dalaran.domain.vo.ActivityThemeVo;
import cn.fw.dalaran.domain.vo.FileDesc;
import cn.fw.dalaran.domain.vo.ValidConfigNewVo;
import cn.fw.dalaran.rpc.erp.ErpTaskRpc;
import cn.fw.dalaran.rpc.erp.dto.TaskSetReq;
import cn.fw.dalaran.service.Common;
import cn.fw.dalaran.service.data.ActivityThemeService;
import cn.fw.dalaran.service.data.ConfigGroupService;
import cn.fw.dalaran.service.data.ThemeFileService;
import cn.fw.dalaran.service.data.ValidConfigNewService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;

/**
 * @author wmy3969
 * @version 1.0
 * @date 2022/1/8 17:30
 * @Description
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ActivityThemeServiceImpl extends ServiceImpl<ActivityThemeDao, ActivityTheme> implements ActivityThemeService {

    @Value("${file-server-addr}")
    private String serverAddr;
    private final ActivityThemeDao activityThemeDao;
    private final ConfigGroupService configGroupService;
    private final ThemeFileService themeFileService;
    private final ValidConfigNewService validConfigNewService;
    private final ErpTaskRpc erpTaskRpc;
    private final Common common;

    /**
     * 校验该活动主题生效时间段是否与已有的活动主题时间段重叠
     *
     * @param vo 需要保存的活动
     * @return 是否有重复
     */
    public boolean validThemeDateDuplicate(ActivityThemeVo vo) {
        final ConfigGroup configGroup = configGroupService.getById(vo.getConfigGroupId());
        final List<ActivityTheme> themeList = this.lambdaQuery()
                .ge(ActivityTheme::getGroupId, configGroup.getGroupId())
                .gt(ActivityTheme::getEndTime, new Date())
                .list();
        return themeList.stream()
                .anyMatch(item -> validDateOverlap(item.getStartTime(), item.getEndTime(), vo.getStartTime(), vo.getEndTime()) &&// 验证时间重叠
                        /*(Objects.equals(item.getAllShop(), 1) || vo.getAllShop() || validShopOverlap(Arrays.stream(item.getShopIds().split(",")).map(Long::valueOf).collect(Collectors.toList()), vo.getShopIds()))// 验证门店重叠*/
                        (Objects.equals(item.getAllShop(), 1) || configGroup.getAllShop() > 0 || validShopOverlap(Arrays.stream(item.getShopIds().split(",")).map(Long::valueOf).collect(Collectors.toList()), Arrays.stream(configGroup.getShopIds().split(",")).map(Long::valueOf).collect(Collectors.toList())))// 验证门店重叠
                );
    }

    /**
     * 验证门店是否重合
     *
     * @param shopIds1
     * @param shopIds2
     * @return
     */
    private boolean validShopOverlap(List<Long> shopIds1, List<Long> shopIds2) {
        if (Objects.equals(shopIds1.get(0), -1L) || Objects.equals(shopIds2.get(0), -1L)) {
            return true;
        } else {
            shopIds1.retainAll(shopIds2);
            return shopIds1.size() > 0;
        }
    }

    /**
     * 校验时间有无重叠
     *
     * @param startDate1 开始时间1
     * @param endDate1   结束时间1
     * @param startDate2 开始时间2
     * @param endDate2   结束时间2
     * @return 两个时间区间是否有重叠
     */
    public boolean validDateOverlap(Date startDate1, Date endDate1, Date startDate2, Date endDate2) {
        if (startDate1.after(endDate1) || startDate2.after(endDate2))
            throw new BusinessException("开始时间必须在结束时间之前");
        return !endDate2.before(startDate1) && !startDate2.after(endDate1) && !endDate1.before(startDate2) && !startDate1.after(endDate2);
    }

    /**
     * 保存主题
     *
     * @param themeVo 参数
     * @return
     */
    @Override
    @Transactional
    public boolean save(ActivityThemeVo themeVo) {
        ConfigGroup configGroup = configGroupService.getById(themeVo.getConfigGroupId());
        ActivityTheme activityTheme = ActivityThemeVo.toDB(themeVo);
        this.assembleConfigJson(themeVo.getConfigGroupId(), activityTheme);
        activityTheme.setConfigGroupId(configGroup.getId());
        activityTheme.setGroupId(configGroup.getGroupId());
        activityTheme.setAllShop(configGroup.getAllShop());
        activityTheme.setShopIds(configGroup.getShopIds());
        activityTheme.setShopNames(configGroup.getShopNames());
        activityTheme.setLogicDel(0);
        boolean result = this.save(activityTheme);
        if (result) {
            erpTaskRpc.setTask(TaskSetReq.<Long>builder()
                    .executeTime(new Date(activityTheme.getStartTime().getTime() + 24 * 3600 * 1000L))
                    .system(DalaranConstants.APPLICATION_NAME)
                    .param(activityTheme.getId())
                    .tag(DalaranConstants.INIT_ACCOUNT_STATUS)
                    .build()
            );
            this.saveFiles(activityTheme.getId(), themeVo.getAllFileDesc());
            this.downloadAndConvertCover(activityTheme, themeVo.getAllFileDesc());
        }
        return result;
    }

    /**
     * 增加话题
     *
     * @param params 增加话题带参
     * @return
     */
    @Override
    public boolean addTopic(AddThemeTopicParams params) {
        final ActivityTheme activityTheme = AddThemeTopicParams.toDB(params);
        final Long themeId = params.getThemeId();
        final ActivityTheme theme = this.getById(themeId);
        if (Objects.isNull(theme))
            throw new BusinessException(String.format("不存在id为: %s的活动主题", themeId));
        List<String> newTopic = params.getTopic().stream()
                .map(item -> {
                    String replace = item.replace("#", "");
                    return "#" + replace;
                })
                .collect(Collectors.toList());
        List<String> oldTopic = Arrays.asList(theme.getTopic().split(",").clone());
        ArrayList<String> result = new ArrayList<>(newTopic);
        result.retainAll(oldTopic);
        long timeSub = System.currentTimeMillis() - theme.getEndTime().getTime();
        if (timeSub > 24 * 3600 * 1000 + 1000)
            throw new BusinessException("活动已经结束数据抓取, 不能再增加话题");
        if (result.size() < oldTopic.size())
            throw new BusinessException("不允许删除原有话题");
        if (Objects.equals(newTopic.size(), oldTopic.size()))
            throw new BusinessException("未进行任何添加操作");
        return this.updateById(activityTheme);
    }

    /**
     * 增加封面
     *
     * @param params 增加封面带参
     * @return
     */
    @Override
    @Transactional
    public boolean addCover(AddThemeCoverParams params) {
        Long themeId = params.getThemeId();
        List<FileDesc> fileList = params.getCovers()
                .stream()
                .filter(item -> Objects.isNull(item.getId()))
                .peek(item -> item.setType(FileTypeEnum.THEME_COVER.getValue()))
                .collect(Collectors.toList());
        ActivityTheme theme = this.getById(themeId);
        long timeSub = System.currentTimeMillis() - theme.getEndTime().getTime();
        if (timeSub > 24 * 3600 * 1000 + 1000)
            throw new BusinessException("活动已经结束数据抓取, 不能再增加封面");
        this.saveFiles(themeId, fileList);
        this.downloadAndConvertCover(theme, fileList);
        return true;
    }

    /**
     * 查询集团话题列表
     *
     * @param groupId       集团id
     * @param configGroupId 所属配置组id
     * @return
     */
    @Override
    public List<ActivityThemeVo> list(Long groupId, Long configGroupId) {
        return this.lambdaQuery()
                .eq(ActivityTheme::getGroupId, groupId)
                .eq(ActivityTheme::getConfigGroupId, configGroupId)
                .orderByDesc(ActivityTheme::getId)
                .list()
                .stream()
                .map(ActivityTheme::toVO)
                .peek(item -> item.setAllFileDesc(Optional.ofNullable(
                        themeFileService
                                .lambdaQuery()
                                .eq(ThemeFile::getThemeId, item.getId())
                                .eq(ThemeFile::getType, FileTypeEnum.THEME_COVER.getValue())
                                .list())
                        .orElse(new ArrayList<>())
                        .stream()
                        .map(ThemeFile::toVO)
                        .collect(Collectors.toList()))
                )
                .collect(Collectors.toList());
    }

    /**
     * 分页查询活动主题列表
     *
     * @param groupId    集团id
     * @param pageParams 分页查询参数
     * @return
     */
    @Override
    public AppPage<ActivityThemeVo> pageList(Long groupId, ActivityThemePageParams pageParams) {
        Page<ActivityTheme> dbPageList = new Page<>(pageParams.getCurrent(), pageParams.getPageSize());
        dbPageList = this.page(dbPageList, Wrappers.<ActivityTheme>lambdaQuery()
                .eq(ActivityTheme::getGroupId, groupId)
                .eq(ActivityTheme::getConfigGroupId, pageParams.getConfigGroupId())
                .orderByDesc(ActivityTheme::getId));
        AppPage<ActivityThemeVo> pageList = AppPage.empty(pageParams);
        pageList.setTotal(dbPageList.getTotal());
        List<ActivityTheme> dbList = dbPageList.getRecords();
        if (CollectionUtils.isEmpty(dbList)) {
            return pageList;
        }
        pageList.setData(dbList.stream()
                .map(ActivityTheme::toVO)
                .peek(item -> item.setAllFileDesc(Optional.ofNullable(
                        themeFileService
                                .lambdaQuery()
                                .eq(ThemeFile::getThemeId, item.getId())
                                .eq(ThemeFile::getType, FileTypeEnum.THEME_COVER.getValue())
                                .list())
                        .orElse(new ArrayList<>())
                        .stream()
                        .map(ThemeFile::toVO)
                        .collect(Collectors.toList()))
                )
                .collect(Collectors.toList())
        );
        return pageList;
    }

    /**
     * 查询活动列表(指定月)
     *
     * @param user      当前登录用户
     * @param timeStamp 指定月之内的时间戳
     * @return 符合条件的活动列表
     */
    @Override
    public List<ActivityThemeVo> listByMonth(LoginAuthBean user, Long timeStamp) {
        Date startTime = DateUtil.getMonthFirstDay(DateUtil.getBeginInTime(new Date(timeStamp)));
        Date endTime = DateUtil.getMonthEndDay(DateUtil.getEndInTime(new Date(timeStamp)));
        Date yesterdayNow = new Date(System.currentTimeMillis() - 24 * 3600 * 1000L);
        if (endTime.compareTo(yesterdayNow) >= 0)
            endTime = yesterdayNow;
        Date finalEndTime = endTime;
        return this.lambdaQuery()
                .eq(ActivityTheme::getGroupId, user.getGroupId())
                .le(ActivityTheme::getStartTime, endTime)
                .ge(ActivityTheme::getEndTime, startTime)
                .list()
                .stream()
                .filter(item -> this.validDateOverlap(item.getStartTime(), item.getEndTime(), startTime, finalEndTime))
                .map(ActivityTheme::toVO)
                .peek(item -> item.setAllFileDesc(Optional.ofNullable(
                        themeFileService
                                .lambdaQuery()
                                .eq(ThemeFile::getThemeId, item.getId())
                                .eq(ThemeFile::getType, FileTypeEnum.THEME_COVER.getValue())
                                .list())
                        .orElse(new ArrayList<>())
                        .stream()
                        .map(ThemeFile::toVO)
                        .collect(Collectors.toList()))
                )
                .sorted(Comparator.comparing(ActivityThemeVo::getStartTime))
                .collect(Collectors.toList())
                ;
    }

    /**
     * 修改活动主题
     *
     * @param param 修改的参数封装
     */
    @Override
    public boolean alertTheme(ActivityTheme param) {
        return activityThemeDao.alertTheme(param);
    }

    /**
     * 组装配置
     *
     * @param configGroupId 配置组id
     * @param activityTheme 活动主题实体
     */
    private void assembleConfigJson(Long configGroupId, ActivityTheme activityTheme) {
        activityTheme.setValidConfigJson(this.getValidConfigJson(configGroupId));
    }

    /**
     * 获取配置组对应有效性配置
     *
     * @param configGroupId 配置组id
     */
    @Override
    public String getValidConfigJson(Long configGroupId) {
        final List<ValidConfigNewVo.singleVo> singleVoList = validConfigNewService.queryList(configGroupId, BizTypeEnum.VIDEO.getValue()).getDetails();
        singleVoList.addAll(validConfigNewService.queryList(configGroupId, BizTypeEnum.LIVE.getValue()).getDetails());
        final List<JSONObject> collect = singleVoList.stream().map(item -> {
            final JSONObject obj = new JSONObject();
            final Integer type = item.getType();
            final Integer indexType = item.getIndexType();
            obj.put("type", type);
            obj.put("indexType", indexType);
            obj.put("indexTypeName", Objects.equals(type, BizTypeEnum.VIDEO.getValue()) ? ValidVideoEnum.getNameByVale(indexType) : ValidLiveEnum.getNameByVale(indexType));
            obj.put("minValue", item.getMinValue());
            obj.put("valid", item.getValid());
            return obj;
        }).collect(Collectors.toList());
        return JSON.toJSONString(collect);
    }

    /**
     * 保存主题封面图信息
     *
     * @param themeId     主题id
     * @param allFileDesc 文件信息
     * @return
     */
    private boolean saveFiles(Long themeId, List<FileDesc> allFileDesc) {
        // 获取主题封面图信息
        List<ThemeFile> fileList = Optional.ofNullable(allFileDesc)
                .orElse(Lists.newArrayList())
                .stream()
                .map(item -> ThemeFile.builder()
                        .themeId(themeId)
                        .fileName(item.getFileName())
                        .fileId(item.getFid())
                        .fileType(item.getFileType())
                        .type(item.getType())
                        .build())
                .collect(Collectors.toList());
        if (fileList.size() > 0)
            return themeFileService.saveBatch(fileList);
        return true;
    }

    /**
     * 下载封面图并转换分辨率, 放入系统临时文件夹
     *
     * @param allFileDesc   所有文件信息
     * @param activityTheme 活动实体
     * @return
     */
    private void downloadAndConvertCover(ActivityTheme activityTheme, List<FileDesc> allFileDesc) {
        String tempDir = common.getActivityThemeCoverDir();
        allFileDesc.forEach(item -> {
            try {
                String fileId = item.getFid();
                File downloadFile = ImageUtils.convertFileByUrl(serverAddr + fileId, fileId);
                ImageUtils.modifyResolution1(downloadFile.getPath(),
                        tempDir + "activityTheme" + File.separator + activityTheme.getTheme() + File.separator + "settingCover",
                        "fw_theme_cover_" + fileId,
                        512, 512);
                boolean result = downloadFile.delete();
            } catch (Exception e) {
                log.error("下载转换封面图失败", e);
            }
        });
    }

    /**
     * 监听器, 收到消息后执行更新主题信息
     *
     * @param msg 消息
     */
    @Async
    @EventListener(String.class)
    public void updateActivityThemeValidConfigJsonMsg(String msg) {
        log.info(Thread.currentThread().getName() + " spring监听器在ActivityThemeServiceImpl.updateActivityThemeMsg()方法上成功收到消息: " + msg);
        final String[] split = msg.split("#");
        if (split.length < 2)
            return;
        LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
        final Long configGroupId = Long.valueOf(split[1]);
        final Date yesterday = new Date(System.currentTimeMillis() - 24 * 3600 * 1000L);
        final String validConfigJson = this.getValidConfigJson(configGroupId);
        this.lambdaUpdate()
                .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();
    }

}