MassSenderComponent.java 19 KB
package cn.com.glsx.entmicro.manager;

import cn.com.glsx.entmicro.constants.Constants;
import cn.com.glsx.entmicro.constants.DracConstant;
import cn.com.glsx.entmicro.converter.QyMsgAttachmentConvert;
import cn.com.glsx.entmicro.dto.DracScrmWelcomeConfigDTO;
import cn.com.glsx.entmicro.entity.EntmicroStaffDepartRelation;
import cn.com.glsx.entmicro.entity.Mass;
import cn.com.glsx.entmicro.entity.MassDetailCustomer;
import cn.com.glsx.entmicro.entity.MassDetailStaff;
import cn.com.glsx.entmicro.mapper.EntmicroAuthorizeMapper;
import cn.com.glsx.entmicro.model.MassBuryingPointParameter;
import cn.com.glsx.entmicro.model.response.EntmicroStaffResponse;
import cn.com.glsx.entmicro.model.response.MassDetailStaffResponse;
import cn.com.glsx.entmicro.model.response.MassResponse;
import cn.com.glsx.entmicro.service.*;
import cn.com.glsx.entmicro.service.common.CommonService;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.scrm.wechat.dto.workwechat.externalmsg.WorkWechatExternalContactMsgAttachmentDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.externalmsg.request.AddWorkWechatExternalContactMsgTemplateRequestDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.externalmsg.response.AddWorkWechatExternalContactMsgTemplateResponseDTO;
import cn.com.glsx.scrm.wechat.remote.WorkWechatExternalContactMsgRemote;
import cn.hutool.core.text.UnicodeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author wangxw
 * @version 1.0.0
 * @ClassName MassSenderComponent.java
 * @description: 客户群发的发送组件
 * @createTime 2021年11月14日 16:35:00
 */
@Slf4j
@Component
public class MassSenderComponent {

    @Autowired
    private MassService massService;

    @Autowired
    private MassDetailStaffService massDetailStaffService;

    @Autowired
    private MassDetailCustomerService massDetailCustomerService;

    @Autowired
    private EntmicroStaffDepartRelationService entmicroStaffDepartRelationService;

    @Autowired
    private WorkWechatExternalContactMsgRemote workWechatExternalContactMsgRemote;

    @Autowired
    private CommonService commonService;

    @Autowired
    private DracScrmWelcomeConfigService dracScrmWelcomeConfigService;

    @Autowired
    private EntmicroStaffService entmicroStaffService;

    @Resource
    private EntmicroAuthorizeMapper entmicroAuthorizeMapper;

    /**
     * 执行 客户群发
     *
     * @param massId
     * @return
     */
    @Async
    public Boolean executorMassSender(Integer massId, List<MassBuryingPointParameter> parameterList) {
        MassResponse massDetail = massService.getDetailSingle(massId);
        if (massDetail.getCrowdFunding() != null && massDetail.getCrowdFunding()) {
            MassDetailStaffResponse staff = massDetail.getUserList().get(0);
            List<EntmicroStaffResponse> listByUserIds = entmicroStaffService.getListByUserIds(Arrays.asList(staff.getQyUserId()), massDetail.getMerchantId());
            if (listByUserIds == null) {
                log.info("群发查询执行员工失败!massId:{}", massId);
                return false;
            }
            EntmicroStaffResponse staffResponse = listByUserIds.get(0);
            parameterList = new ArrayList<>();
            buildParameterList(parameterList, staffResponse);
            String croPid = getCroPid(massDetail.getMerchantId());
            if (croPid != null) {
                parameterList.add(new MassBuryingPointParameter("corpId", croPid));
            }
        }
        if (massDetail.getType() == Constants.MASS_TYPE_CUSTOMER) {
            // 客户 - 群发
            senderCustomerMessage(massDetail, Constants.CHAT_TYPE_SINGLE, parameterList);
        } else if (massDetail.getType() == Constants.MASS_TYPE_GROUP) {
            // 客户群 - 群发
            senderCustomerMessage(massDetail, Constants.CHAT_TYPE_GROUP, parameterList);
        }
        executorTask(massDetail);
        return true;
    }

    private String getCroPid(Integer merchantId) {
        Integer merchantNo = entmicroStaffService.findSupMerchantNo(merchantId);
        if (merchantNo == null) {
            return "";
        }
        return entmicroAuthorizeMapper.findEntmicroId(merchantNo);
    }

    private void buildParameterList(List<MassBuryingPointParameter> parameterList, EntmicroStaffResponse staffResponse) {
        if (staffResponse.getMerchantId() != null) {
            parameterList.add(new MassBuryingPointParameter("merchantId", staffResponse.getMerchantId()));
        }
        parameterList.add(new MassBuryingPointParameter("shareStaffType", 2));
        if (staffResponse.getStaffPhone() != null) {
            parameterList.add(new MassBuryingPointParameter("userPhone", staffResponse.getStaffPhone()));
        }
        if (staffResponse.getThumbAvatar() != null) {
            parameterList.add(new MassBuryingPointParameter("shareStaffImageUrl", staffResponse.getThumbAvatar()));
        }
        if (!StringUtils.isEmpty(staffResponse.getStaffName())) {
            parameterList.add(new MassBuryingPointParameter("shareStaffName", UnicodeUtil.toUnicode(staffResponse.getStaffName()).replace("\\u", "@")));
        } else {
            parameterList.add(new MassBuryingPointParameter("shareStaffName", staffResponse.getStaffName()));
        }
        if (staffResponse.getUserOneid() != null) {
            parameterList.add(new MassBuryingPointParameter("shareStaffUuid", staffResponse.getUserOneid()));
        }
    }

    private void executorTask(MassResponse massDetail) {
        try {
            Mass mass = new Mass();
            BeanUtils.copyProperties(massDetail, mass);
            List<MassDetailStaff> massDetailStaffs = canAddTask(massDetail.getId());
            if (massDetailStaffs != null && !massDetailStaffs.isEmpty()) {
                // 增加客户任务
                log.info("增加客户任务入参:saveMass:{},massDetailStaffs:{}", JSON.toJSONString(mass), massDetailStaffs);
                addBatchTask(mass, massDetailStaffs);
            } else {
                log.info("此次群发未查询到符合条件的员工详情,所以不创建客户任务。");
            }
        } catch (BeansException e) {
            log.info("群发创建任务异常:{}", e);
        }
    }

    private void senderCustomerMessage(MassResponse massDetail, String chatType, List<MassBuryingPointParameter> parameterList) {
        AddWorkWechatExternalContactMsgTemplateRequestDTO sendWorkDTO = new AddWorkWechatExternalContactMsgTemplateRequestDTO();
        sendWorkDTO.setChatType(chatType);

        List<DracScrmWelcomeConfigDTO> scrmWelcomeConfigDTOList = null;
        if (parameterList == null || parameterList.isEmpty()) {
            parameterList = new ArrayList<>();
        }
        MassBuryingPointParameter parameter = new MassBuryingPointParameter("mass_id", massDetail.getId());
        parameterList.add(parameter);
        scrmWelcomeConfigDTOList = dracScrmWelcomeConfigService.getQySendContactDataList(massDetail.getUuid(), DracConstant.WelcomeDesc.MASS, null, null, null, null, parameterList);
        //附件数据封装
        if (!CollectionUtils.isEmpty(scrmWelcomeConfigDTOList)) {
            List<WorkWechatExternalContactMsgAttachmentDTO> attachmentDTOList = new ArrayList<>();
            for (DracScrmWelcomeConfigDTO dracWelcomeConfig : scrmWelcomeConfigDTOList) {
                if (dracWelcomeConfig.getAttType().equals(DracConstant.AttType.TEXT)) {
                    sendWorkDTO.setText(QyMsgAttachmentConvert.convertTextAttachment(dracWelcomeConfig));
                } else {
                    attachmentDTOList.add(QyMsgAttachmentConvert.convertAttachment(dracWelcomeConfig));
                }
            }
            sendWorkDTO.setAttachments(attachmentDTOList);
        }

        Integer supMerchantNo = null;
        if (massDetail.getMerchantId() != null) {
            supMerchantNo = entmicroStaffService.findSupMerchantNo(massDetail.getMerchantId());
        }
        if (supMerchantNo == null) {
            log.info("根据商户号查询授权商户号为空!");
            massDetailStaffService.updateQyMessageSenderStatusByMassId(massDetail.getId(), Constants.MASS_DETAIL_STAFF_STATUS.SEND_ERROR);
            //更新群发消息状态为发送失败
            massService.updateMassData(massDetail.getId(), DracConstant.MassStatus.SEND_FAILURE);
            return;
        }

        // 为每个员工发送消息
        for (MassDetailStaffResponse staffResponse : massDetail.getUserList()) {
            if (sendWorkDTO.getChatType().equals(Constants.CHAT_TYPE_SINGLE)) {
                List<MassDetailCustomer> customerList = massDetailCustomerService.getMassDetailCustomerListByRelationId(staffResponse.getId());
                if (CollectionUtils.isEmpty(customerList)) {
                    log.info("send qywechat work message customerlist is empty. staffInfo:{}", JSONObject.toJSONString(staffResponse));
                    //群发客户列表为空,则默认发送失败
                    massDetailStaffService.updateQyMessageSenderResultStatus(staffResponse.getId(), Constants.MASS_DETAIL_STAFF_STATUS.SEND_ERROR);
                    continue;
                }
                sendWorkDTO.setExternalUserIdList(buildCustomerUserIds(customerList));
            }

            sendWorkDTO.setSender(staffResponse.getQyUserId());
            sendWorkDTO.setMerchantId(supMerchantNo);
            log.info("群发参数详情:{}", JSONObject.toJSONString(sendWorkDTO));
            RpcResponse<AddWorkWechatExternalContactMsgTemplateResponseDTO> sendRpcResponse = workWechatExternalContactMsgRemote.addMsgTemplate(sendWorkDTO);
            log.info("send qy wechatmessage staffid:{}, sendResult:{}", JSONObject.toJSONString(staffResponse.getStaffId()), JSONObject.toJSONString(sendRpcResponse));
            if (sendRpcResponse.isSuccess() && sendRpcResponse.getResult() != null && sendRpcResponse.getResult().getMsgId() != null) {
                String msgId = sendRpcResponse.getResult().getMsgId();
                massDetailStaffService.updateQyMessageSenderResult(staffResponse.getId(), msgId);
                List<String> failList = sendRpcResponse.getResult().getFailList();
                if (failList != null && !failList.isEmpty()) {
                    massDetailCustomerService.updateFailListCustomer(failList, staffResponse);
                }
            } else {
                log.info("------------群发失败:staffid:{}", staffResponse.getStaffId());
                massDetailStaffService.updateQyMessageSenderResultStatus(staffResponse.getId(), Constants.MASS_DETAIL_STAFF_STATUS.SEND_ERROR);
            }
        }
        MassResponse baseMass = massService.getBaseMass(massDetail.getId());
        if (baseMass != null && (baseMass.getStatus().equals(DracConstant.MassStatus.SUCCESS) || baseMass.getStatus().equals(DracConstant.MassStatus.UNSEND))) {
            //更新群发消息状态为已发送
            massService.updateMassData(massDetail.getId(), DracConstant.MassStatus.SENDER);
        }

    }

    private List<String> buildCustomerUserIds(List<MassDetailCustomer> massDetailCustomerList) {
        List<String> userIdList = new ArrayList<>();
        for (MassDetailCustomer customerInfo : massDetailCustomerList) {
            userIdList.add(customerInfo.getExternalUserId());
            if (userIdList.size() >= 9999) {//限制客户数量为9999
                return userIdList;
            }
        }
        return userIdList;
    }

//    /**
//     * 客户群发 - 增加客户任务
//     *
//     * @param uuid
//     * @param userIdList
//     * @param merchantId
//     * @param massType
//     */
//    public void addBatchTask(String uuid, String userIdList, Integer merchantId, int massType) {
//        // 3:客户群发,4:客户群群发
//        int taskType = (massType == Constants.MASS_TYPE_CUSTOMER) ? 3 : 4;
//        List<Integer> staffIdList = getStaffIdList(userIdList);
//        List<EntmicroStaffDepartRelation> entmicroStaffDepartRelationList = entmicroStaffDepartRelationService.findStaffUidDepartForMerchant(staffIdList, merchantId);
//        if (CollectionUtils.isEmpty(entmicroStaffDepartRelationList)) {
//            log.info("send task batchtask staff department relation empty uuid:{}", uuid);
//            return;
//        }
//        List<String> userUidList = entmicroStaffDepartRelationList.stream().map(EntmicroStaffDepartRelation::getUserOneid).filter(Objects::nonNull).collect(Collectors.toList());
//        if (userUidList.isEmpty()) {
//            log.info("可创建任务的用户列表为空,不创建任务-------------------------");
//            return;
//        }
//        log.info("uuid:{} ------- userUidList:{}------ merchantId:{} -------taskType:{}", uuid, userUidList, String.valueOf(merchantId), taskType);
//        commonService.addBatchTask(uuid, userUidList, String.valueOf(merchantId), taskType);
//    }

    /**
     * 客户群发 - 增加客户任务
     */
    public void addBatchTask(Mass mass, List<MassDetailStaff> massDetailStaffs) {
        // 3:客户群发,4:客户群群发
        int taskType = (mass.getType() == Constants.MASS_TYPE_CUSTOMER) ? 3 : 4;
        List<Integer> staffIdList = massDetailStaffs.stream().map(MassDetailStaff::getStaffId).collect(Collectors.toList());
        List<EntmicroStaffDepartRelation> entmicroStaffDepartRelationList = entmicroStaffDepartRelationService.findStaffUidDepartForMerchant(staffIdList, mass.getMerchantId());
        if (CollectionUtils.isEmpty(entmicroStaffDepartRelationList)) {
            log.info("send task batchtask staff department relation empty uuid:{}", mass.getUuid());
            return;
        }

        List<String> userUidList = entmicroStaffDepartRelationList.stream().map(EntmicroStaffDepartRelation::getUserOneid).filter(Objects::nonNull).collect(Collectors.toList());
        if (userUidList.isEmpty()) {
            log.info("可创建任务的用户列表为空,不创建任务-------------staffIdList:{}------------", staffIdList);
            return;
        }
        log.info("uuid:{} ------- userUidList:{}------ merchantId:{} -------taskType:{}", mass.getUuid(), userUidList, String.valueOf(mass.getMerchantId()), taskType);
        commonService.addBatchTask(mass.getUuid(), userUidList, String.valueOf(mass.getMerchantId()), taskType);
    }


    /**
     * 客户群发 - 增加客户任务(消费kafka消息时调用)
     *
     * @param uuid
     * @param staffIdList
     * @param merchantId
     * @param massType
     */
    public void addBatchTaskForKafkaResp(String uuid, List<Integer> staffIdList, Integer merchantId, int massType) {
        // 3:客户群发,4:客户群群发
        int taskType = (massType == Constants.MASS_TYPE_CUSTOMER) ? 3 : 4;
        List<EntmicroStaffDepartRelation> entmicroStaffDepartRelationList = entmicroStaffDepartRelationService.findStaffUidDepartForMerchant(staffIdList, merchantId);
        if (CollectionUtils.isEmpty(entmicroStaffDepartRelationList)) {
            log.info("send task batchtask staff department relation empty uuid:{}", uuid);
            return;
        }

        List<String> userUidList = entmicroStaffDepartRelationList.stream().map(EntmicroStaffDepartRelation::getUserOneid).filter(Objects::nonNull).collect(Collectors.toList());
        if (userUidList.isEmpty()) {
            log.info("可创建任务的用户列表为空,不创建任务-------------------------");
            return;
        }
        log.info("uuid:{} ------- userUidList:{}------ merchantId:{} -------taskType:{}", uuid, userUidList, String.valueOf(merchantId), taskType);
        commonService.addBatchTask(uuid, userUidList, String.valueOf(merchantId), taskType);
    }

//    /**
//     * 客户群发 - 增加客户任务(消费kafka消息时调用)
//     *
//     * @param uuid
//     * @param staffIdList
//     * @param merchantId
//     * @param massType
//     */
//    public void addBatchTaskForKafkaResp(String uuid, List<Integer> staffIdList, Integer merchantId, int massType) {
//        // 3:客户群发,4:客户群群发
//        int taskType = (massType == Constants.MASS_TYPE_CUSTOMER) ? 3 : 4;
//        List<EntmicroStaffDepartRelation> entmicroStaffDepartRelationList = entmicroStaffDepartRelationService.findStaffUidDepartForMerchant(staffIdList, merchantId);
//        if (CollectionUtils.isEmpty(entmicroStaffDepartRelationList)) {
//            log.info("send task batchtask staff department relation empty uuid:{}", uuid);
//            return;
//        }
//
//        List<String> userUidList = entmicroStaffDepartRelationList.stream().map(EntmicroStaffDepartRelation::getUserOneid).filter(Objects::nonNull).collect(Collectors.toList());
//        if (userUidList.isEmpty()) {
//            log.info("可创建任务的用户列表为空,不创建任务-------------------------");
//            return;
//        }
//        log.info("uuid:{} ------- userUidList:{}------ merchantId:{} -------taskType:{}", uuid, userUidList, String.valueOf(merchantId), taskType);
//        commonService.addBatchTask(uuid, userUidList, String.valueOf(merchantId), taskType);
//    }

    private List<Integer> getStaffIdList(String userIdStr) {
        String[] userIdArray = userIdStr.split(",");
        List<Integer> userIdList = new ArrayList<>();
        for (String item : userIdArray) {
            userIdList.add(Integer.parseInt(item));
        }
        return userIdList;
    }

    /**
     * 更新任务中心 - 任务状态
     *
     * @param uuid
     * @param staffId
     * @param taskStatus
     * @param merchantId
     */
    public void updateBatchTaskStatus(String uuid, Integer staffId, int taskStatus, Integer merchantId) {
        EntmicroStaffDepartRelation entmicroStaffDepartRelation = entmicroStaffDepartRelationService.findDepartByStaffIdForMerchant(staffId, merchantId);
        List<String> staffUuidList = new ArrayList<>();
        if (entmicroStaffDepartRelation == null) {
            log.error("更新任务中心 - 任务状态失败!");
            return;
        }
        staffUuidList.add(entmicroStaffDepartRelation.getUserOneid());
        log.info("更新任务中心 - 任务状态uuid:{},staffId:{},taskStatus:{},merchantId:{}", uuid, staffId, taskStatus, merchantId);
        commonService.updateBatchTask(uuid, staffUuidList, String.valueOf(merchantId), taskStatus);
    }

    /**
     * 根据massId判断是否创建任务中心任务
     *
     * @param massId
     * @return
     */
    public List<MassDetailStaff> canAddTask(Integer massId) {
        if (massId == null) {
            return null;
        }
        return massService.canAddTask(massId);
    }
}