SyncCustomerService.java 11.7 KB
package cn.com.glsx.entmicro.service;/**
 * @author zhouhaibao
 * @date 2021/12/11
 */

import cn.com.glsx.entmicro.constants.Constants;
import cn.com.glsx.entmicro.entity.CustomerMerge;
import cn.com.glsx.entmicro.mapper.CustomerMapper;
import cn.com.glsx.entmicro.mapper.CustomerMergeMapper;
import cn.com.glsx.entmicro.mapper.EntmicroCustomerFollowMapper;
import cn.com.glsx.entmicro.model.CustomerMagicRopResponse;
import cn.com.glsx.entmicro.model.MerchantRopResponse;
import cn.com.glsx.entmicro.model.request.MagicDynamicInfoRequest;
import cn.com.glsx.entmicro.model.request.MagicDynamicRequest;
import cn.com.glsx.entmicro.model.response.CustomerInfoResponse;
import cn.com.glsx.entmicro.service.cache.RedisCacheService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhouhaibao
 * @version 1.0
 * @description: TODO
 * @date 2021/12/11 12:15
 */
@Slf4j
@Component
public class SyncCustomerService {

    @Autowired
    private RopCommonServie ropCommonServie;

    @Autowired
    private MerchantService merchantService;

    @Value("${addway.magic}")
    private Integer addwayMagic;

    @Autowired
    private Environment environment;

    @Autowired
    private CustomerMergeMapper customerMergeMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Resource
    private EntmicroCustomerFollowMapper entmicroCustomerFollowMapper;

    @Resource
    private ScrmDataCubeJoinRestCloudService scrmDataCubeJoinRestCloudService;

    @Resource
    private RedisCacheService redisCacheService;

    private static final String SYNC_CUSTOMER_REMARK_TO_CDP_CACHE = "sync_customer_remark_to_cdp_cache";

    public void syncCustomerRemarkToCdp() {
        Date updateTime = null;
        try {
            Object cache = redisCacheService.getCache(SYNC_CUSTOMER_REMARK_TO_CDP_CACHE);
            if (cache != null) {
                updateTime = (Date) cache;
            }
            redisCacheService.setCache(SYNC_CUSTOMER_REMARK_TO_CDP_CACHE, new Date(), 60 * 60 * 24 * 7L);
        } catch (Exception e) {
            log.warn(e.getMessage(), e);
        }
        String merchants = environment.getProperty("scrm_syncCustomerTypeTag_merchants");
        List<Integer> merchantIdList = Arrays.stream(merchants.split(",")).map(Integer::valueOf).collect(Collectors.toList());
        List<Map<String, Object>> maps = entmicroCustomerFollowMapper.selectCustomerFollowRemark(updateTime, merchantIdList);
        log.info("syncCustomerRemarkToCdp data:{}", maps);
        if (CollectionUtils.isEmpty(maps)) {
            log.warn("maps is empty");
            return;
        }
        scrmDataCubeJoinRestCloudService.reportDataProcess(JSON.toJSONString(maps));
    }


    /**
     * 同步数据到大数据,取消异步操作;异步操作交给组件实现({@link cn.com.glsx.entmicro.manager.CustomerDetailMagicAsyncComponent})
     *
     * @param magicDynamicRequest
     */
    public void syncBatchCustomer(MagicDynamicRequest magicDynamicRequest) {
        List<MagicDynamicInfoRequest> customers = magicDynamicRequest.getCustomers();
        if (!CollectionUtils.isEmpty(customers)) {
            String customerBatchCount = environment.getProperty("customer.batchCount");
            List<List<MagicDynamicInfoRequest>> partition = ListUtils.partition(customers, Integer.parseInt(customerBatchCount));
            partition.forEach(index -> {
                magicDynamicRequest.setCustomers(index);
                syncBatchCustomerData(magicDynamicRequest, 0);
            });
        }
    }


    /**
     * 批量同步数仓、企微魔方、小程序客户到大数据
     *
     * @param magicDynamicRequest
     * @param merChangeStatus
     */
    public void syncBatchCustomerData(MagicDynamicRequest magicDynamicRequest, Integer merChangeStatus) {
        log.info("数仓客户同步到大数据: {}", JSONArray.toJSONString(magicDynamicRequest));
        //渠道号
        MerchantRopResponse merchantByMerchantNo = merchantService.findMerchantByMerchantNo(magicDynamicRequest.getMerchantId());
        Integer channelId = merchantByMerchantNo.getChannelId();
        // 门店(商户)变更状态 0-正常 1-门店已变更
        String jsonStr = JSONObject.toJSONStringWithDateFormat(magicDynamicRequest, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);
        List<CustomerMagicRopResponse> customerMagicRopResponses = ropCommonServie.syncEntCubeImp(magicDynamicRequest, channelId, addwayMagic);
        if (!CollectionUtils.isEmpty(customerMagicRopResponses)) {
            //客戶來源赋值
            List<MagicDynamicInfoRequest> customers = magicDynamicRequest.getCustomers();
            for (CustomerMagicRopResponse customerMagicRopRespons : customerMagicRopResponses) {
                for (MagicDynamicInfoRequest customer : customers) {
                    if (null == customerMagicRopRespons.getCustomerId() || null == customer.getCustomerId()) {
                        continue;
                    } else if (customerMagicRopRespons.getCustomerId().equals(customer.getCustomerId())) {
                        customerMagicRopRespons.setAddWay(customer.getAddWay());
                        break;
                    }
                }
            }
            //批量更新oneid
            log.info("魔方客户更新oneId: {}", JSONArray.toJSONString(customerMagicRopResponses));
            customerMapper.batchUpdateOneId(customerMagicRopResponses);

            List<String> oneIds = customerMagicRopResponses.stream().map(CustomerMagicRopResponse::getOneId).collect(Collectors.toList());
            //构建参数
            customerMerge(customerMagicRopResponses, magicDynamicRequest);

            Map<String, CustomerInfoResponse> customerExists = customerMergeMapper.getCustomerByOneIds(oneIds, magicDynamicRequest.getMerchantId());

            if (null != customerExists && customerExists.size() > 0) {
                List<CustomerMerge> addList = new ArrayList<>();
                List<CustomerMerge> updateList = new ArrayList<>();

                for (CustomerMagicRopResponse customerMagicRopRespons : customerMagicRopResponses) {
                    String oneId = customerMagicRopRespons.getOneId();
                    if (StringUtils.isEmpty(oneId)) {
                        continue;
                    }

                    if (customerExists.containsKey(oneId)) {
                        CustomerMerge customerMerge = buildCustomerMerge(customerMagicRopRespons, false);
                        CustomerInfoResponse customerInfoResponse = customerExists.get(oneId);
                        Integer id = customerInfoResponse.getId();
                        if (null != id) {
                            customerMerge.setId(id);
                            updateList.add(customerMerge);
                        }
                    } else {
                        CustomerMerge customerMerge = buildCustomerMerge(customerMagicRopRespons, true);
                        addList.add(customerMerge);
                    }
                }

                //更新merge客户表
                if (!CollectionUtils.isEmpty(updateList)) {
                    log.info("数仓客户更新merge数据: {}", updateList);
                    customerMergeMapper.batchUpdate(updateList);
                }

                //新增merge客户表
                if (!CollectionUtils.isEmpty(addList)) {
                    log.info("数仓客户新增merge数据: {}", addList);
                    customerMergeMapper.insertList(addList);
                }
            } else {
                //新增merge客户表
                List<CustomerMerge> custsAdd = customerMagicRopResponses.stream().map(c -> buildCustomerMerge(c, true)).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(custsAdd)) {
                    log.info("新增客户size{}, 数仓客户新增merge数据: {}", custsAdd.size(), JSONArray.toJSONString(custsAdd));
                    customerMergeMapper.insertList(custsAdd);
                }
            }
        }
    }

    private boolean verifyAddWay(Integer nowAddWay, Integer initialAddWay) {
        nowAddWay = nowAddWay == null ? 0 : nowAddWay;
        initialAddWay = initialAddWay == null ? 0 : initialAddWay;
        // 初始来源是魔方,则当前来源为魔方才能修改
        if (initialAddWay == 101 && nowAddWay != 101) {
            return true;
            // 初始来源非魔方,则当前来源为魔方和保单才能修改
        } else if (initialAddWay != 101 && nowAddWay != 101 && nowAddWay != 103) {
            return true;
        }
        return false;
    }

    /**
     * 客户优先级合并
     *
     * @param customerMagicRopResponses 返回的客户
     * @param magicDynamicRequest       魔方导入客户
     */
    private void customerMerge(List<CustomerMagicRopResponse> customerMagicRopResponses, MagicDynamicRequest magicDynamicRequest) {
        List<MagicDynamicInfoRequest> customers = magicDynamicRequest.getCustomers();
        Map<Integer, MagicDynamicInfoRequest> customer_phone = customers.stream().collect(Collectors.toMap(MagicDynamicInfoRequest::getCustomerId, Function.identity()));
        customerMagicRopResponses.forEach(index -> {
            MagicDynamicInfoRequest customerMagicRopRequest = customer_phone.get(index.getCustomerId());
            if (customerMagicRopRequest != null) {
                Map<String, Object> custAttr = customerMagicRopRequest.getCustAttr();
                if (custAttr.get("customer_name") != null) {
                    index.setCustomerName(custAttr.get("customer_name") + "");
                }
                if (custAttr.get("customer_idcard_no") != null) {
                    index.setIdCard(custAttr.get("customer_idcard_no") + "");
                }
                index.setCustomerPhone(custAttr.get("customer_phone") + "");
                Object customerSex = custAttr.get("customer_sex");
                if (customerSex != null) {
                    index.setCustomerSex(Integer.parseInt(customerSex + ""));
                }
            }
        });
    }

    /**
     * 构建魔方合并表数据
     *
     * @param res
     * @param isAdd
     * @return
     */
    private CustomerMerge buildCustomerMerge(CustomerMagicRopResponse res, boolean isAdd) {
        CustomerMerge customerMerge = new CustomerMerge();
        customerMerge.setCustomerPhone(res.getCustomerPhone());
        customerMerge.setCustomerName(res.getCustomerName());
        customerMerge.setIdCard(res.getIdCard());
        customerMerge.setCustomerSex(res.getCustomerSex());
        customerMerge.setAddWay(res.getAddWay());
        customerMerge.setMerchantId(res.getMerchantId());
        if (isAdd) {
            //新增
            customerMerge.setOneId(res.getOneId());
            customerMerge.setCreatedTime(new Date());
            customerMerge.setDelFlag(Constants.NORMAL_FLAG);
            //正常
            customerMerge.setStatus(0);
            //未加入企微
            customerMerge.setIsJoin(0);
        }
        log.info("构建魔方合并表数据:{}, 构建后数据: {}", JSONArray.toJSONString(res), JSONArray.toJSONString(customerMerge));
        return customerMerge;
    }
}