Newer
Older
huludao / src / main / java / com / newfiber / api / pc / service / impl / WxUserTemplateServiceImpl.java
package com.newfiber.api.pc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.newfiber.api.core.commons.CustomException;
import com.newfiber.api.core.commons.ResultCode;
import com.newfiber.api.pc.dao.WxUserTemplateMapper;
import com.newfiber.api.pc.dto.ConfigUserTemplate;
import com.newfiber.api.pc.dto.WxUserInfo;
import com.newfiber.api.pc.model.entity.WxUserTemplate;
import com.newfiber.api.pc.service.WxUserTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName WxUserTemplateServiceImpl
 * @Description TODO
 * @Author 张鸿志
 * @Date 2021年7月26日19:14:52 19:14
 * Version 1.0
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class WxUserTemplateServiceImpl extends ServiceImpl<WxUserTemplateMapper, WxUserTemplate> implements WxUserTemplateService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //该值与wechat-api项目里面配置的值保持一致
    private final static String REDISKEY = "wxUserTemplateKey";

    @Override
    public void config(ConfigUserTemplate configUserTemplate) {
        if(StringUtils.isEmpty(configUserTemplate)){
            throw new CustomException(ResultCode.PARAM_NULL);
        }
        EntityWrapper<WxUserTemplate> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("template_id",configUserTemplate.getTemplateId());
        //首先删除已经配置过的
        boolean delete = this.delete(entityWrapper);
        if(!delete){
            throw new CustomException(500,"源数据删除失败!");
        }
        //删除已经配置过的
        List<WxUserTemplate> list = new ArrayList<>();
        for (WxUserInfo info : configUserTemplate.getInfos()) {
            WxUserTemplate wxUserTemplate = new WxUserTemplate();
            wxUserTemplate.setOpenId(info.getOpenId());
            wxUserTemplate.setUserNo(info.getPhoneNumber());
            wxUserTemplate.setTemplateId(configUserTemplate.getTemplateId());
            list.add(wxUserTemplate);
        }

        boolean b = this.insertBatch(list);
        if(!b){
            throw new CustomException(500,"批量新增用户关联模板错误!");
        }
        //每次修改配置的时候就将内存中的数据清空,这样wechat-api里面获取数据就会一直是最新的
        if(stringRedisTemplate.hasKey(REDISKEY)){
            stringRedisTemplate.delete(REDISKEY);
        }
    }



}