ContactBizService.java 10.5 KB
package cn.fw.valhalla.service.bus.cust;

import cn.fw.common.exception.BusinessException;
import cn.fw.common.web.auth.PassportAuthBean;
import cn.fw.data.base.domain.common.Message;
import cn.fw.hermes.sdk.api.ImSendMessage;
import cn.fw.hermes.sdk.api.para.BusinessType;
import cn.fw.hermes.sdk.api.para.MessageBusinessType;
import cn.fw.hermes.sdk.api.para.MsgParamCondition;
import cn.fw.valhalla.common.utils.MobileUtil;
import cn.fw.valhalla.common.utils.StringUtils;
import cn.fw.valhalla.domain.db.customer.Customer;
import cn.fw.valhalla.domain.db.customer.CustomerBaseInfo;
import cn.fw.valhalla.domain.db.customer.CustomerContact;
import cn.fw.valhalla.domain.dto.CorrelationDto;
import cn.fw.valhalla.domain.enums.ContactRelationEnum;
import cn.fw.valhalla.domain.enums.ContactTypeEnum;
import cn.fw.valhalla.domain.vo.customer.CustomerContactVO;
import cn.fw.valhalla.rpc.member.MemberRpcService;
import cn.fw.valhalla.rpc.member.dto.MemberUserDTO;
import cn.fw.valhalla.sdk.result.CustomerContactDto;
import cn.fw.valhalla.service.data.CustomerBaseInfoService;
import cn.fw.valhalla.service.data.CustomerContactService;
import cn.fw.valhalla.service.data.CustomerService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static cn.fw.common.businessvalidator.Validator.BV;

/**
 * @author : kurisu
 * @className : ContactBizService
 * @description : 联系人服务
 * @date: 2020-08-27 15:29
 */
@Service
@Slf4j
public class ContactBizService {

    private final CustomerService customerService;
    private final CustomerBaseInfoService customerBaseInfoService;
    /**
     * 联系人服务
     */
    private final CustomerContactService contactsService;
    private final MemberRpcService memberRpcService;
    private final StringRedisTemplate redisTemplate;
    private final ImSendMessage imSendMessage;

    @Value("${spring.cache.custom.global-prefix}:customer:contact")
    @Getter
    private String keyPrefix;

    @Autowired
    public ContactBizService(final CustomerService customerService,
                             final CustomerBaseInfoService customerBaseInfoService,
                             final CustomerContactService contactsService,
                             final MemberRpcService memberRpcService,
                             final StringRedisTemplate redisTemplate,
                             final ImSendMessage imSendMessage) {
        this.customerService = customerService;
        this.customerBaseInfoService = customerBaseInfoService;
        this.contactsService = contactsService;
        this.memberRpcService = memberRpcService;
        this.redisTemplate = redisTemplate;
        this.imSendMessage = imSendMessage;
    }

    /**
     * 联系人列表
     *
     * @param customerId
     * @return
     */
    public List<CustomerContactVO> contactList(Long customerId) {
        final Customer cust = customerService.getById(customerId);
        if (Objects.isNull(cust)) {
            return Collections.emptyList();
        }
        CustomerBaseInfo baseInfo = customerBaseInfoService.queryById(cust.getBaseId());
        final List<CustomerContactVO> voList = new ArrayList<>();
        CustomerContactVO contactVO = new CustomerContactVO();
        contactVO.setId(customerId);
        contactVO.setCusId(customerId);
        contactVO.setType(ContactTypeEnum.OWNER.getValue());
        if (Objects.nonNull(baseInfo)) {
            contactVO.setName(baseInfo.getName());
            contactVO.setPhone(baseInfo.getMobile());
            contactVO.setMemberId(baseInfo.getMemberId());
            contactVO.setRelation(ContactRelationEnum.SELF.getValue());
            contactVO.setRegion(MobileUtil.attribution(baseInfo.getMobile()));
        }
        voList.add(contactVO);
        final List<CustomerContact> list = contactsService.list(Wrappers.<CustomerContact>lambdaQuery()
                .eq(CustomerContact::getCusId, customerId));
        if (CollectionUtils.isEmpty(list)) {
            return voList;
        }
        for (CustomerContact contact : list) {
            CustomerContactVO vo = new CustomerContactVO();
            BeanUtils.copyProperties(contact, vo);
            vo.setId(contact.getId());
            vo.setType(contact.getType().getValue());
            vo.setRelation(contact.getRelation().getValue());
            vo.setRegion(MobileUtil.attribution(contact.getPhone()));
            voList.add(vo);
        }
        return voList;
    }


    /**
     * 是否关联了档案
     *
     * @param userId
     * @param customerId
     * @return
     */
    public Boolean existCorrelation(final Long userId, final Long customerId) {
        return contactsService.count(Wrappers.<CustomerContact>lambdaQuery()
                .eq(CustomerContact::getCusId, customerId)
                .eq(CustomerContact::getMemberId, userId)) == 0;
    }

    /**
     * C端关联送修人
     *
     * @param user
     * @param correlationDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean correlation(PassportAuthBean user, CorrelationDto correlationDto) {
        Long customerId = correlationDto.getCustomerId();
        Customer customer = customerService.queryById(customerId);
        BV.notNull(customer, "档案信息异常");
        CustomerContact contact = new CustomerContact();
        CustomerContact existContact = contactsService.getOne(Wrappers.<CustomerContact>lambdaQuery()
                .eq(CustomerContact::getCusId, customerId)
                .eq(CustomerContact::getMemberId, user.getUserId())
                .last("limit 1"));
        if (existContact != null) {
            contact.setId(existContact.getId());
        }
        contact.setCusId(customerId);
        MemberUserDTO userDto = memberRpcService.user(user.getUserId());
        BV.notNull(customer, "用户信息查询失败");
        String finalName = StringUtils.isValid(correlationDto.getName()) ? correlationDto.getName() : userDto.getNickName();
        contact.setName(finalName);
        contact.setPhone(userDto.getPhone());
        contact.setMemberId(userDto.getUserId());
        contact.setRelation(ContactRelationEnum.ofValue(correlationDto.getRelation()));
        contact.setType(ContactTypeEnum.SENDER);
        contact.setCreateTime(new Date());
        contact.setUpdateTime(new Date());
        boolean sucess = contactsService.saveOrUpdate(contact);
        String key = generateKey(customerId, correlationDto.getPlateNo(), correlationDto.getShopId());
        String data = JSONObject.toJSONString(contact);
        setToCache(key, data, 15 * 60);
        if (Objects.nonNull(correlationDto.getAdviserId())) {
            sendMsg(correlationDto.getAdviserId(), data);
        }
        return sucess;
    }

    /**
     * 查询接车是扫码的送修人
     *
     * @param customerId
     * @param plateNo
     * @param shopId
     * @return
     */
    public CustomerContactDto queryReceptioner(final Long customerId, final String plateNo, final Long shopId) {
        String key = generateKey(customerId, plateNo, shopId);
        String cache = getFromCache(key);
        CustomerContact contact = JSONObject.parseObject(cache, CustomerContact.class);
        if (Objects.nonNull(contact)) {
            return new CustomerContactDto(contact.getId(), contact.getCusId(), contact.getName(), contact.getPhone(), contact.getMemberId());
        }
        return null;
    }

    /**
     * 查询接车是扫码的送修人
     *
     * @param customerId
     * @param memberId
     * @return
     */
    public CustomerContactDto queryContactInfo(final Long customerId, final Long memberId) {
        CustomerContact contact = contactsService.getOne(Wrappers.<CustomerContact>lambdaQuery()
                .eq(CustomerContact::getMemberId, memberId)
                .eq(CustomerContact::getCusId, customerId)
                .last("limit 1")
        );
        if (Objects.nonNull(contact)) {
            return new CustomerContactDto(contact.getId(), contact.getCusId(), contact.getName(), contact.getPhone(), contact.getMemberId());
        }
        return null;
    }

    private String getFromCache(final String key) {
        String json = null;
        try {
            BoundValueOperations<String, String> ops = redisTemplate.boundValueOps(key);
            json = ops.get();
        } catch (Exception e) {
            log.error("CustomerManagerImpl  从缓存获取联系人信息失败", e);
        }
        return json;
    }

    private void setToCache(final String key, final String value, long timeout) {
        try {
            redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("CustomerManagerImpl  缓存联系人信息失败", e);
            throw new BusinessException("联系人信息保存失败,请重试");
        }
    }

    private String generateKey(final Long customerId, final String plateNo, final Long shopId) {
        BV.isTrue(Objects.nonNull(customerId), "customerId cannot be null");
        BV.isTrue(StringUtils.isValid(plateNo), "plateNo cannot be null");
        BV.isTrue(Objects.nonNull(shopId), "shopId cannot be null");

        return String.format("%s:%s:%s:%s", getKeyPrefix(), shopId, customerId, plateNo);
    }

    private void sendMsg(Long targetUserId, String data) {
        try {
            String text = "新增联系人通知";
            Map<String, Object> ext = new HashMap<>(2);
            ext.put("type", MessageBusinessType.SENDER_NOTICE.getMsg());
            ext.put("data", data);
            final MsgParamCondition msgPara = MsgParamCondition.getCustomMsg(text, "", ext, 0, targetUserId, false)
                    .setBusinessType(BusinessType.INTERNAL_NOTIFICATION)
                    .build();
            final Message<Boolean> msg = imSendMessage.synSendMsg(msgPara);
            log.info("给[{}]推送im消息结果:[{}]", targetUserId, msg.getResult());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}