MassService.java 53.5 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 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
package cn.com.glsx.entmicro.service;

import cn.com.glsx.entmicro.Enum.BusinessExceptionEnum;
import cn.com.glsx.entmicro.config.LocalMerchantCache;
import cn.com.glsx.entmicro.constants.Constants;
import cn.com.glsx.entmicro.constants.DracConstant;
import cn.com.glsx.entmicro.constants.RedisCacheKeyPreConstants;
import cn.com.glsx.entmicro.converter.MassConvert;
import cn.com.glsx.entmicro.converter.MassDetailStaffConvert;
import cn.com.glsx.entmicro.dto.DracScrmWelcomeConfigDTO;
import cn.com.glsx.entmicro.dto.mass.*;
import cn.com.glsx.entmicro.entity.*;
import cn.com.glsx.entmicro.entity.mass.MassChatItemEntity;
import cn.com.glsx.entmicro.entity.mass.MassCustomerItemEntity;
import cn.com.glsx.entmicro.entity.mass.MassDetailQyMsgSendResultEntity;
import cn.com.glsx.entmicro.manager.MassServiceComponent;
import cn.com.glsx.entmicro.mapper.MassConditionCrowdMapper;
import cn.com.glsx.entmicro.mapper.MassConditionMapper;
import cn.com.glsx.entmicro.mapper.MassMapper;
import cn.com.glsx.entmicro.model.request.MassAttachmentRequest;
import cn.com.glsx.entmicro.model.request.MassRequest;
import cn.com.glsx.entmicro.model.request.mass.*;
import cn.com.glsx.entmicro.model.response.*;
import cn.com.glsx.entmicro.service.cache.RedisCacheService;
import cn.com.glsx.entmicro.service.common.CommonService;
import cn.com.glsx.entmicro.util.BeanConverUtil;
import cn.com.glsx.entmicro.util.DateFormatUtil;
import cn.com.glsx.entmicro.util.UUIDUtils;
import cn.com.glsx.entmicro.util.UserLocalUtils;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.framework.core.util.RpcAssert;
import cn.com.glsx.scrm.taskcenter.constants.TaskCycleStatus;
import cn.com.glsx.scrm.taskcenter.dto.SubmitTaskDTO;
import cn.com.glsx.scrm.taskcenter.remote.TaskInfoRemote;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.glsx.plat.common.utils.DateUtils;
import com.glsx.plat.common.utils.StringUtils;
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.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

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

@Slf4j
@Service
public class MassService{

    @Resource
    private MassMapper massMapper;
    @Resource
    private MassConditionMapper conditionMapper;

    @Autowired
    private TaskInfoRemote taskInfoRemote;

    @Resource
    private MassDetailStaffService massDetailStaffService;

    @Resource
    private MassChatDetailService massChatDetailService;

    @Value("${topic.entmicroMassConsumer}")
    private String massTopic;

    @Autowired
    private DracScrmWelcomeConfigService dracScrmWelcomeConfigService;

    @Autowired
    private MassDetailCustomerService massDetailCustomerService;

    @Autowired
    private EntmicroStaffService entmicroStaffService;

    @Autowired
    private MassServiceComponent massServiceComponent;

    @Autowired
    private Environment env;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private CommonService commonService;

    @Resource
    private MassConditionCrowdMapper conditionCrowdMapper;

    @Autowired
    private RedisCacheService redisCacheService;

    @Resource
    private AsyncMassService asyncMassService;

    /**
     * 自动生成代码 - 查询接口
     * @param id
     * @return
     */
    public Mass selectByPrimaryKey(Integer id) {
        return massMapper.selectByPrimaryKey(id);
    }

    /**
     * 自动生成代码 - 查询接口
     * @param record
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RpcServiceException.class})
    public int updateByPrimaryKeySelective(Mass record) {
        return massMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 群发数据保存
     * @param request
     * @return
     */
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RpcServiceException.class})
    public Mass saveMassInfo(MassRequest request) throws RpcServiceException {
        Date now = new Date();
        Mass saveMass = BeanConverUtil.conver(request,Mass.class);
        saveMass.setUuid(UUIDUtils.getUUID());
        saveMass.setCreatedBy(request.getCreatedBy());
        saveMass.setCreatedTime(now);
        saveMass.setStatus(DracConstant.MassStatus.SUCCESS);
        saveMass.setIsRemind(Constants.RemindStatus.UN_REMIND);
        saveMass.setDelFlag(Constants.NORMAL_FLAG);
        if(request.getSendType()==Constants.MASS_SEND_TIME){
            saveMass.setStatus(DracConstant.MassStatus.UNSEND);
        }
        if (StringUtils.isBlank(request.getMassName())) {
            String timeEnd = DateFormatUtil.toString(new Date(), DateFormatUtil.pattern20);
            String massStart = (request.getType()==1)?"MS":"MG";
            saveMass.setMassName(massStart+timeEnd);
        }
        if (saveMass.getSendTime()==null){
            saveMass.setSendTime(now);
        }
        // 保存 - 群发
        massMapper.insertUseGeneratedKeys(saveMass);
        if(saveMass.getId()==null) {
            log.info("群发数据库保存失败!");
            throw new RpcServiceException("db exception");
        }
        try {
            //保存关联数据
            this.saveAttachmentData(request.getAttachmentList(), saveMass);
            // 保存 - 筛选条件
            MassCondition condition = null;
            if(saveMass.getSelectType()!=null && saveMass.getSelectType()==Constants.MASS_SELECT_CONDITION){  //条件筛选客户
                condition = BeanConverUtil.conver(request.getCondition(), MassCondition.class);
                if (condition!=null) {
                    condition.setMassId(saveMass.getId());
                    condition.setDelFlag(Constants.NORMAL_FLAG);
                    if (condition.getLabelList() != null && !condition.getLabelList().isEmpty()) {
                        String tagId = condition.getLabelList().stream().map(s -> String.valueOf(s.getLabelId())).collect(Collectors.joining(","));
                        condition.setTagId(tagId);
                        String tagName = condition.getLabelList().stream().map(s -> String.valueOf(s.getLabelName())).collect(Collectors.joining(","));
                        condition.setTagName(tagName);
                    }
                    conditionMapper.insertUseGeneratedKeys(condition);
                }else {

                }
            }else if (saveMass.getSelectType()!=null && saveMass.getSelectType()==Constants.MASS_CROWD_CONDITION){//人群筛选
                List<MassConditionCrowdRequest> crowdConditions = request.getCrowdCondition();
                if (crowdConditions!=null&&!crowdConditions.isEmpty()){
                    List<MassConditionCrowd> list = MassConvert.convertMassConditionCrowdList(crowdConditions);
                    list.stream().forEach(s->{
                        s.setMassId(saveMass.getId());
                        s.setCreatedTime(new Date());
                        s.setCreatedBy(saveMass.getCreatedBy());
                        s.setDelFlag(0);
                    });
                    conditionCrowdMapper.insertList(list);
                }else {
                    updateMassFail(saveMass.getId());
                    throw new RpcServiceException("群发条件为空,创建失败!");
                }
            }

            // 保存 - 群发员工列表
            List<MassDetailStaff> massStaffList = parseUserData(request.getUserIdList(), saveMass.getId());
            if (massStaffList==null||massStaffList.isEmpty()){
                updateMassFail(saveMass.getId());
                throw new RpcServiceException("群发员工列表为空,创建失败!");
            }
            massDetailStaffService.insertMassDetailStaffList(massStaffList);
            log.info("mass detail staff list data:{}", JSONObject.toJSONString(massStaffList));
            if(saveMass.getType()==Constants.MASS_TYPE_CUSTOMER){
                // 客户 - 群发
                if (saveMass.getSelectType()==Constants.MASS_CROWD_CONDITION){
                    saveMassCrowdDetailCustomer(saveMass,request.getCombineType(),request.getCrowdCondition(),massStaffList);
                }else if (saveMass.getSelectType()!=null && saveMass.getSelectType()==Constants.MASS_ONECLICK_CONDITION){
                   saveOneClickCustomerDetail(request.getCustomerList(),saveMass,massStaffList);
                }else {
                    saveMassDetailCustomer(saveMass, condition, massStaffList);
                }
            } else if(saveMass.getType()==Constants.MASS_TYPE_GROUP){
                // 客户群 - 群发
                saveMassDetailChat(saveMass, massStaffList);
            }
        } catch (RpcServiceException e) {
            updateMassData(saveMass.getId(),DracConstant.MassStatus.FAILURE);
            throw e;
        }catch (Exception e){
            log.info("群发保存关联数据异常:{}",e);
            updateMassData(saveMass.getId(),DracConstant.MassStatus.FAILURE);
            throw new RpcServiceException(DefaultErrorEnum.DATABASE_ERROR);
        }
        return saveMass;
    }

    public void updateMassFail(Integer id){
        Mass mass = new Mass();
        mass.setId(id);
        mass.setStatus(DracConstant.MassStatus.FAILURE);
        mass.setUpdatedTime(new Date());
        mass.setUpdatedBy(UserLocalUtils.getCreatedId());
        updateByPrimaryKeySelective(mass);
    }

    private void saveOneClickCustomerDetail(List<CustomerInfoRequest> customerList, Mass saveMass, List<MassDetailStaff> massStaffList) {
        Map<Integer, MassDetailStaff> massDetailMapper = massStaffList.stream().collect(Collectors.toMap(MassDetailStaff::getStaffId, Function.identity()));
        List<CustomerInfoResponse> customerInfoResponse = MassConvert.convertCustomerInfoResponse(customerList);
        if (customerInfoResponse==null||customerInfoResponse.isEmpty()){
            Mass mass = new Mass();
            mass.setId(saveMass.getId());
            mass.setStatus(DracConstant.MassStatus.FAILURE);
            mass.setUpdatedTime(new Date());
            mass.setUpdatedBy(UserLocalUtils.getCreatedId());
            updateByPrimaryKeySelective(mass);
            throw new RpcServiceException(BusinessExceptionEnum.CUSTOMER_NUMBER_ZERO);
        }
        saveMassCustomerDetail(customerInfoResponse,saveMass,massDetailMapper);
    }

    /**
     * 客户群发 客户信息保存
     * @param saveMass
     * @param condition
     * @param massStaffList
     */
    public void saveMassDetailCustomer(Mass saveMass, MassCondition condition, List<MassDetailStaff> massStaffList) {
        if (condition==null) {
            condition = new MassCondition();
        }
        // 过滤客户列表,客户数为0时创建失败
        List<CustomerInfoResponse> customerList = filterCustomerListByCondition(condition, saveMass.getMerchantId(), massStaffList);
        log.info("filter customerlist:{}", JSONObject.toJSONString(customerList));
        if (CollectionUtils.isEmpty(customerList)) {
            Mass mass = new Mass();
            mass.setId(saveMass.getId());
            mass.setStatus(DracConstant.MassStatus.FAILURE);
            mass.setUpdatedTime(new Date());
            mass.setUpdatedBy(UserLocalUtils.getCreatedId());
            updateByPrimaryKeySelective(mass);
            throw new RpcServiceException(BusinessExceptionEnum.CUSTOMER_NUMBER_ZERO);
        } else {
            Map<Integer, MassDetailStaff> massDetailMapper = massStaffList.stream().collect(Collectors.toMap(MassDetailStaff::getStaffId, Function.identity()));
            saveMassCustomerDetail(customerList, saveMass, massDetailMapper);
        }
    }

    /**
     * 客户群发 客户信息保存(人群条件)
     * @param saveMass
     * @param crowdRequests
     * @param massStaffList
     */
    private void saveMassCrowdDetailCustomer(Mass saveMass, Integer combineType,List<MassConditionCrowdRequest> crowdRequests, List<MassDetailStaff> massStaffList) {
        // 过滤客户列表,客户数为0时创建失败
        List<CustomerInfoResponse> customerList = filterCustomerListByCondition(combineType, crowdRequests, saveMass.getMerchantId(), massStaffList);
        log.info("filter customerlist:{}", JSONObject.toJSONString(customerList));
        if (CollectionUtils.isEmpty(customerList)) {
            Mass mass = new Mass();
            mass.setId(saveMass.getId());
            mass.setStatus(DracConstant.MassStatus.FAILURE);
            mass.setUpdatedTime(new Date());
            mass.setUpdatedBy(UserLocalUtils.getCreatedId());
            updateByPrimaryKeySelective(mass);
            throw new RpcServiceException(BusinessExceptionEnum.CUSTOMER_NUMBER_ZERO);
        } else {
            Map<Integer, MassDetailStaff> massDetailMapper = massStaffList.stream().collect(Collectors.toMap(MassDetailStaff::getStaffId, Function.identity(),(s1,s2)->s1));
            saveMassCustomerDetail(customerList, saveMass, massDetailMapper);
        }
    }

    public List<CustomerInfoResponse> filterCustomerListByCondition(MassCondition condition, Integer merchantId, List<MassDetailStaff> massStaffList) {
        // 筛选客户
        List<Integer> staffIds = null;
        if (!CollectionUtils.isEmpty(massStaffList)) {
            staffIds = massStaffList.stream().map(MassDetailStaff::getStaffId).collect(Collectors.toList());
        }
        log.info("filter customerlist params:{}, merchantId:{}, staffIds:{}", JSONObject.toJSONString(condition), merchantId, JSONObject.toJSONString(staffIds));
        List<CustomerInfoResponse> responseList = massServiceComponent.filterCustomerListByCondtion(condition, merchantId, staffIds);
        return responseList;
    }


    public List<CustomerInfoResponse> filterCustomerListByCondition(Integer combineType,List<MassConditionCrowdRequest> crowdRequests, Integer merchantId, List<MassDetailStaff> massStaffList) {
        // 筛选客户
        List<Integer> staffIds = null;
        if (!CollectionUtils.isEmpty(massStaffList)) {
            staffIds = massStaffList.stream().map(MassDetailStaff::getStaffId).collect(Collectors.toList());
        }
        log.info("filter customerlist crowdRequests:{}, merchantId:{}, staffIds:{}", JSONObject.toJSONString(crowdRequests), merchantId, JSONObject.toJSONString(staffIds));
        List<CustomerInfoResponse> responseList = massServiceComponent.filterCustomerListByDCrowdCondtion(combineType,crowdRequests, merchantId, staffIds);
        return responseList;
    }



    /**
     * 人群筛选返回跟进人列表
     *
     * @param combineType
     * @param crowdRequests
     * @param merchantId
     * @return
     */
    public List<StaffFollowResponse> filterFollowerListByCondition(Integer combineType, List<MassConditionCrowdRequest> crowdRequests, Integer merchantId) {
        log.info("filter customerlist crowdRequests:{}, merchantId:{}", JSONObject.toJSONString(crowdRequests), merchantId);
        List<StaffFollowResponse> responseList = massServiceComponent.filterFollowerListByCondition(combineType,crowdRequests, merchantId);
        return responseList;
    }

    public void saveMassCustomerDetail(List<CustomerInfoResponse> customerList, Mass saveMass, Map<Integer, MassDetailStaff> massDetailMapper) {
        List<MassDetailCustomer> massDetailCustomerList = new ArrayList<>();
        for (CustomerInfoResponse customerInfo : customerList) {
            MassDetailCustomer massDetailCustomer = new MassDetailCustomer();
            if (StringUtils.isEmpty(customerInfo.getStaffId())) {
                log.info("error filter customer info not have param staffId:{}", JSONObject.toJSONString(customerInfo));
                continue;
            }
            MassDetailStaff detailStaff = massDetailMapper.get(Integer.parseInt(customerInfo.getStaffId()));
            log.info("mass customerdetail customerInfo:{} staff:{}", JSONObject.toJSONString(customerInfo), JSONObject.toJSONString(detailStaff));
            massDetailCustomer.setStaffRelationId((detailStaff!=null)?detailStaff.getId():0);
            massDetailCustomer.setCustomerId(customerInfo.getId());
            massDetailCustomer.setExternalUserId(customerInfo.getUserid());
            massDetailCustomer.setDelFlag(DracConstant.DelFlag.OK);
            massDetailCustomer.setStatus(DracConstant.MassSenderStatus.UN_SENDER);
            massDetailCustomerList.add(massDetailCustomer);
        }
        massDetailCustomerService.batchSaveMassDetailCustomer(massDetailCustomerList);
    }

    /**
     * 保存客户群群发 群信息
     * @param saveMass
     * @param massStaffList
     */
    private void saveMassDetailChat(Mass saveMass, List<MassDetailStaff> massStaffList) {
        if (massStaffList==null||massStaffList.isEmpty()){
            return;
        }
        List<Integer> staffIds = massStaffList.stream().map(MassDetailStaff::getStaffId).collect(Collectors.toList());
        List<CustGroupResponse> chatIds = massServiceComponent.filterCustomerChatIdsByStaffIds(saveMass.getMerchantId(), staffIds);
        log.info("客户群id列表返回:{}", JSONObject.toJSONString(chatIds));
        if (CollectionUtils.isEmpty(chatIds)) {
            Mass mass = new Mass();
            mass.setId(saveMass.getId());
            mass.setStatus(DracConstant.MassStatus.FAILURE);
            mass.setUpdatedTime(new Date());
            mass.setUpdatedBy(UserLocalUtils.getCreatedId());
            updateByPrimaryKeySelective(mass);
            throw new RpcServiceException(BusinessExceptionEnum.CUSTOMER_CHAT_NUMBER_ZERO);
        } else {
            Map<Integer, MassDetailStaff> map = massStaffList.stream().collect(Collectors.toMap(MassDetailStaff::getStaffId, Function.identity(), (s1, s2) -> s1));
            List<MassChatDetail> massChatDetailList = new ArrayList<>();
            for (CustGroupResponse groupResponse:chatIds) {
                if (groupResponse.getChatId()==null) {
                    continue;
                }
                MassDetailStaff massDetailStaff = map.get(groupResponse.getStaffId());
                if (massDetailStaff==null) {
                    continue;
                }
                MassChatDetail massChatDetail = new MassChatDetail();
                massChatDetail.setStaffRelationId(massDetailStaff.getId());
                massChatDetail.setChatId(groupResponse.getChatId());
                massChatDetail.setDelFlag(DracConstant.DelFlag.OK);
                massChatDetail.setStatus(Constants.MASS_CHAT_DETAIL_STATUS.UNSEND);
                massChatDetailList.add(massChatDetail);
            }
            log.info("批量保存客户群群发群详情信息列表参数:{}",JSONObject.toJSON(massChatDetailList));
            massChatDetailService.batchInsertMassChatDetail(massChatDetailList);
        }
    }

    /**
     * 保存一客一群附件数据
     * @param attachmentList
     * @param mass
     */
    private void saveAttachmentData(List<MassAttachmentRequest> attachmentList, Mass mass){
        if(CollectionUtils.isEmpty(attachmentList)){
            return;
        }
        // 保存附件数据
        List<DracScrmWelcomeConfigDTO> dracScrmWelcomeConfigDTOList = new ArrayList<>();
        for (MassAttachmentRequest att:attachmentList) {
            DracScrmWelcomeConfigDTO dracWelcome = new DracScrmWelcomeConfigDTO();
            dracWelcome.setAttType(att.getAttType());
            dracWelcome.setAttContent(att.getAttContent());
            dracWelcome.setMerchantId(mass.getMerchantId());
            dracWelcome.setBusinessUuid(mass.getUuid());
            dracWelcome.setBusinessDesc(DracConstant.WelcomeDesc.MASS);
            dracWelcome.setCreatedBy(mass.getCreatedBy());
            dracWelcome.setDelFlag(DracConstant.DelFlag.OK);
            dracScrmWelcomeConfigDTOList.add(dracWelcome);
        }
        dracScrmWelcomeConfigService.saveDracScrmWelcomeConfigList(dracScrmWelcomeConfigDTOList);
    }

    /**
     * 保存客户群发员工数据
     * @param userIdList
     * @param massId
     */
    private List<MassDetailStaff> parseUserData(String userIdList, Integer massId){
        if(StringUtils.isEmpty(userIdList)){
            return null;
        }
        String[] idArr = userIdList.split(",");
        int len = idArr.length;
        List<MassDetailStaff> list = new ArrayList<>(len);
        for (int i = 0; i < len; i++) {
            MassDetailStaff user = new MassDetailStaff();
            user.setMassId(massId);
            user.setStaffId(Integer.parseInt(idArr[i]));
            user.setDelFlag(Constants.NORMAL_FLAG);
            //未发送
            user.setStatus(DracConstant.MassSenderStatus.UN_SENDER);
            list.add(user);
        }
        return list;
    }

    public MassResponse getBaseMass(Integer id){
        //获取主表数据
        Mass selectCondition = new Mass();
        selectCondition.setId(id);
        Mass selectResult = massMapper.selectByPrimaryKey(selectCondition);
        if (selectResult==null) {
            log.info("数据不存在,massId:{}",id);
            return null;
        }

        MassResponse massResponse = MassConvert.convertMassData(selectResult);
        return massResponse;
    };

    /**
     * 获取客户群发详情
     * @param id
     * @return
     */
    public MassResponse getDetailSingle(Integer id) {
        RpcAssert.assertNotNull(id,DefaultErrorEnum.PARAMETER_NULL,"群发id参数不能为空!");
        //获取主表数据
        Mass selectCondition = new Mass();
        selectCondition.setId(id);
        Mass selectResult = massMapper.selectByPrimaryKey(selectCondition);
        if (selectResult==null) {
            throw new RpcServiceException(DefaultErrorEnum.DATA_NOT_EXIST);
        }

        MassResponse massResponse = MassConvert.convertMassData(selectResult);
        List<MassDetailStaffResponse> userList = buildMassSenderStaffList(id);
        //获取一客一群 员工列表数据
        massResponse.setUserList(userList);
        //获取附件关系数据
//        massResponse.setAttachmentList(dracScrmWelcomeConfigService.getDracScrmWelcomeConfigList(massResponse.getUuid(), DracConstant.WelcomeDesc.MASS));
        massResponse.setAttachmentList(getAttachmentList(massResponse.getUuid()));
        //获取条件列表
        if(massResponse.getSelectType()==Constants.MASS_SELECT_CONDITION) {  //客户筛选条件
//            massResponse.setCondition(conditionMapper.selectByMassId(id));
            massResponse.setCondition(getConditionByMassId(id));
        }else if (massResponse.getSelectType()==Constants.MASS_CROWD_CONDITION){//人群筛选
            massResponse.setConditionResponses(getConditionCrowdsByMassId(id));
        }
        //获取客户数量
        massResponse.setCustomerCount(getCustomerCountByMassId(id,massResponse.getType()));
        //获取创建人名称
        if (massResponse.getCreatedBy()!=null){
            UserResponse userResponse = new UserResponse();
            userResponse.setCreatedBy(massResponse.getCreatedBy());
            List<UserResponse> userResponses = commonService.setUser(Arrays.asList(userResponse));
            if (userResponses!=null&&!userResponses.isEmpty()){
                massResponse.setCreatedName(userResponses.get(0).getCreatedName());
            }
        }
        return massResponse;
    }

    /**
     * 根据群发Id查询人群筛选条件列表
     * @param id
     * @return
     */
    public List<MassCrowdConditionResponse> getConditionCrowdsByMassId(Integer id) {
        Example example = new Example(MassConditionCrowd.class);
        example.createCriteria().andEqualTo("massId",id).andEqualTo("delFlag",Constants.NORMAL_FLAG);
        List<MassConditionCrowd> massConditionCrowds = conditionCrowdMapper.selectByExample(example);
        return MassConvert.convertMassCrowdConditionResponse(massConditionCrowds);
    }


    /**
     * 根据massId查询客户/客户群数量
     * @param massId
     * @param type 群发类型
     * @return
     */
    private Integer getCustomerCountByMassId(Integer massId, Byte type) {
        log.info("根据massId查询客户数量入参:massId:{}",massId);
        if (massId==null||type==null){
            return null;
        }
        try {
            if (Constants.MASS_TYPE_CUSTOMER==type){
                return massDetailCustomerService.countCustomers(massId);
            }else if (Constants.MASS_TYPE_GROUP==type){
                return massChatDetailService.countChats(massId);
            }
        } catch (Exception e) {
            log.info("根据massId获取客户数量异常:{}",e);
            e.printStackTrace();
        }
        return null;
    }

    //根据massId查询筛选条件
    private MassConditionResponse getConditionByMassId(Integer id) {
        if (id==null){
            return null;
        }
        Example example = new Example(MassCondition.class);
        example.createCriteria().andEqualTo("massId",id).andEqualTo("delFlag",Constants.NORMAL_FLAG);
        List<MassCondition> massConditions = conditionMapper.selectByExample(example);
        if (massConditions!=null&&!massConditions.isEmpty()){
            MassConditionResponse response = new MassConditionResponse();
            BeanUtils.copyProperties(massConditions.get(0),response);
            return response;
        }
        return null;
    }

    private List<MassDetailStaffResponse> buildMassSenderStaffList(Integer id) {
        List<MassDetailStaffResponse> staffList = massDetailStaffService.getStaffListByMassId(id);
        if (CollectionUtils.isEmpty(staffList)) {
            return null;
        }

        List<Integer> staffIds = staffList.stream().map(MassDetailStaffResponse::getStaffId).collect(Collectors.toList());
        Map<Integer, EntmicroStaffResponse> staffMapper = massServiceComponent.getEntmicroStaffResponseMapper(staffIds);
        for (MassDetailStaffResponse massDetail:staffList) {
            EntmicroStaffResponse entmicroStaff = staffMapper.get(massDetail.getStaffId());
            if (entmicroStaff==null) {
                continue;
            }
            massDetail.setStaffName(entmicroStaff.getStaffName());
            massDetail.setQyUserId(entmicroStaff.getUserId());
        }
        return staffList;
    }

    /**
     * 获取群发分页列表数据
     *
     * @param pagination
     * @return
     */
    public Page<MassResponse> getMassPage(RpcPagination<MassRequest> pagination) {
        RpcAssert.assertNotNull(pagination.getCondition().getMerchantId(), DefaultErrorEnum.PARAMETER_NULL, "merchantId params must not be null");
        PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
        Page<MassResponse> pageResponse = massMapper.selectByCondition(pagination.getCondition());
        if (CollectionUtils.isEmpty(pageResponse.getResult())) {
            return pageResponse;
        }
        for (MassResponse massResponse : pageResponse.getResult()) {
            // 包装附件内容
            massResponse.setAttachmentList(getAttachmentList(massResponse.getUuid()));
            if (massResponse.getType()==Constants.MASS_TYPE_CUSTOMER) {
                // 包装统计数据
                buildMassSenderStatistic(massResponse);
            } else {
                // 包装统计数据
                buildMassGroupSenderStatistic(massResponse);
            }
        }
        return pageResponse;
    }

    // 缓存优化
    public List<DracScrmWelcomeConfigDTO> getAttachmentList(String uuid) {
        try {
            Object cache = redisCacheService.getCache(RedisCacheKeyPreConstants.massAttachmentKey + uuid);
            if (cache != null) {
                List<DracScrmWelcomeConfigDTO> list = (List<DracScrmWelcomeConfigDTO>) cache;
                return list;
            }
        } catch (Exception e) {
        }
        List<DracScrmWelcomeConfigDTO> dracScrmWelcomeConfigList = dracScrmWelcomeConfigService.getDracScrmWelcomeConfigList(uuid, DracConstant.WelcomeDesc.MASS);
        try {
            if (dracScrmWelcomeConfigList != null) {
                redisCacheService.setCache(RedisCacheKeyPreConstants.massAttachmentKey + uuid, dracScrmWelcomeConfigList, RedisCacheKeyPreConstants.massAttachmentKeyTimeout);
            }
        } catch (Exception e) {
        }
        return dracScrmWelcomeConfigList;
    }

    private void buildMassSenderStatistic(MassResponse massResponse) {
        // 客户统计数量
        MassDetailStatisticDTO massDetailStatisticDTO = statisticMassDetail(massResponse.getId());
        // 已发送员工数
        massResponse.setSendUserNum(massDetailStatisticDTO.getSenderStaffCount());
        // 未发送员工数
        massResponse.setUnsendUserNum(massDetailStatisticDTO.getUnSenderStaffCount());
        // 已送达客户数
        massResponse.setSendCustomerNum(massDetailStatisticDTO.getSenderCustomerCount());
        // 未送达客户数
        massResponse.setUnsendCustomerNum(massDetailStatisticDTO.getUnSenderCustomerCount());
    }

    private void buildMassGroupSenderStatistic(MassResponse massResponse) {
        // 客户群统计数量
        MassGroupDetailStatisticDTO massGroupDetailStatisticDTO = statisticMassGroupDetail(massResponse.getId());
        // 已发送员工数
        massResponse.setSendUserNum(massGroupDetailStatisticDTO.getSenderStaffCount());
        // 未发送员工数
        massResponse.setUnsendUserNum(massGroupDetailStatisticDTO.getUnSenderStaffCount());
        // 已送达客户数
        massResponse.setSendCustomerNum(massGroupDetailStatisticDTO.getSenderGroupCount());
        // 未送达客户数
        massResponse.setUnsendCustomerNum(massGroupDetailStatisticDTO.getUnSenderGroupCount());
    }

    /**
     * 推送定时任务至任务中心
     * @param uuid
     * @param massId
     * @param date
     */
    public void sendMassTaskToCenter(String uuid, Integer massId, Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);					//放入Date类型数据
        StringBuffer cron = new StringBuffer();
        cron.append(cal.get(Calendar.SECOND)).append(" " + cal.get(Calendar.MINUTE))
                .append(" " + cal.get(Calendar.HOUR_OF_DAY)).append(" " + cal.get(Calendar.DATE))
                .append(" " + (cal.get(Calendar.MONTH) + 1)).append(" " + "?");
        SubmitTaskDTO dto = new SubmitTaskDTO();
        String taskId = uuid + "_" + massId;
        dto.setTaskId(taskId);
        dto.setTaskName(Constants.MASS_TASK_PREFIX + taskId);
        dto.setCronExpression(cron.toString());
        dto.setRepeatCount(null);  //默认只执行一次
        dto.setTaskSource(Constants.MASS_TASK_SOURCE);
        dto.setCycleTask(TaskCycleStatus.CYCLE);
        dto.setTaskTopic(massTopic);
        log.info("群发定时任务对象:{}", JSONObject.toJSONString(dto));
        try {
            RpcResponse<Boolean> rpcResponse = taskInfoRemote.submitTask(dto);
            log.info("=======推送定时任务:{}至任务中心返回结果:{}", taskId, JSONObject.toJSONString(rpcResponse));
        } catch (Exception e) {
            log.error("send mass task to taskcenter exception:{}", e.getMessage());
            updateMassData(massId, DracConstant.MassStatus.FAILURE);
            throw new RpcServiceException(DefaultErrorEnum.RPC_ERROR);
        }
    }

    /**
     * 群发任务更新数据
     * @param id
     * @param status
     * @return
     */
    public int updateMassData(Integer id, Byte status){
        Mass record = new Mass();
        record.setId(id);
        record.setStatus(status);  //状态更新
        record.setUpdatedTime(new Date());
        record.setUpdatedBy(UserLocalUtils.getCreatedId());
        int i = massMapper.updateByPrimaryKeySelective(record);
        return i;
    }

    /**
     * 发送提醒
     * @param id
     * @throws RpcServiceException
     */
    public void sendMassRemind(Integer id) throws RpcServiceException {
        MassResponse massResponse = getDetailSingle(id);
        if (massResponse==null) {
            throw new RpcServiceException(DefaultErrorEnum.DATA_NOT_EXIST);
        }

        LocalMerchantCache.putMerchantId(massResponse.getMerchantId());

        /*
         * 发送提醒是否满足条件
         *  24小时内无法再次提醒
         */
        Date remindDate = massResponse.getRemindTime();
        Date now = new Date();
        if(remindDate!=null && massResponse.getIsRemind()!=null && massResponse.getIsRemind()==1 &&
                (now.getTime()-remindDate.getTime())<Constants.REMIND_TIME_LIMIT){
            throw new RpcServiceException(BusinessExceptionEnum.LIMIT_REMIND);
        }
        List<MassDetailStaffResponse> userList = massResponse.getUserList();
        if(org.springframework.util.CollectionUtils.isEmpty(userList)){
            log.info("mass semd remind message staff is empty. massId:{}", id);
            return;
        }

        String content = getNoticMessageContent(massResponse.getType());
        remindStaffList(userList, content);

        //更新提醒时间
        Mass upadteMass = new Mass();
        upadteMass.setId(massResponse.getId());
        upadteMass.setIsRemind(Constants.RemindStatus.REMIND);
        upadteMass.setRemindTime(now);
        updateByPrimaryKeySelective(upadteMass);
    }

    private void remindStaffList(List<MassDetailStaffResponse> userList, String content) {
        StringBuilder sb = new StringBuilder();
        for (MassDetailStaffResponse staffResponse : userList) {
            sb.append(staffResponse.getQyUserId()).append("|");
        }
        String staffUserIds = sb.toString();
        staffUserIds = staffUserIds.substring(0, staffUserIds.length()-1);
        Integer merchantId = LocalMerchantCache.getMerchantId();
        commonService.sendNoticeMsg(staffUserIds, content, merchantId);
    }

    /**
     * 提醒某一个员工或群主
     * @param id
     * @param massType
     */
    public Boolean sendMassRemindStaff(Integer id, Integer massType) {
        Boolean result = false;
        MassDetailStaff massDetailStaff = massDetailStaffService.getStaffDetailById(id);
        if (massDetailStaff==null) {
            return result;
        }

        MassResponse massResponse = getDetailSingle(massDetailStaff.getMassId());
        if (massResponse==null) {
            return result;
        }

        EntmicroStaffResponse entmicroStaffResponse = entmicroStaffService.findStaffDetailById(massDetailStaff.getStaffId());
        if (entmicroStaffResponse==null) {
            return false;
        }
        boolean remindLock = putCacheKeyRemindLock(id);
        if (!remindLock) {
            return false;
        }

        String content = getNoticMessageContent(massType.byteValue());
        String userId = entmicroStaffResponse.getUserId();
        log.info("mass detail sendMassRemindStaff userId:{}, content:{}", userId, content);
        commonService.sendNoticeMsg(userId, content, massResponse.getMerchantId());
        return true;
    }

    private boolean putCacheKeyRemindLock(Integer id) {
        String key = getRemindLockKey(id);
        long timeOut = Long.parseLong(env.getProperty("mass.staff.remind.key.timeout"));
        boolean lockResult = redisTemplate.boundValueOps(key).setIfAbsent(key, timeOut, TimeUnit.MINUTES);
        return lockResult;
    }

    private String getRemindLockKey(Integer id) {
        return Constants.RedisKey.MassStaffRemindKey + id;
    }

    private String getNoticMessageContent(Byte type) {
        String sendDate = DateUtils.format(new Date(), "yyyyMMdd");
        String remindMsg = env.getProperty(Constants.RemindPropertyKey.REMIND_MSG);
        String typeText = (type==Constants.MASS_TYPE_CUSTOMER)?"客户群发":"客户群群发";
        String content = String.format(remindMsg, sendDate, typeText);
        return content;
    }

    /**
     * 统计客户群发
     * @param massId
     * @return
     */
    public MassDetailStatisticDTO statisticMassDetail(Integer massId) {
        MassDetailStatisticDTO massDetailStatisticDTO = new MassDetailStatisticDTO();
        Future<Map<Integer, Integer>> f1 = asyncMassService.countStaffSender(massId);
        Future<Map<Integer, Integer>> f2 = asyncMassService.countCustomerSender(massId);
        // 员工
//        Map<Integer, Integer> massStaffCountMapper = massDetailStaffService.countStaffSender(massId);
        Map<Integer, Integer> massStaffCountMapper = null;
        Map<Integer, Integer> massCustomerCountMapper = null;
        try {
            massStaffCountMapper = f1.get();
            massCustomerCountMapper = f2.get();
        } catch (Exception e) {
            log.info("异步查询异常:{}",e);
        }
        //已发送和发送失败的都为已发送
        Integer sended = massGmUtil(massStaffCountMapper, DracConstant.MassSenderStatus.SENDER);
        Integer sendedError = massGmUtil(massStaffCountMapper, DracConstant.MassSenderStatus.FAILURE_SENDER);
        massDetailStatisticDTO.setSenderStaffCount(sended+sendedError);
        massDetailStatisticDTO.setUnSenderStaffCount(massGmUtil(massStaffCountMapper, DracConstant.MassSenderStatus.UN_SENDER));
        // 客户
//        Map<Integer, Integer> massCustomerCountMapper = massDetailCustomerService.countCustomerSender(massId);

        massDetailStatisticDTO.setSenderCustomerCount(massGmUtil(massCustomerCountMapper, DracConstant.MassSenderStatus.SENDER));
        massDetailStatisticDTO.setUnSenderCustomerCount(massGmUtil(massCustomerCountMapper, DracConstant.MassSenderStatus.UN_SENDER));
        massDetailStatisticDTO.setSenderCustomerFailureCount(massGmUtil(massCustomerCountMapper, DracConstant.MassSenderStatus.FAILURE_SENDER)+massGmUtil(massCustomerCountMapper, DracConstant.MassSenderStatus.FAILURE_RECIVER));
        return massDetailStatisticDTO;
    }

    private Integer massGmUtil(Map<Integer, Integer> countMapper, Integer senderStatus) {
        int defaultCount = 0;
        if (countMapper==null||countMapper.isEmpty()) {
            return defaultCount;
        }
        Integer count = countMapper.get(senderStatus);
        return (count!=null)?count:defaultCount;
    }

    /**
     * 返回员工列表
     * @param massRequest
     * @return
     */
    public List<MassStaffSenderItemDTO> getMassDetailStaffList(MassDetailListRequest massRequest) {
        List<MassDetailStaffResponse> staffResponseList = massDetailStaffService.getStaffListByMassIdAndStatus(massRequest.getMassId(), massRequest.getStatus());
        if (CollectionUtils.isEmpty(staffResponseList)) {
            return null;
        }
        // 获取到员工信息
        List<Integer> staffIdLsit = staffResponseList.stream().map(MassDetailStaffResponse::getStaffId).collect(Collectors.toList());
        Map<Integer, EntmicroStaffResponse> staffMapper = massServiceComponent.getEntmicroStaffResponseMapper(staffIdLsit);
        // 组装返回数据
        List<MassStaffSenderItemDTO> resultList = MassDetailStaffConvert.convertToMassStaffDetailList(staffResponseList, staffMapper);
        if (resultList != null && !resultList.isEmpty()) {
            for (MassStaffSenderItemDTO itemDTO : resultList) {
                // remindStatus:0未提醒  1已提醒
                boolean remindLock = validRemindLock(itemDTO.getId());
                itemDTO.setRemindStatus(remindLock ? Constants.RemindStatus.REMIND_I : Constants.RemindStatus.UN_REMIND_I);
            }
        }
        return resultList;
    }

    private boolean validRemindLock(Integer id) {
        String key = getRemindLockKey(id);
        Object value = redisTemplate.boundValueOps(key).get();
        return value!=null;
    }

    /**
     * 返回客户列表
     * @param massRequest
     * @return
     */
    public List<MassCustomerSenderItemDTO> getMassDetailCustomerList(MassDetailListRequest massRequest) {
        List<MassCustomerItemEntity> massDetailCustomerList = massDetailCustomerService.getCustomerListByMassIdAndStatus(massRequest.getMassId(), massRequest.getStatus());
        if (CollectionUtils.isEmpty(massDetailCustomerList)) {
            return null;
        }

        Mass mass = getMassEntityById(massDetailCustomerList.get(0).getMassId());
//        log.info("===" + JSONObject.toJSONString(massDetailCustomerList));
//        log.info("===" + JSONObject.toJSONString(mass));

        // 获取员工和客户构建数据
        List<Integer> staffIds = massDetailCustomerList.stream().map(MassCustomerItemEntity::getStaffId).distinct().collect(Collectors.toList());
        List<Integer> customerIds = massDetailCustomerList.stream().map(MassCustomerItemEntity::getCustomerId).collect(Collectors.toList());
//        Map<Integer, EntmicroStaffResponse> staffMapper = massServiceComponent.getEntmicroStaffResponseMapper(staffIds);
//        Map<Integer, CustomerInfoResponse> customerMapper = massServiceComponent.getCustomerInfoResponseMapper(customerIds, mass.getMerchantId());
        Map<Integer, EntmicroStaffResponse> staffMapper = null;
        Map<Integer, CustomerInfoResponse> customerMapper = null;
        Future<Map<Integer, EntmicroStaffResponse>> staffMapperFuture = asyncMassService.getEntmicroStaffResponseMapper(staffIds);
        Future<Map<Integer, CustomerInfoResponse>> customerMapperFuture = asyncMassService.getCustomerInfoResponseMapper(customerIds, mass.getMerchantId());
        try {
            staffMapper = staffMapperFuture.get();
            customerMapper = customerMapperFuture.get();
        } catch (Exception e) {
            log.info("异步查询异常:{}",e);
        }
        List<MassCustomerSenderItemDTO> resultList = MassDetailStaffConvert.convertCustomerList(massDetailCustomerList, staffMapper, customerMapper);
        return resultList;
    }

    /**
     * 统计客户群 群发
     * @param massId
     * @return
     */
    public MassGroupDetailStatisticDTO statisticMassGroupDetail(Integer massId) {
        MassGroupDetailStatisticDTO massGroupDetailStatisticDTO = new MassGroupDetailStatisticDTO();
        Future<Map<Integer, Integer>> f1 = asyncMassService.countStaffSender(massId);
        Future<Map<Integer, Integer>> f2 = asyncMassService.countCustomerChatSender(massId);
        // 员工
        Map<Integer, Integer> massStaffCountMapper = null;
        Map<Integer, Integer> massGroupCountMapper = null;
        try {
            massStaffCountMapper = f1.get();
            massGroupCountMapper = f2.get();
        } catch (Exception e) {
            log.info("异步查询异常:{}",e);
        }
        // 员工
        massGroupDetailStatisticDTO.setSenderStaffCount(massGmUtil(massStaffCountMapper, DracConstant.MassSenderStatus.SENDER));
        massGroupDetailStatisticDTO.setUnSenderStaffCount(massGmUtil(massStaffCountMapper, DracConstant.MassSenderStatus.UN_SENDER));
        // 群
        massGroupDetailStatisticDTO.setSenderGroupCount(massGmUtil(massGroupCountMapper, DracConstant.MassSenderStatus.SENDER));
        massGroupDetailStatisticDTO.setUnSenderGroupCount(massGmUtil(massGroupCountMapper, DracConstant.MassSenderStatus.UN_SENDER));
        return massGroupDetailStatisticDTO;
    }

    /**
     * 返回员工群列表
     * @param massSearchRequest
     * @return
     */
    public List<MassGroupDetailSenderDTO> getMassGroupDetailStaffList(MassGroupStatusSearchRequest massSearchRequest) {
        List<MassGroupDetailSenderDTO> resultList = new ArrayList<>();
        Mass mass = getMassEntityById(massSearchRequest.getMassId());
        if (mass==null) {
            return null;
        }

        List<MassChatItemEntity> massChatDetailList = massChatDetailService.searchMassGroupDetailList(massSearchRequest, mass.getMerchantId());
        if (CollectionUtils.isEmpty(massChatDetailList)) {
            return null;
        }
        resultList = MassDetailStaffConvert.convertToMassGroupDetailSenderDTO(massChatDetailList,mass);
        if (resultList==null||resultList.isEmpty()){return null;}
        //封装部门名称
        List<Integer> staffIds = massChatDetailList.stream().map(MassChatItemEntity::getStaffId).collect(Collectors.toList());
        if (!staffIds.isEmpty()){
            Map<Integer, EntmicroStaffResponse> departmentNameBaseMap = massServiceComponent.getMassDepartmentName(staffIds,mass.getMerchantId());
            for (MassGroupDetailSenderDTO dto : resultList) {
                EntmicroStaffResponse entmicroStaffResponse = departmentNameBaseMap.get(dto.getStaffId());
                if (entmicroStaffResponse==null) {
                    continue;
                }
                dto.setDepartmentName(entmicroStaffResponse.getDepartmentName());
                dto.setStaffName(entmicroStaffResponse.getStaffName());
            }
        }

        for (MassGroupDetailSenderDTO itemDTO:resultList) {
            // remindStatus:0未提醒  1已提醒
            boolean remindLock = validRemindLock(itemDTO.getId());
            itemDTO.setRemindStatus(remindLock?Constants.RemindStatus.REMIND_I:Constants.RemindStatus.UN_REMIND_I);
        }
        return resultList;
    }

    private Mass getMassEntityById(Integer massId) {
        Mass selectCondition = new Mass();
        selectCondition.setId(massId);
        Mass mass = massMapper.selectByPrimaryKey(selectCondition);
        return mass;
    }

    /**
     * 获取未执行成功的任务
     * @return
     */
    public List<MassDetailQyMsgSendResultEntity> getMassDetailSendResultJobList() {
        List<MassDetailQyMsgSendResultEntity> msgSendResultEntityList = massMapper.getMassDetailSendResultJobList();
        if (CollectionUtils.isEmpty(msgSendResultEntityList)) {
            log.info("================获取未执行成功的任务列表为空!==================");
            return null;
        }
        List<Integer> staffIds = msgSendResultEntityList.stream().map(MassDetailQyMsgSendResultEntity::getStaffId).collect(Collectors.toList());
        Map<Integer, EntmicroStaffResponse> staffMapper = massServiceComponent.getEntmicroStaffResponseMapper(staffIds);
        for (MassDetailQyMsgSendResultEntity massDetail:msgSendResultEntityList) {
            EntmicroStaffResponse entmicroStaffResponse = staffMapper.get(massDetail.getStaffId());
            if (entmicroStaffResponse==null||entmicroStaffResponse.getUserId()==null) {
                continue;
            }
            massDetail.setUserId(entmicroStaffResponse.getUserId());
        }
        return msgSendResultEntityList.stream().filter(s->s.getMsgId()!=null).collect(Collectors.toList());
    }

    public List<MassDetailQyMsgSendResultEntity> getMassDetailSendResultJobList(Integer merchantId) {
        RpcAssert.assertNotNull(merchantId,DefaultErrorEnum.PARAMETER_NULL,"商户号为空!");
        List<MassDetailQyMsgSendResultEntity> msgSendResultEntityList = massMapper.getMassDetailSendResultJobListByMerchantId(merchantId);
        if (CollectionUtils.isEmpty(msgSendResultEntityList)) {
            log.info("================获取未执行成功的任务列表为空!==================");
            return null;
        }
        List<Integer> staffIds = msgSendResultEntityList.stream().map(MassDetailQyMsgSendResultEntity::getStaffId).collect(Collectors.toList());
        Map<Integer, EntmicroStaffResponse> staffMapper = massServiceComponent.getEntmicroStaffResponseMapper(staffIds);
        for (MassDetailQyMsgSendResultEntity massDetail:msgSendResultEntityList) {
            EntmicroStaffResponse entmicroStaffResponse = staffMapper.get(massDetail.getStaffId());
            if (entmicroStaffResponse==null||entmicroStaffResponse.getUserId()==null) {
                continue;
            }
            massDetail.setUserId(entmicroStaffResponse.getUserId());
        }
        return msgSendResultEntityList.stream().filter(s->s.getMsgId()!=null).collect(Collectors.toList());
    }

    /**
     * 根据massId获取任务列表
     * @return
     */
    public List<MassDetailQyMsgSendResultEntity> getMassDetailSendResultByMassId(Integer massId) {
        List<MassDetailQyMsgSendResultEntity> msgSendResultEntityList = massMapper.getMassDetailSendResultByMassId(massId);
        if (CollectionUtils.isEmpty(msgSendResultEntityList)) {
            log.info("================获取未执行成功的任务列表为空!==================");
            return null;
        }
        List<Integer> staffIds = msgSendResultEntityList.stream().map(MassDetailQyMsgSendResultEntity::getStaffId).collect(Collectors.toList());
        Map<Integer, EntmicroStaffResponse> staffMapper = massServiceComponent.getEntmicroStaffResponseMapper(staffIds);
        for (MassDetailQyMsgSendResultEntity massDetail:msgSendResultEntityList) {
            EntmicroStaffResponse entmicroStaffResponse = staffMapper.get(massDetail.getStaffId());
            if (entmicroStaffResponse==null||entmicroStaffResponse.getUserId()==null) {
                continue;
            }
            massDetail.setUserId(entmicroStaffResponse.getUserId());
        }
        return msgSendResultEntityList.stream().filter(s->s.getMsgId()!=null).collect(Collectors.toList());
    }

    public Integer screenCustomerCount(MassRequest massRequest) {
        List<MassDetailStaff> massStaffList = parseUserData(massRequest.getUserIdList(), 0);
        if (Constants.MASS_CROWD_CONDITION == massRequest.getSelectType()) {
            List<CustomerInfoResponse> filteCustomerList = filterCustomerListByCondition(massRequest.getCombineType(),massRequest.getCrowdCondition(), massRequest.getMerchantId(), massStaffList);
            return (CollectionUtils.isEmpty(filteCustomerList)) ? 0 : filteCustomerList.size();
        }
        MassCondition condition = BeanConverUtil.conver(massRequest.getCondition(), MassCondition.class);
        List<CustomerInfoResponse> filteCustomerList = filterCustomerListByCondition(condition, massRequest.getMerchantId(), massStaffList);
        return (CollectionUtils.isEmpty(filteCustomerList))?0:filteCustomerList.size();
    }

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

    /**
     * 人群筛选条件回显跟进人列表
     * @param massRequest
     * @return
     */
    public List<MassFollowStaffEchoApi> followerEcho(MassRequest massRequest) {
        RpcAssert.assertNotNull(massRequest.getMerchantId(),DefaultErrorEnum.PARAMETER_NULL,"merchantId must not null!");
        RpcAssert.assertNotNull(massRequest.getCrowdCondition(),DefaultErrorEnum.PARAMETER_NULL,"merchantId must not null!");
        List<StaffFollowResponse> list = filterFollowerListByCondition(massRequest.getCombineType(),massRequest.getCrowdCondition(), massRequest.getMerchantId());
        return MassConvert.convertMassFollowStaffEchoApi(list);
    }

    public List<Integer> getSendSuccessCustomerIdList(Integer massId){
        return massDetailCustomerService.getSendSuccessCustomerIdList(massId);
    }

    public MassStaffSendStatusResponse selectMassStaffDetail(MassStaffDetailListRpcRequest request){
        return massDetailStaffService.selectMassStaffDetail(request);
    }

    /**
     * 客户群发客户分页列表
     * @param pagination
     * @return
     */
    public Page<MassCustomerSenderItemDTO> getMassDetailCustomerListPage(RpcPagination<MassCustomerStatusPageRpcRequest> pagination) {
        RpcAssert.assertNotNull(pagination.getCondition(),DefaultErrorEnum.PARAMETER_NULL,"param must not null!");
        if (pagination.getPageNum()==0||pagination.getPageSize()==0){
            pagination.setPageNum(1);
            pagination.setPageSize(10);
        }
        PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
        Page<MassCustomerItemEntity> page = massDetailCustomerService.getCustomerListByMassIdAndStatusPage(pagination.getCondition().getId(), pagination.getCondition().getStatus());
        if (CollectionUtils.isEmpty(page.getResult())){
            return new Page<>(page.getPageNum(),page.getPageSize());
        }
        Mass mass = getMassEntityById(pagination.getCondition().getId());
        // 获取员工和客户构建数据
        List<Integer> staffIds = page.getResult().stream().map(MassCustomerItemEntity::getStaffId).distinct().collect(Collectors.toList());
        List<Integer> customerIds = page.getResult().stream().map(MassCustomerItemEntity::getCustomerId).collect(Collectors.toList());
        Map<Integer, EntmicroStaffResponse> staffMapper = null;
        Map<Integer, CustomerInfoResponse> customerMapper = null;
        Future<Map<Integer, EntmicroStaffResponse>> staffMapperFuture = asyncMassService.getEntmicroStaffResponseMapper(staffIds);
        Future<Map<Integer, CustomerInfoResponse>> customerMapperFuture = asyncMassService.getCustomerInfoResponseMapper(customerIds, mass.getMerchantId());
        try {
            staffMapper = staffMapperFuture.get();
            customerMapper = customerMapperFuture.get();
        } catch (Exception e) {
            log.info("异步查询异常:{}",e);
        }
        List<MassCustomerSenderItemDTO> resultList = MassDetailStaffConvert.convertCustomerList(page.getResult(), staffMapper, customerMapper);
        if (resultList==null||resultList.isEmpty()){
            return new Page<>(page.getPageNum(),page.getPageSize());
        }
        Page<MassCustomerSenderItemDTO> respPage = new Page<>(page.getPageNum(), page.getPageSize());
        BeanUtils.copyProperties(page,respPage);
        respPage.getResult().addAll(resultList);
        return respPage;
    }
}