package com.ruoyi.ibs.list.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ibs.customerselect.service.Impl.ListSelectServiceImpl;
import com.ruoyi.ibs.draw.domain.dto.draw.LayerGridDTO;
import com.ruoyi.ibs.draw.domain.entity.DrawGrid;
import com.ruoyi.ibs.draw.service.DrawLayerService;
import com.ruoyi.ibs.grid.domain.entity.VirtualCustUser;
import com.ruoyi.ibs.grid.mapper.VirtualCustUserMapper;
import com.ruoyi.ibs.grid.service.VirtualGridListService;
import com.ruoyi.ibs.list.domain.*;
import com.ruoyi.ibs.list.mapper.*;
import com.ruoyi.ibs.list.service.ISysCampaignService;
import com.ruoyi.ibs.list.service.ISysGroupCustomerService;
import com.ruoyi.ibs.list.service.ISysGroupService;
import com.ruoyi.system.mapper.SysDeptMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.rmi.ServerException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;
import static com.ruoyi.common.utils.SecurityUtils.*;
import static com.ruoyi.ibs.list.domain.Constans.*;
import static com.ruoyi.ibs.list.domain.ListUtil.splitList;

/**
 * 活动Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-11
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class SysCampaignServiceImpl implements ISysCampaignService
{
    @Autowired
    private SysCampaignMapper sysCampaignMapper;
    @Autowired
    private SysGroupMapper sysGroupMapper;
    @Autowired
    private ISysGroupService sysGroupService;
    @Autowired
    private CustDeptUserGridMapper custDeptUserGridMapper;
    @Autowired
    private CustDeptUserCmpmMapper custDeptUserCmpmMapper;
    @Autowired
    private SysGroupCustomerMapper sysGroupCustomerMapper;
    @Autowired
    private SysCampaignGroupCustomerMapper sysCampaignGroupCustomerMapper;
    @Autowired
    private ISysGroupCustomerService sysGroupCustomerService;
    @Autowired
    private VirtualCustUserMapper virtualCustUserMapper;
    @Autowired
    private DrawLayerService drawLayerService;
    @Autowired
    private VirtualGridListService virtualGridListService;
    @Autowired
    private SysCampaignGroupCustomerCoopMapper sysCampaignGroupCustomerCoopMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;

    @Resource
    private LowcodeVisstFeedbackModelMapper lowcodeVisstFeedbackModelMapper;

    private static Logger logger= LoggerFactory.getLogger(ListSelectServiceImpl.class);


    /**
     * 查询活动
     * 
     * @param id 活动主键
     * @return 活动
     */
    @Override
    public SysCampaign selectSysCampaignById(String id)
    {
        SysCampaign sysCampaign = sysCampaignMapper.selectSysCampaignByCampaignId(id);

        if(!"-1".equalsIgnoreCase(sysCampaign.getRelatedModelId())){
            LambdaQueryWrapper<LowcodeVisstFeedbackModel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LowcodeVisstFeedbackModel::getUuid, sysCampaign.getRelatedModelId());
            LowcodeVisstFeedbackModel lowcodeVisstFeedbackModel = lowcodeVisstFeedbackModelMapper.selectOne(queryWrapper);
            if(lowcodeVisstFeedbackModel!=null) {
                sysCampaign.setRelatedModelName(lowcodeVisstFeedbackModel.getModelName());
            }else{
                sysCampaign.setRelatedModelId("-1");
            }
        }

        sysCampaign.setGroups(sysCampaignMapper.selectCampaignGroupByCampaignId(id));

        if( ROLE_BRANCH.equalsIgnoreCase(userRole())  && ("1").equalsIgnoreCase(sysCampaign.getSecondPushStatus()))
        {
            SysCampaign sysCampaignSecond = sysCampaignMapper.selectSysCampaignSecondByCampaignId(id,getDeptId(),null);
            sysCampaign.setGroups(sysCampaignMapper.selectCampaignGroupByCampaignId(id));
            return sysCampaignSecond;
        }
        if( ROLE_Outlet.equalsIgnoreCase(userRole())  && ("1").equalsIgnoreCase(sysCampaign.getSecondPushStatus()))
        {
            SysCampaign sysCampaignSecond = sysCampaignMapper.selectSysCampaignSecondByCampaignId(id,null,getDeptId());
            sysCampaign.setGroups(sysCampaignMapper.selectCampaignGroupByCampaignId(id));
            return sysCampaignSecond;
        }

        return sysCampaign;
    }

    /**
     * 查询任务列表
     *  总行管理查询  总行穿件
     *  部室查询部室创建人物
     *  支行查询支行创建人物
     *  网点、客户经理  忽略
     *
     * @param campaignName
     * @param custType
     * @param type
     * @return
     */
    @Override
    public List<SysCampaign> selectSysCampaignList(String campaignName, String custType, java.lang.String type)
    {
        if (StringUtils.isBlank(custType)||StringUtils.isBlank(type)){
            throw new RuntimeException("缺乏必填项");
        }
        List<SysCampaign> sysCampaigns = new ArrayList<>();
        SysCampaign sysCampaign = new SysCampaign();
        sysCampaign.setCampaignName(campaignName);
        sysCampaign.setCustType(custType);
        sysCampaign.setUserId(getUserId());
        java.lang.String roleName = userRole();
        sysCampaign.setCampaignLevel(roleName.equals(ROLE_HEAD) ? "0" :
                roleName.equals(ROLE_HeadPublic) ?  "2" :
                        roleName.equals(ROLE_HeadPrivate) ? "1"
                                : roleName.equals(ROLE_HeadOps)  ? "3"
                                 : roleName.equals(ROLE_BRANCH) ? "5"
                                    : roleName.equals(ROLE_Outlet) ? "6": "-1" );
        if(("-1".equalsIgnoreCase(sysCampaign.getCampaignLevel()))   ||
                ( ("6").equalsIgnoreCase(sysCampaign.getCampaignLevel()) && ("1").equalsIgnoreCase(type))  ){
            // 客戶經理一定查詢 分配給自己的任務     网点管理  -  推送给我的当客户经理用
            HashMap<String, Object> stringStringHashMap = new HashMap<>();
            if (("6").equalsIgnoreCase(sysCampaign.getCampaignLevel())){
                stringStringHashMap.put("deptId", getDeptId());
            }else if (("-1".equalsIgnoreCase(sysCampaign.getCampaignLevel()))){
                stringStringHashMap.put("userId", getUserId());
            }
            stringStringHashMap.put("coopDeptId", getDeptId());
            stringStringHashMap.put("custType", custType);
            stringStringHashMap.put("campaignName", campaignName);
            return sysCampaignMapper.selectSysCampTypeUser(stringStringHashMap);
        }
        //当前登录账号为总行管理员
        if (sysCampaign.getCampaignLevel().equalsIgnoreCase("-1") && type.equals("0")){
            return   sysCampaigns ;
            //总行管理员只有我的任务和其他任
        }
        sysCampaign.setLoginOrg3(java.lang.String.valueOf((getDeptId()/1000)));
        sysCampaign.setDeptId(getDeptId().toString().endsWith("000") ?  null: getDeptId());

        //  查询我创建的任务  限制机构、 角色即可
        if (StringUtils.isNotEmpty(sysCampaign.getCampaignLevel()) && type.equals("0")){
            sysCampaign.setDeptId( ("-1").equalsIgnoreCase(sysCampaign.getCampaignLevel()) ? null:  getDeptId());
            sysCampaign.setCreateRole(sysCampaign.getCampaignLevel());
            return   sysCampaignMapper.selectSysCampaignList(sysCampaign, type) ;
        }
        if(type.equals("1") || type.equals("2")) {
            if (Long.valueOf(sysCampaign.getCampaignLevel()) > -1 &&
                    Long.valueOf(sysCampaign.getCampaignLevel()) <= 4) {
                sysCampaign.setIsHead("true");
            }
            sysCampaign.setDeptType(type);
            HashMap<String, Object> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("deptType", type);
            stringStringHashMap.put("campaignLevel", sysCampaign.getCampaignLevel());
            stringStringHashMap.put("userId", getUserId().toString());
            stringStringHashMap.put("deptId", getDeptId().toString());
            stringStringHashMap.put("isHead", sysCampaign.getIsHead());
            stringStringHashMap.put("loginOrg3", getDeptId().toString().substring(0, 3));
            stringStringHashMap.put("custType",custType);
            stringStringHashMap.put("campaignName", campaignName);
            stringStringHashMap.put("coopDeptId", getDeptId());
            return sysCampaignMapper.selectSysCampType1And2(stringStringHashMap);
        }

        return sysCampaigns;
    }

    @Override
    public List<CustomerList> selectSysCampaignListDetails(String campaignId, CustomerList customerList, String type,Long userManagerId) {
        if (StringUtils.isBlank(type) || StringUtils.isBlank(campaignId)|| StringUtils.isBlank(customerList.getCustType())) {
            throw new IllegalArgumentException("缺乏必填项");
        }
        String custType = customerList.getCustType();
        List<CustomerList> customerLists = new ArrayList<>();
        String roleName = userRole();
        String tabName =  Constans.getTableName(custType);

        String roleUser  =   roleName.equals(ROLE_HEAD) ? "0" :
                roleName.equals(ROLE_HeadPublic) ?  "3" :
                        roleName.equals(ROLE_HeadPrivate) ? "2"
                                : roleName.equals(ROLE_HeadOps)  ? "4"
                                : roleName.equals(ROLE_BRANCH) ? "5"
                                : roleName.equals(ROLE_Outlet) ? "6": "-1";
        // 客户经理一定查询自己的
        if("-1".equalsIgnoreCase(roleUser) ||  (userManagerId !=null &&  userManagerId == 999 ) ||
                ( ("6").equalsIgnoreCase(roleUser) && ("1").equalsIgnoreCase(type))  ){
            List<CustomerList> ans = sysCampaignMapper.selectCustomerListAll2(campaignId, customerList, tabName, null,
                    "6".equalsIgnoreCase(roleUser) ? getDeptId(): null,
                    "-1".equalsIgnoreCase(roleUser) ? getUserId() : null,
                    type,userManagerId);
            if(ans != null && ans.size()>0){
                ans.forEach(e->{
                    e.setAdminFlag("manager");
                    if("head".equalsIgnoreCase(e.getPushUserLevel())){
                        e.setSecondPushStatus("/");
                    }
                });
            }
            return ans;
        }

        if(type.equalsIgnoreCase("0")){
            // 我创建的任务
            List<CustomerList> customerLists1 = sysCampaignMapper.selectCustomerListAll(campaignId, customerList, tabName, null, null, type, userManagerId);
            List<CustomerList> ans = customerLists1;
            if(ans != null && ans.size()>0){
                ans.forEach(e->{
                    if("head".equalsIgnoreCase(e.getPushUserLevel()) && StringUtils.isNotEmpty(e.getUserName()) ){
                        e.setSecondPushStatus("/");
                    }
                });
            }
            return ans;
        }
        if(type.equalsIgnoreCase("1")){
            // 推送给我的任务   要进行过滤   总行没有查询东西， 支行查询推送给支行但是没到客户经理的，  客户经理查询客户经理的
            List<CustomerList> ans = sysCampaignMapper.selectCustomerListAll2(campaignId, customerList, tabName,
                    "5".equalsIgnoreCase(roleUser) ? getDeptId() : null,
                    "6".equalsIgnoreCase(roleUser) ? getDeptId(): null,
                    "-1".equalsIgnoreCase(roleUser) ? getUserId() : null,
                    type, userManagerId);

            return ans;
        }
        if(type.equalsIgnoreCase("2")){
            // 其他任务 ： 支行创建的   |   推送给支行网点 、客户经理的
            List<CustomerList> ans = sysCampaignMapper.selectCustomerListAll3(campaignId,customerList,tabName, Long.valueOf(roleUser), getDeptId());
            if(ans != null && ans.size()>0){
                ans.forEach(e->{
                    if("head".equalsIgnoreCase(e.getPushUserLevel()) && StringUtils.isNotEmpty(e.getTellerId())){
                        e.setSecondPushStatus("/");
                    }
                });
            }
            return ans;
        }
        return customerLists;
    }

    @Override
    public List<CustomerList> selectSysCoopCampaignListDetails(String campaignId, CustomerList customerList, String type,Long userManagerId) {
        String custType = customerList.getCustType();
        String tabName =  Constans.getTableName(custType);
        List<CustomerList> customerLists = new ArrayList<>();
        if(type.equalsIgnoreCase("0")){
            // 我创建的任务
            customerLists = sysCampaignMapper.selectCoopCustomerList(campaignId, customerList, tabName, null, null, type, userManagerId);
        }else{
            customerLists = sysCampaignMapper.selectCoopCustomerList(campaignId, customerList, tabName, null, getUserId(), type, userManagerId);
        }
        List<CustCampaignGroup> custCampaignGroups = sysCampaignMapper.selectCustCampaignGroupByCampaignId(campaignId);
        if(custCampaignGroups != null && custCampaignGroups.size()>0){
            customerLists.forEach(e->{
                CustCampaignGroup custCampaignGroup = custCampaignGroups.stream().filter(c->c.getCustId().equalsIgnoreCase(e.getCustId())).findFirst().orElse(null);
                if(custCampaignGroup != null){
                    e.setGroupName(custCampaignGroup.getGroupName());
                    e.setGroupId(custCampaignGroup.getGroupId());
                }
            });
        }
        return customerLists;
    }

    @Override
    public List<SysCampaignListVo> listCampaign(String custType) {
        SysCampaign sysCampaign = new SysCampaign();
        sysCampaign.setCustType(custType);
        String roleName = userRole();
        String roleUser  = roleName.equals(ROLE_HEAD) ? "0" :
                roleName.equals(ROLE_HeadPublic) ?  "2" :
                        roleName.equals(ROLE_HeadPrivate) ? "1"
                                : roleName.equals(ROLE_HeadOps)  ? "3"
                                : roleName.equals(ROLE_BRANCH) ? "5"
                                : roleName.equals(ROLE_Outlet) ? "6": "-1";
        sysCampaign.setCreateRole(roleUser);
        sysCampaign.setTimeNow(new Date());
        sysCampaign.setDeptId(getDeptId());
        return sysCampaignMapper.selectSysCampaignVoList(sysCampaign).stream().map(e-> new SysCampaignListVo(e)).collect(Collectors.toList());
    }

    @Override
    public void selectSysGroupCustomerListExportByCustIds(HttpServletResponse response, String campaignId, List<String> custIds) {
        List<SysGroupCustomerExportVo> customerExportVos = new ArrayList<>();
        List<SysGroupMerchantExportVo> merchantExportVos = new ArrayList<>();
        List<SysGroupBusinessExportVo> businessExportVos = new ArrayList<>();
        SysCampaign sysCampaign = sysCampaignMapper.selectSysCampaignByCampaignId(campaignId);
        if (sysCampaign==null){
            throw new RuntimeException("活动不存在");
        }
        String custType = sysCampaign.getCustType();
        CustomerList customer = new CustomerList();
        customer.setCustType(custType);
        List<CustomerList> customerList = selectSysCampaignListDetails(campaignId,customer,"0",null);
        List<CustomerList> returnList = new ArrayList<>();
        if (customerList!=null&&customerList.size()>0){
            for (CustomerList customerList1 : customerList) {
                if (custIds.contains(customerList1.getCustId())){
                    returnList.add(customerList1);
                }
            }

        }
        if (custIds!=null && custIds.size()>0){
            sysGroupCustomerService.convertExport(response,returnList,customerExportVos,merchantExportVos,businessExportVos,custType);
        }else {
            sysGroupCustomerService.convertExport(response,customerList,customerExportVos,merchantExportVos,businessExportVos,custType);
        }



    }



    /**
     * 新增活动
     * 
     * @param sysCampaign 活动
     * @return 结果
     */
    @Override
    public int insertSysCampaign(SysCampaign sysCampaign,List<String> groupIds) throws ServerException {
        if (StringUtils.isBlank(sysCampaign.getCampaignName())
                ||StringUtils.isBlank(sysCampaign.getCampaignDegree())||StringUtils.isBlank(sysCampaign.getClaimType())
                || sysCampaign.getStartTime()==null||sysCampaign.getEndTime()==null||sysCampaign.getClaimStartTime()==null ||sysCampaign.getClaimEndTime()==null
                ||StringUtils.isBlank(sysCampaign.getDistributeType())){
            throw new RuntimeException("必填项未全部填写");
        }
        if ("0".equals(sysCampaign.getCreateRole())){
            if (sysCampaign.getExecuter()==null||"".equals(sysCampaign.getExecuter())){
                throw new RuntimeException("必填项未全部填写");
            }
        }
        int count = selectByCampaignName(sysCampaign.getCampaignName());
        if (count>0){
            throw new RuntimeException("系统中已有重名活动,请修改活动名称");
        }
        String roleName = userRole();
        sysCampaign.setCreateTime(DateUtils.getNowDate());
        String uuid = UUID.randomUUID().toString();
        sysCampaign.setCampaignId(uuid);
        sysCampaign.setDeptId(getDeptId());
        sysCampaign.setUserId(getUserId());
        sysCampaign.setCreateBy(getUsername());


        if(sysCampaign.getLayerIds()!=null) {
            StringBuilder lys = new StringBuilder();
            for (int i = 0; i < sysCampaign.getLayerIds().size(); i++) {
                lys.append(sysCampaign.getLayerIds().get(i));
                if (i < sysCampaign.getLayerIds().size() - 1) {
                    lys.append(",");
                }
            }
            sysCampaign.setDistributeType2(lys.toString());
        }
        if(sysCampaign.getVirtualGridIds()!=null) {
            StringBuilder vtg = new StringBuilder();
            for (int i = 0; i < sysCampaign.getVirtualGridIds().size(); i++) {
                vtg.append(sysCampaign.getVirtualGridIds().get(i));
                if (i < sysCampaign.getVirtualGridIds().size() - 1) {
                    vtg.append(",");
                }
            }
            sysCampaign.setDistributeType3(vtg.toString());
        }





        SysGroupCustomer sysGroupCustomer = new SysGroupCustomer();
//        sysGroupCustomer.setGroupId(groupId);
        //存放需要生成的清单数据，后续统一插入数据库
        List<SysCampaignGroupCustomer> campaignGroupCustomers = new ArrayList<>();
        //存放需要修改推送状态的客群数据，后续统一修改
        List<SysGroupCustomer> updateGroupCustomerLists = new ArrayList<>();
//        if (ROLE_BRANCH.equals(roleName)){
//            sysGroupCustomer.setDeptId(getDeptId());
//        }
        List<SysGroupCustomer> sysGroupCustomers = sysGroupCustomerMapper.selectSysGroupCustomerListIds(groupIds,null,null,null);

        if(sysGroupCustomers.size() == 0){
            throw    new ServerException("客群中无有效客户数据！");
        }
        if(sysGroupCustomers.size()>0){
            // 多个客群中如果有相同的客户，且cust_id外有其他字段不统一，单独处理 取第一个
            Map<String, Long>  custCounts1 = sysGroupCustomers.stream().collect(Collectors.groupingBy(SysGroupCustomer::getCustId, Collectors.counting()));
            Set<String> duplicateVules = custCounts1.entrySet().stream().filter(e -> e.getValue() >= 2).map(Map.Entry::getKey).collect(Collectors.toSet());
            Map<String, List<SysGroupCustomer>>  custCounts2 = sysGroupCustomers.stream().collect(Collectors.groupingBy(SysGroupCustomer::getCustId, Collectors.toList()));
            List<SysGroupCustomer> finalSysGroupCustomers = sysGroupCustomers;
            duplicateVules.forEach(e-> {
                List<SysGroupCustomer> sysGroupCustomersCust = custCounts2.get(e);
                SysGroupCustomer sysGroupCustomer0 = sysGroupCustomersCust.get(0);
                sysGroupCustomersCust.stream().map(d -> finalSysGroupCustomers.remove(d));
                finalSysGroupCustomers.add(sysGroupCustomer0);
            });
            sysGroupCustomers = finalSysGroupCustomers;
        }
        if(!StringUtils.isNotEmpty(sysCampaign.getRelatedModelId())){
            // 设置默认模板
            sysCampaign.setRelatedModelId("-1");
        }
        sysCampaignMapper.insertSysCampaign(sysCampaign);
        if("branch".equalsIgnoreCase(roleName)) {
            // 为保持一致， 支行规则保存在二次分配中
            sysCampaignMapper.insertSysCampaignSecond(sysCampaign);
        }
        // 补充  活动、客群关系表

        for (String groupId: groupIds ) {
            SysCampaign sysCampaignGroup = new SysCampaign();
            sysCampaignGroup.setCampaignId(uuid);
            sysCampaignGroup.setGroupId(groupId);
            sysCampaignGroup.setCreateBy(getUsername());
            sysCampaignMapper.insertSysCampaignGroup(sysCampaignGroup);
        }

        List<SysGroupCustomer> directDistributeLists = new ArrayList<>();
        //优先按照导入模板里面的归属关系分配，若无归属客户经理和部门再按照选择的优先级分配规则去分配
        //先筛选出无地址与电话的客户，无法推送清单
        sysGroupCustomers = filterAddressAndPhone(sysGroupCustomers,campaignGroupCustomers,uuid);
            //优先按照导入模板里面的归属关系分配，若无归属客户经理和部门再按照选择的优先级分配规则去分配
        if (sysGroupCustomers!=null&&sysGroupCustomers.size()>0){
            sysGroupCustomers = getUnDirectDistributeList(sysGroupCustomers,campaignGroupCustomers,sysCampaign);
            sysGroupCustomers.forEach(sysGroupCustomer1 -> {
                // 处理机构执行 分配到网点的情况
                if (jg_executer.equals(sysCampaign.getExecuter())
                        && Objects.nonNull(sysGroupCustomer1.getOutletsId())
                        && Objects.isNull(sysGroupCustomer1.getUserId()))
                {
                    sysGroupCustomer1.setOutlets(null);
                    sysGroupCustomer1.setOutletsId(null);
                }
                if(wd_executer.equals(sysCampaign.getExecuter())
                        && Objects.nonNull(sysGroupCustomer1.getDeptId())
                        && Objects.isNull(sysGroupCustomer1.getOutletsId()))
                {
                    sysGroupCustomer1.setDeptId(null);
                }
            });
        }

       //    客群中有客戶經理的情況
        List<SysGroupCustomer> groupAppoint = sysGroupCustomers.stream().filter(e -> e.getUserId() != null || e.getDeptId() != null).collect(Collectors.toList());
        sysGroupCustomers.removeAll(groupAppoint);

        List<SysCampaignGroupCustomer> collect = groupAppoint.stream().map(e -> {
            SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            BeanUtils.copyProperties(e, sysCampaignGroupCustomer);
            sysCampaignGroupCustomer.setCampaignId(uuid);
            sysCampaignGroupCustomer.setPushStatus("1");
            if (e.getUserId() != null) {
                sysCampaignGroupCustomer.setOrgDistributeStatus("1");
                sysCampaignGroupCustomer.setSecondPushStatus("1");
                sysCampaignGroupCustomer.setOrgClaimStatus("1");
                if (qz_claimType.equals(sysCampaign.getClaimType())) {
                    sysCampaignGroupCustomer.setCustClaimStatus("1");
                } else {
                    sysCampaignGroupCustomer.setCustClaimStatus("0");
                }
            }else{
                sysCampaignGroupCustomer.setSecondPushStatus("0");
                if (qz_claimType.equals(sysCampaign.getClaimType())) {
                    sysCampaignGroupCustomer.setOrgClaimStatus("1");
                } else {
                    sysCampaignGroupCustomer.setOrgClaimStatus("0");
                }
                sysCampaignGroupCustomer.setOrgDistributeStatus("0");
            }
            return sysCampaignGroupCustomer;
        }).collect(Collectors.toList());
        campaignGroupCustomers.addAll(collect);


        if (sysCampaign.getDistributeType() != null) {
            //按照管户关系分配或者地址分配
            List<String> distributeRules = Arrays.asList(sysCampaign.getDistributeType().split(","));
            distribute(sysCampaign,distributeRules,sysGroupCustomers,"",uuid,campaignGroupCustomers);
        }

        if (campaignGroupCustomers.size()>0){
            campaignGroupCustomers.forEach(e->{
                //支行创建的时候， 无论是否到客户经理，一定要有  PushUserLevel
                    e.setPushUserLevel(ROLE_HEAD.equalsIgnoreCase(userRoleHeadOrBranch()) ? "head" : "branch");
                    e.setSecondPushStatus(ROLE_HEAD.equalsIgnoreCase(userRoleHeadOrBranch())  ? e.getUserId()!=null ||e.getDeptId() == null ? null : "0"
                            :  e.getUserId()!=null ?  "1" : Arrays.asList(sysCampaign.getDistributeType().split(",")).contains("0") ? "0" : "2");
                    if(e.getUserId() !=null && StringUtils.isNotEmpty(e.getCustClaimStatus())){
                        if (qz_claimType.equals(sysCampaign.getClaimType())) {
                            e.setCustClaimStatus("1");
                        } else {
                            e.setCustClaimStatus("0");
                        }
                    }
                });
            sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomerBatch(campaignGroupCustomers);
        }
//        if (updateGroupCustomerLists.size()>0){
//            sysGroupCustomerMapper.updateSysGroupCustomerBatch(updateGroupCustomerLists);
//        }

        Stream<SysCampaignGroupCustomer> unSuccessList = campaignGroupCustomers.stream().filter(e -> e.getPushStatus() != null && !"1".equalsIgnoreCase(e.getPushStatus()));
        if(unSuccessList !=null && unSuccessList.count()>0 && "head".equalsIgnoreCase(userRoleHeadOrBranch())){
            sysCampaignGroupCustomerMapper.insertHeadHandledMission(sysCampaign.getCampaignId(),getUsername());
        }


        return 1;
    }

    /**
     * 新增活动
     *
     * @param sysCampaign 活动
     * @param groupId
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSysCooperateCampaign(SysCampaign sysCampaign, List<String> groupIds) throws ServerException {
        if (StringUtils.isBlank(sysCampaign.getCampaignName())
                ||StringUtils.isBlank(sysCampaign.getCampaignDegree())||StringUtils.isBlank(sysCampaign.getClaimType())
                || sysCampaign.getStartTime()==null||sysCampaign.getEndTime()==null||sysCampaign.getClaimStartTime()==null ||sysCampaign.getClaimEndTime()==null
                || Objects.isNull(sysCampaign.getCooperateDeptId()) ){
            throw new RuntimeException("必填项未全部填写");
        }
        if ("0".equals(sysCampaign.getCreateRole())){
            if (sysCampaign.getExecuter()==null||"".equals(sysCampaign.getExecuter())){
                throw new RuntimeException("必填项未全部填写");
            }
        }
        int count = selectByCampaignName(sysCampaign.getCampaignName());
        if (count>0){
            throw new RuntimeException("系统中已有重名活动,请修改活动名称");
        }
        String roleName = userRole();
        sysCampaign.setCreateTime(DateUtils.getNowDate());
        String uuid = UUID.randomUUID().toString();
        sysCampaign.setCampaignId(uuid);
        sysCampaign.setDeptId(getDeptId());
        sysCampaign.setUserId(getUserId());
        sysCampaign.setCreateBy(getUsername());
        sysCampaign.setDistributeType("0");
        sysCampaign.setCooperateDeptId(sysCampaign.getCooperateDeptId());

        if(!StringUtils.isNotEmpty(sysCampaign.getRelatedModelId())){
            // 设置默认模板
            sysCampaign.setRelatedModelId("-1");
        }
        sysCampaign.setIsCooperate(Boolean.TRUE);
        sysCampaignMapper.insertSysCampaign(sysCampaign);

        // 补充  活动、客群关系表
        for (String groupId: groupIds ) {
            SysCampaign sysCampaignGroup = new SysCampaign();
            sysCampaignGroup.setCampaignId(uuid);
            sysCampaignGroup.setGroupId(groupId);
            sysCampaignGroup.setCreateBy(getUsername());
            sysCampaignMapper.insertSysCampaignGroup(sysCampaignGroup);
        }

        List<SysGroupCustomer> sysGroupCustomers = sysGroupCustomerMapper.selectSysGroupCustomerListIds(groupIds,null,null,null);
        if(sysGroupCustomers.size() == 0){
            throw new ServerException("客群中无有效客户数据！");
        }
        if(sysGroupCustomers.size()>0){
            // 多个客群中如果有相同的客户，且cust_id外有其他字段不统一，单独处理 取第一个
//            Map<String, Long>  custCounts1 = sysGroupCustomers.stream().collect(Collectors.groupingBy(SysGroupCustomer::getCustId, Collectors.counting()));
//            Set<String> duplicateVules = custCounts1.entrySet().stream().filter(e -> e.getValue() >= 2).map(Map.Entry::getKey).collect(Collectors.toSet());
//            Map<String, List<SysGroupCustomer>>  custCounts2 = sysGroupCustomers.stream().collect(Collectors.groupingBy(SysGroupCustomer::getCustId, Collectors.toList()));
//            List<SysGroupCustomer> finalSysGroupCustomers = sysGroupCustomers;
//            duplicateVules.forEach(e-> {
//                List<SysGroupCustomer> sysGroupCustomersCust = custCounts2.get(e);
//                SysGroupCustomer sysGroupCustomer0 = sysGroupCustomersCust.get(0);
//                sysGroupCustomersCust.stream().map(d -> finalSysGroupCustomers.remove(d));
//                finalSysGroupCustomers.add(sysGroupCustomer0);
//            });
            Map<String, SysGroupCustomer> customerMap = new HashMap<>();
            sysGroupCustomers.forEach(sysGroupCustomer -> {
                if (!customerMap.containsKey(sysGroupCustomer.getCustId())){
                    customerMap.put(sysGroupCustomer.getCustId(),sysGroupCustomer);
                }
            });
            sysGroupCustomers = customerMap.keySet().stream().map(e->customerMap.get(e)).collect(Collectors.toList());
        }
        List<SysCampaignGroupCustomer> campaignGroupCustomers = new ArrayList<>();
        //先筛选出无地址与电话的客户，无法推送清单
        sysGroupCustomers = filterAddressAndPhone(sysGroupCustomers,campaignGroupCustomers,uuid);
        SysDept sysDept = sysDeptMapper.selectDeptById(sysCampaign.getCooperateDeptId());
        for (SysGroupCustomer sysGroupCustomer : sysGroupCustomers) {
            SysCampaignGroupCustomerCoop sysCampaignGroupCustomerCoop = new SysCampaignGroupCustomerCoop();
            BeanUtils.copyProperties(sysGroupCustomer, sysCampaignGroupCustomerCoop);
            sysCampaignGroupCustomerCoop.setCampaignId(uuid);
            sysCampaignGroupCustomerCoop.setPushStatus("1");
            if (sysDept.getDeptType().equals("branch")){
                sysCampaignGroupCustomerCoop.setDeptId(sysCampaign.getCooperateDeptId());
            }else if (sysDept.getDeptType().equals("outlet")){
                sysCampaignGroupCustomerCoop.setDeptId(sysDept.getParentId());
                sysCampaignGroupCustomerCoop.setOutletsId(sysDept.getDeptId());
            }
            sysCampaignGroupCustomerCoop.setUserId(null);
            sysCampaignGroupCustomerCoop.setOrgClaimStatus("1");
            sysCampaignGroupCustomerCoop.setOrgDistributeStatus(null);
            sysCampaignGroupCustomerCoop.setCustClaimStatus(null);
            sysCampaignGroupCustomerCoop.setOutlets(null);
            sysCampaignGroupCustomerCoopMapper.insert(sysCampaignGroupCustomerCoop);
        }
        return 1;
    }


    /**
     * 对存量活动新增 客户的处理
     *
     * @param
     * @return 结果
     */
    @Override
    public int addSysCampaignHis(String campaignId,List<String> custIds ,Map<String,SysCampaignGroupCustomer>  custVos,List<String> groupIds,String custType) throws ServerException {

        SysCampaign sysCampaign = sysCampaignMapper.selectSysCampaignByCampaignId(campaignId);

        // 补充 客群关系
        for (String groupId: groupIds ) {
            SysCampaign sysCampaignGroup = new SysCampaign();
            if(sysCampaignMapper.selectSysCampaignGroupCount(campaignId, groupId) > 0){
                continue;
            }
            //  group_id = -1  表示 直接从客户视图中添加
            sysCampaignGroup.setCampaignId(campaignId);
            sysCampaignGroup.setGroupId(groupId);
            sysCampaignGroup.setCreateBy(getUsername());
            sysCampaignMapper.insertSysCampaignGroup(sysCampaignGroup);
        }

        if( StringUtils.isNotEmpty(sysCampaign.getDistributeType2())) {
            //设置layer
            sysCampaign.setLayerIds(Arrays.stream(sysCampaign.getDistributeType2().split(",")).map(Long :: valueOf)
                    .collect(Collectors.toList()));
        }
        if( StringUtils.isNotEmpty(sysCampaign.getDistributeType3())) {
            //设置 虚拟网格
            sysCampaign.setVirtualGridIds(Arrays.stream(sysCampaign.getDistributeType3().split(",")).map(Long :: valueOf)
                    .collect(Collectors.toList()));
        }
        SysGroupCustomer sysGroupCustomer = new SysGroupCustomer();
//        sysGroupCustomer.setGroupId(groupId);
        //存放需要生成的清单数据，后续统一插入数据库
        List<SysCampaignGroupCustomer> campaignGroupCustomers = new ArrayList<>();
        //存放需要修改推送状态的客群数据，后续统一修改
        List<SysGroupCustomer> updateGroupCustomerLists = new ArrayList<>();
//        if (ROLE_BRANCH.equals(roleName)){
//            sysGroupCustomer.setDeptId(getDeptId());
//        }
        List<SysGroupCustomer> sysGroupCustomers = new ArrayList<>();
        if(!"-1".equalsIgnoreCase(groupIds.get(0))) {
            sysGroupCustomers = sysGroupCustomerMapper.selectSysGroupCustomerListIds(groupIds, "true", custIds, null);
        }else{
            SysGroupCustomer e = new SysGroupCustomer();
            e.setCustId(custIds.get(0));
            e.setCustType(custType);
            sysGroupCustomers.add(e);
        }

        sysGroupCustomers.forEach(sysGroupCustomer1 -> {
            // 处理机构执行 分配到网点的情况
            if (jg_executer.equals(sysCampaign.getExecuter())
                    && Objects.nonNull(sysGroupCustomer1.getOutletsId())
                    && Objects.isNull(sysGroupCustomer1.getUserId())){
                sysGroupCustomer1.setOutlets(null);
                sysGroupCustomer1.setOutletsId(null);
            }
            if(wd_executer.equals(sysCampaign.getExecuter())
                    && Objects.nonNull(sysGroupCustomer1.getDeptId())
                    && Objects.isNull(sysGroupCustomer1.getOutletsId()))
            {
                sysGroupCustomer1.setDeptId(null);
            }
        });

        //    客群中有客戶經理的情況
        List<SysGroupCustomer> groupAppoint = sysGroupCustomers.stream().filter(e -> e.getUserId() != null || e.getDeptId() != null).collect(Collectors.toList());
        sysGroupCustomers.removeAll(groupAppoint);

        List<SysCampaignGroupCustomer> collect = groupAppoint.stream().map(e -> {
            SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            BeanUtils.copyProperties(e, sysCampaignGroupCustomer);
            BeanUtils.copyProperties(custVos.get(e.getCustId()), sysCampaignGroupCustomer);
            sysCampaignGroupCustomer.setCampaignId(campaignId);
            sysCampaignGroupCustomer.setPushStatus("1");
            if (e.getUserId() != null) {
                sysCampaignGroupCustomer.setOrgDistributeStatus("1");
                sysCampaignGroupCustomer.setSecondPushStatus("1");
                sysCampaignGroupCustomer.setOrgClaimStatus("1");
                if (qz_claimType.equals(sysCampaign.getClaimType())) {
                    sysCampaignGroupCustomer.setCustClaimStatus("1");
                } else {
                    sysCampaignGroupCustomer.setCustClaimStatus("0");
                }
            }else{
                sysCampaignGroupCustomer.setSecondPushStatus("0");
                if (qz_claimType.equals(sysCampaign.getClaimType())) {
                    sysCampaignGroupCustomer.setOrgClaimStatus("1");
                } else {
                    sysCampaignGroupCustomer.setOrgClaimStatus("0");
                }
            }
            return sysCampaignGroupCustomer;
        }).collect(Collectors.toList());
        campaignGroupCustomers.addAll(collect);


        List<SysGroupCustomer> directDistributeLists = new ArrayList<>();
        //优先按照导入模板里面的归属关系分配，若无归属客户经理和部门再按照选择的优先级分配规则去分配
        //先筛选出无地址与电话的客户，无法推送清单
        sysGroupCustomers = filterAddressAndPhone(sysGroupCustomers,campaignGroupCustomers,campaignId);
        //优先按照导入模板里面的归属关系分配，若无归属客户经理和部门再按照选择的优先级分配规则去分配
        if (sysGroupCustomers!=null&&sysGroupCustomers.size()>0){
            sysGroupCustomers = getUnDirectDistributeList(sysGroupCustomers,campaignGroupCustomers,sysCampaign);
        }

        if (sysCampaign.getDistributeType() != null) {
            //按照管户关系分配或者地址分配
            List<String> distributeRules = Arrays.asList(sysCampaign.getDistributeType().split(","));

            distribute(sysCampaign,distributeRules,sysGroupCustomers,null,campaignId,campaignGroupCustomers);

        }

        if (campaignGroupCustomers.size()>0){
            List<SysCampaignGroupCustomer> campaignGroupCustomersRemove = new ArrayList<>();
            campaignGroupCustomers.forEach( e ->{
                SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                sysCampaignGroupCustomer.setCampaignId(campaignId);
                sysCampaignGroupCustomer.setCustId(e.getCustId());
                sysCampaignGroupCustomer.setDeptId(e.getDeptId());
                sysCampaignGroupCustomer.setUserId(e.getUserId());
                //  是否下发机构标志  true下发机构
                 sysCampaignGroupCustomer.setDeptFlag(e.getUserId() == null ? "ture" : null);
                List<SysCampaignGroupCustomer> sysCampaignGroupCustomers = sysCampaignGroupCustomerMapper.selectSysCampaignGroupCustomerList(sysCampaignGroupCustomer);
                if(sysCampaignGroupCustomers.size() > 0){
                    campaignGroupCustomersRemove.add(e);
                }
            });
            log.info("重复添加的活动客户-》"+ campaignGroupCustomersRemove.stream().map(SysCampaignGroupCustomer:: getCustId).collect(Collectors.toList()));
            campaignGroupCustomers.removeAll(campaignGroupCustomersRemove);
            if(campaignGroupCustomers.size()>0) {
                campaignGroupCustomers.forEach(e->{
                    e.setPushUserLevel(ROLE_HEAD.equalsIgnoreCase(userRoleHeadOrBranch()) ? "head" : "branch");
                    e.setSecondPushStatus(null);
                });
                //   对于新增客户下发到存量活动中，如果下发完成，则  下发后，如果下发成功，机构认领状态为空已认领， 机构分配状态为已经分配，按照 早先分配规则完成分配，客户认领状态为待认领
                //   如果本身是支行，则无需处理，仅处理总行即可
                if( ROLE_HEAD.equalsIgnoreCase(userRoleHeadOrBranch()) ){
                    // 本次新增客户中，下发到支行的数据列表
                    List<SysCampaignGroupCustomer> collectBranch = campaignGroupCustomers.stream().filter(e -> e.getDeptId() != null && e.getOutletsId()== null  && e.getUserId() == null).collect(Collectors.toList());
                    if(collectBranch != null && collectBranch.size() > 0){
                        log.info("本次新增客户需要进行 支行二次分配的列表： "  + collectBranch.stream().map(SysCampaignGroupCustomer:: getCustId).collect(Collectors.toList()) );
                        campaignGroupCustomers.removeAll(collectBranch);
                        // 按照支行分组处理
                        Map<Long, List<SysCampaignGroupCustomer>> groupedByDeptId = collectBranch.stream()
                                .collect(Collectors.groupingBy(SysCampaignGroupCustomer::getDeptId));
                        groupedByDeptId.forEach((deptId, sysCampaignGroupBranchCustomers) -> {
                            // 查询支行二次分配的规则
                            SysCampaign sysCampaignBranchSecond = sysCampaignMapper.selectSysCampaignSecondByCampaignId(campaignId, deptId,null);
                            if( sysCampaignBranchSecond != null  ){
                                // 该支行存在二次分配规则
                                sysCampaignBranchSecond.setExecuter("1");
                                List<String> custIBranchds = sysCampaignGroupBranchCustomers.stream().map(e -> e.getCustId()).collect(Collectors.toList());
                                List<SysGroupCustomer> sysGroupCustomersBranch = sysCampaignGroupBranchCustomers.stream().map(e -> {
                                    SysGroupCustomer sysGroupCustomerE = new SysGroupCustomer();
                                    BeanUtils.copyProperties(e, sysGroupCustomerE);
                                    // 根据需要设置其他属性
                                    return sysGroupCustomerE;
                                }).collect(Collectors.toList());
                                distribute(sysCampaignBranchSecond,Arrays.asList(sysCampaignBranchSecond.getDistributeType().split(",")),sysGroupCustomersBranch,null,campaignId,sysCampaignGroupBranchCustomers);
                                sysCampaignGroupBranchCustomers.forEach(e->{
                                    e.setOrgClaimStatus("1");
                                    e.setOrgDistributeStatus("1");
                                    e.setPushStatus("1");
                                    e.setPushUserLevel("branch");
                                    e.setSecondPushStatus( e.getUserId()!=null ?  "1" : Arrays.asList(sysCampaignBranchSecond.getDistributeType().split(",")).contains("0") ? "0" : "2");
                                });
                            }
                            campaignGroupCustomers.addAll(sysCampaignGroupBranchCustomers);
                        });
                    }

                    // 本次新增客户中，下发到網點的数据列表
                    List<SysCampaignGroupCustomer> collectOutlet = campaignGroupCustomers.stream().filter(e -> e.getOutletsId() != null  && e.getUserId() == null).collect(Collectors.toList());
                    if(collectOutlet != null && collectOutlet.size() > 0){
                        log.info("本次新增客户需要进行 网点二次分配的列表： "  + collectOutlet.stream().map(SysCampaignGroupCustomer:: getCustId).collect(Collectors.toList()) );
                        campaignGroupCustomers.removeAll(collectOutlet);
                        // 按照网点分组处理
                        Map<Long, List<SysCampaignGroupCustomer>> groupedByOutletId = collectOutlet.stream()
                                .collect(Collectors.groupingBy(SysCampaignGroupCustomer::getOutletsId));
                        groupedByOutletId.forEach((outletsId, sysCampaignGroupOutletCustomers) -> {
                            // 查询支行二次分配的规则
                            SysCampaign sysCampaignOutletSecond = sysCampaignMapper.selectSysCampaignSecondByCampaignId(campaignId, null,outletsId);
                            if( sysCampaignOutletSecond != null  ){
                                // 存在二次分配规则
                                sysCampaignOutletSecond.setExecuter("3");
                                List<SysGroupCustomer> sysGroupCustomersBranch = sysCampaignGroupOutletCustomers.stream().map(e -> {
                                    SysGroupCustomer sysGroupCustomerE = new SysGroupCustomer();
                                    BeanUtils.copyProperties(e, sysGroupCustomerE);
                                    // 根据需要设置其他属性
                                    return sysGroupCustomerE;
                                }).collect(Collectors.toList());
                                distribute(sysCampaignOutletSecond,Arrays.asList(sysCampaignOutletSecond.getDistributeType().split(",")),sysGroupCustomersBranch,null,campaignId,sysCampaignGroupOutletCustomers);
                                sysCampaignGroupOutletCustomers.forEach(e->{
                                    e.setOrgClaimStatus("1");
                                    e.setOrgDistributeStatus("1");
                                    e.setPushStatus("1");
                                    e.setPushUserLevel("outlet");
                                    e.setSecondPushStatus( e.getUserId()!=null ?  "1" : Arrays.asList(sysCampaignOutletSecond.getDistributeType().split(",")).contains("0") ? "0" : "2");
                                });
                            }
                            campaignGroupCustomers.addAll(sysCampaignGroupOutletCustomers);
                        });
                    }
                }

                if(ROLE_BRANCH.equalsIgnoreCase(userRoleHeadOrBranch())){
                    //  如果是支行 添加的客户，任务一定是已经有分配规则的，一次推送一定成功，二次推送状态 按照一次推送状态重置，保证机构推送状态字段无误
                    campaignGroupCustomers.forEach(e->{
                        e.setSecondPushStatus(e.getPushStatus());
                        e.setPushStatus("1");
                    });
                }


                sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomerBatch(campaignGroupCustomers);
            }
        }

        return 1;
    }



    public List<SysGroupCustomer> getUnDirectDistributeList(List<SysGroupCustomer> sysGroupCustomers, List<SysCampaignGroupCustomer> campaignGroupCustomers,SysCampaign sysCampaign){
        String roleName = userRole();
        List<SysGroupCustomer> directDistributeLists = new ArrayList<>();
        if (sysGroupCustomers!=null&&sysGroupCustomers.size()>0){
            directDistributeLists = sysGroupCustomers.stream().filter(s->s.getDeptId()!=null).filter(s->s.getUserId()!=null).
                    collect(Collectors.toList());
            if (ROLE_BRANCH.equals(roleName)){
                //支行仅能直接推送其客群下的客户
                directDistributeLists = directDistributeLists.stream().filter(s->getDeptId().equals(s.getDeptId())).
                        collect(Collectors.toList());
            }
            directDistributeLists.forEach(d->d.setPushStatus("1"));
            //存储可以直接根据模板推送的客群关系
            campaignGroupCustomers.addAll(directDistributeLists.stream().map(d->{
                        SysCampaignGroupCustomer campaignGroupCustomer = new SysCampaignGroupCustomer();
                        BeanUtils.copyProperties(d,campaignGroupCustomer);
                        //campaignGroupCustomer.setPushStatus("1");
                        if (ROLE_HEAD.equals(roleName)){
                            campaignGroupCustomer.setCreateRole("0");
                        } else if (ROLE_BRANCH.equals(roleName)){
                            campaignGroupCustomer.setCreateRole("5");
                        } else if (ROLE_HeadOps.equals(roleName)){
                    campaignGroupCustomer.setCreateRole("3");
                         } else if (ROLE_HeadPublic.equals(roleName)){
                             campaignGroupCustomer.setCreateRole("2");
                         } else if (ROLE_HeadPrivate.equals(roleName)){
                            campaignGroupCustomer.setCreateRole("1");
                        }
                        campaignGroupCustomer.setCampaignId(sysCampaign.getCampaignId());
                        campaignGroupCustomer.setSecondPushStatus("0");
                        grStatusSet(campaignGroupCustomer,sysCampaign.getClaimType());
                        return campaignGroupCustomer;
                    }
            ).collect(Collectors.toList()));
            //获取无法直接根据模板分配的list
            sysGroupCustomers.removeAll(directDistributeLists);
            //直接推送的状态修改为1
        }
        return sysGroupCustomers;
    }
    @Async
    @Override
    public void distribute(SysCampaign sysCampaign,List<String> distributeRules,List<SysGroupCustomer> sysGroupCustomers,String groupId,String campaignId,List<SysCampaignGroupCustomer> campaignGroupCustomers){
        String roleName = userRole();
        List<SysGroupCustomer> noCustIds = sysGroupCustomers.stream().filter(s->StringUtils.isBlank(s.getCustId())).collect(Collectors.toList());
        for (int i = 0; i <noCustIds.size() ; i++) {
            //没有客户号的客户无法推送
            SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            BeanUtils.copyProperties(noCustIds.get(i), sysCampaignGroupCustomer);
            sysCampaignGroupCustomer.setPushStatus("3");
            campaignGroupCustomers.add(sysCampaignGroupCustomer);
        }
        sysGroupCustomers.removeAll(noCustIds);
        if (distributeRules != null&&distributeRules.size()>0) {
            int k = 0;//虚拟网格分配方式计数
            int l = 0;//特色网格分配方式计数

            for (int j = 0; j <distributeRules.size();j++){
                //按照行政网格
                if (distributeRules.get(j).length()==2&&'2'==distributeRules.get(j).charAt(0)) {
                    String opsDept = distributeRules.get(j).substring(1);
                    distributeDZ(sysCampaign,sysGroupCustomers,groupId,campaignId,campaignGroupCustomers,opsDept);
                }
                //按照特色网格
                if (distributeRules.get(j).length()==2&&'4'==distributeRules.get(j).charAt(0)) {
                    //todo 根据部室与特色网格类型查询特色网格列表
                    List<Long> layerIds = sysCampaign.getLayerIds();
                    String opsDept = String.valueOf(distributeRules.get(j).charAt(1));
                    if (layerIds.size()>l){
                        Long layerId = layerIds.get(l);
                        LayerGridDTO layerGridDTO = new LayerGridDTO();
                        layerGridDTO.setLayerId(layerId);
                        layerGridDTO.setOpsDept(opsDept);
                        List<DrawGrid> drawGrids = drawLayerService.getDrawGridList(layerGridDTO);
                        List<Long> gridIds = drawGrids.stream().map(DrawGrid::getGridId).collect(Collectors.toList());
                        if (gridIds.size()>0){
                            distributeTs(sysCampaign,sysGroupCustomers,groupId,campaignId,campaignGroupCustomers,gridIds);
                        }
                        ++l;
                    }

                }
                //按照虚拟网格
                if (distributeRules.get(j).length()==2&&'5'==distributeRules.get(j).charAt(0)) {
                    //todo 根据部室与虚拟网格名称查询虚拟网格列表
                    List<Long> virtualGridIds = sysCampaign.getVirtualGridIds();
                    if (virtualGridIds.size()>k){
                        Long gridId = virtualGridIds.get(k);
                        distributeXN(sysCampaign,sysGroupCustomers,groupId,campaignId,campaignGroupCustomers,gridId);
                        ++k;
                    }

                }
                //按照管户关系分配
                if (distributeRules.get(j).length()>3){
                    distributeGH(sysCampaign,sysGroupCustomers,groupId,campaignId,campaignGroupCustomers,distributeRules.get(j));
                }
                //随机平均分配
                if (sj_campaignDistributeType.equals(distributeRules.get(j))){
                    distributeSJ(sysCampaign,sysGroupCustomers,groupId,campaignId,campaignGroupCustomers);
                }
            }
            //各分配规则分配完后仍有未分配客户，则直接置为分配失败
            if (sysGroupCustomers.size()>0){
                //剩余的直接随机平均分配
                for (int i = 0; i <sysGroupCustomers.size() ; i++) {
                    SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                    BeanUtils.copyProperties(sysGroupCustomers.get(i), sysCampaignGroupCustomer);
                    sysCampaignGroupCustomer.setCampaignId(campaignId);
                    //最后选择的分配规则为手动指定，则剩余客户为未推送，否则为推送失败
                    if (sd_campaignDistributeType.equals(distributeRules.get(distributeRules.size()-1))){
                        sysCampaignGroupCustomer.setPushStatus("0");
                    }else {
                        sysCampaignGroupCustomer.setPushStatus("2");
                    }
                    campaignGroupCustomers.add(sysCampaignGroupCustomer);
                }
            }

        }

    }
    //地址分配方式
    public void distributeDZ(SysCampaign sysCampaign,List<SysGroupCustomer> sysGroupCustomers,String groupId,String campaignId,List<SysCampaignGroupCustomer> campaignGroupCustomers,String opsDept){
        String roleName = userRole();
        List<SysGroupCustomer> distributeDzList = new ArrayList<>();
        sysGroupCustomers.forEach(groupCustomer -> {
            SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            BeanUtils.copyProperties(groupCustomer, sysCampaignGroupCustomer);


            CustDeptUserGrid custDeptUserGrid = new CustDeptUserGrid();
            String custId = groupCustomer.getCustId();
            //根据匹配表中关联关系查询到对应的客户归属
            custDeptUserGrid.setCustId(custId);
            custDeptUserGrid.setOpsDept(opsDept);
            if (ROLE_BRANCH.equals(roleName)){
                custDeptUserGrid.setDeptId(getDeptId());
            }
            List<CustDeptUserGrid> custDeptUserGrids = custDeptUserGridMapper.selectCustDeptUserGridList(custDeptUserGrid);
            custDeptUserGrids = custDeptUserGrids.stream().filter(c->c.getDeptId()!=null).collect(Collectors.toList());
            //归属用户不为空，则分配成功
            if (custDeptUserGrids.size()>0) {
                //能找到归属关系，则直接去除该客户，避免二次分配
                distributeDzList.add(groupCustomer);
                logger.info(groupCustomer.getCustId()+"客户归属关系情况"+custDeptUserGrids);
                Map<Long,List<CustDeptUserGrid>> custMaps = custDeptUserGrids.stream().collect(Collectors.groupingBy(CustDeptUserGrid::getDeptId));
                if (jg_executer.equals(sysCampaign.getExecuter()) || wd_executer.equals(sysCampaign.getExecuter())){
                    //执行人为机构的情况下，即使有多条管户关系，也只需要推送到同一个客户到同一个机构下一条
                    for (Long l : custMaps.keySet()){
                        List<CustDeptUserGrid> custDeptUserGridList = custMaps.get(l);
                        if (custDeptUserGridList.size()>=1){
                            BeanUtils.copyProperties(custDeptUserGridList.get(0), sysCampaignGroupCustomer);
                            //取导入模板里面的电话与证件号
                            sysCampaignGroupCustomer.setCustPhone(groupCustomer.getCustPhone());
                            sysCampaignGroupCustomer.setCustIdc(groupCustomer.getCustIdc());
                            campaignGroupStatusSet(sysCampaign,sysCampaignGroupCustomer,custDeptUserGrids.get(0));
                            campaignGroupCustomers.add(sysCampaignGroupCustomer);
                            initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                            sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                            sysCampaignGroupCustomer.setGroupId(groupId);
                            sysCampaignGroupCustomer.setDelFlag("0");
                            sysCampaignGroupCustomer.setSecondPushStatus("0");
                            //groupCustomer.setPushStatus("1");
                        }

                    }

                }
                if (ROLE_BRANCH.equals(roleName)||gr_executer.equals(sysCampaign.getExecuter())||hh_executer.equals(sysCampaign.getExecuter())){
                    for (int i = 0; i < custDeptUserGrids.size(); i++) {
                        BeanUtils.copyProperties(custDeptUserGrids.get(i), sysCampaignGroupCustomer);
                        //取导入模板里面的电话与证件号
                        sysCampaignGroupCustomer.setCustPhone(groupCustomer.getCustPhone());
                        sysCampaignGroupCustomer.setCustIdc(groupCustomer.getCustIdc());
                        if (campaignGroupStatusSet(sysCampaign,sysCampaignGroupCustomer,custDeptUserGrids.get(i))==null){
                            //能找到归属关系，但是归属关系里无客户id，推送失败
                            initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                            sysCampaignGroupCustomer.setPushStatus("2");
                            campaignGroupCustomers.add(sysCampaignGroupCustomer);
                            //groupCustomer.setPushStatus("2");
                            continue;
                        }
                        initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                        campaignGroupCustomers.add(sysCampaignGroupCustomer);
                        //groupCustomer.setPushStatus("1");
                        sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                        sysCampaignGroupCustomer.setGroupId(groupId);
                        sysCampaignGroupCustomer.setDelFlag("0");
                        sysCampaignGroupCustomer.setSecondPushStatus("0");
                        //sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomer(sysCampaignGroupCustomer);


                    }
                }


            }

        });
        sysGroupCustomers.removeAll(distributeDzList);

    }


    //虚拟网格分配方式
    public void distributeXN(SysCampaign sysCampaign,List<SysGroupCustomer> sysGroupCustomers,String groupId,String campaignId,List<SysCampaignGroupCustomer> campaignGroupCustomers,Long gridId){
        String roleName = userRole();
        List<SysGroupCustomer> distributeDzList = new ArrayList<>();
        sysGroupCustomers.forEach(groupCustomer -> {
            SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            BeanUtils.copyProperties(groupCustomer, sysCampaignGroupCustomer);

            VirtualCustUser virtualCustUser  = new VirtualCustUser();
            String custId = groupCustomer.getCustId();
            //根据匹配表中关联关系查询到对应的客户归属
            virtualCustUser.setCustId(custId);
            virtualCustUser.setGridId(gridId);
            if (ROLE_BRANCH.equals(roleName)){
                virtualCustUser.setRelateDeptId(getDeptId());
            }
            List<VirtualCustUser> virtualCustUsers = virtualCustUserMapper.selectVirtualCustUserList(virtualCustUser);
            virtualCustUsers = virtualCustUsers.stream().filter(c->c.getRelateDeptId()!=null).collect(Collectors.toList());
            //归属用户不为空，则分配成功
            if (virtualCustUsers.size()>0) {
                //能找到归属关系，则直接去除该客户，避免二次分配
                distributeDzList.add(groupCustomer);
                logger.info(groupCustomer.getCustId()+"客户归属关系情况"+virtualCustUsers);
                Map<Long,List<VirtualCustUser>> custMaps = virtualCustUsers.stream().collect(Collectors.groupingBy(VirtualCustUser::getRelateDeptId));
                if (jg_executer.equals(sysCampaign.getExecuter()) || wd_executer.equals(sysCampaign.getExecuter())){
                    //执行人为机构的情况下，即使有多条管户关系，也只需要推送到同一个客户到同一个机构下一条
                    for (Long l : custMaps.keySet()){
                        List<VirtualCustUser> virtualCustUserList = custMaps.get(l);
                        if (virtualCustUserList.size()>=1){
                            DeptAndOutlets deptAndOutlet = sysCampaignMapper.selectDeptAndOutletsByUserName(virtualCustUserList.get(0).getUserName());
                            BeanUtils.copyProperties(deptAndOutlet,sysCampaignGroupCustomer);
                            campaignGroupStatusSetXN(sysCampaign,sysCampaignGroupCustomer,virtualCustUsers.get(0));
                            campaignGroupCustomers.add(sysCampaignGroupCustomer);
                            initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                            sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                            sysCampaignGroupCustomer.setGroupId(groupId);
                            sysCampaignGroupCustomer.setDelFlag("0");
                            sysCampaignGroupCustomer.setSecondPushStatus("0");
                            //groupCustomer.setPushStatus("1");
                        }

                    }

                }
                if (ROLE_BRANCH.equals(roleName)||gr_executer.equals(sysCampaign.getExecuter())||hh_executer.equals(sysCampaign.getExecuter())){
                    for (int i = 0; i < virtualCustUsers.size(); i++) {
                        DeptAndOutlets deptAndOutlet = sysCampaignMapper.selectDeptAndOutletsByUserName(virtualCustUsers.get(i).getUserName());
                        BeanUtils.copyProperties(deptAndOutlet,sysCampaignGroupCustomer);
                        if (campaignGroupStatusSetXN(sysCampaign,sysCampaignGroupCustomer,virtualCustUsers.get(i))==null){
                            //能找到归属关系，但是归属关系里无客户id，推送失败
                            initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                            sysCampaignGroupCustomer.setPushStatus("2");
                            campaignGroupCustomers.add(sysCampaignGroupCustomer);
                            //groupCustomer.setPushStatus("2");
                            continue;
                        }
                        initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                        campaignGroupCustomers.add(sysCampaignGroupCustomer);
                        //groupCustomer.setPushStatus("1");
                        sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                        sysCampaignGroupCustomer.setGroupId(groupId);
                        sysCampaignGroupCustomer.setDelFlag("0");
                        sysCampaignGroupCustomer.setSecondPushStatus("0");
                        //sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomer(sysCampaignGroupCustomer);


                    }
                }


            }

        });
        sysGroupCustomers.removeAll(distributeDzList);

    }

    //特色分配方式
    public void distributeTs(SysCampaign sysCampaign,List<SysGroupCustomer> sysGroupCustomers,String groupId,String campaignId,List<SysCampaignGroupCustomer> campaignGroupCustomers,List<Long> gridIds){
        String roleName = userRole();
        List<SysGroupCustomer> distributeDzList = new ArrayList<>();
        List<GridInfoTs> gridInfos = sysCampaignMapper.selectGridInfoTsByGridIds(gridIds);
        sysGroupCustomers.forEach(groupCustomer -> {
            SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            BeanUtils.copyProperties(groupCustomer, sysCampaignGroupCustomer);
            List<GridInfoTs> gridInfoTsList = gridInfos.stream().filter(c->c.getCustId().equals(groupCustomer.getCustId())).collect(Collectors.toList());
            //归属用户不为空，则分配成功
            if (gridInfoTsList.size()>0) {
                //能找到归属关系，则直接去除该客户，避免二次分配
                distributeDzList.add(groupCustomer);
                logger.info(groupCustomer.getCustId()+"客户归属关系情况"+gridInfoTsList);
                Map<Long,List<GridInfoTs>> custMaps = gridInfoTsList.stream().collect(Collectors.groupingBy(GridInfoTs::getRelateDeptId));
                if (jg_executer.equals(sysCampaign.getExecuter()) || wd_executer.equals(sysCampaign.getExecuter())){
                    //执行人为机构的情况下，即使有多条管户关系，也只需要推送到同一个客户到同一个机构下一条
                    for (Long l : custMaps.keySet()){
                        List<GridInfoTs> TsCustUserList = custMaps.get(l);
                        if (TsCustUserList.size()>=1){
                            DeptAndOutlets deptAndOutlet = sysCampaignMapper.selectDeptAndOutletsByUserName(TsCustUserList.get(0).getUserName());
                            BeanUtils.copyProperties(deptAndOutlet,sysCampaignGroupCustomer);
                            campaignGroupStatusSetTs(sysCampaign,sysCampaignGroupCustomer,TsCustUserList.get(0));
                            campaignGroupCustomers.add(sysCampaignGroupCustomer);
                            initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                            sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                            sysCampaignGroupCustomer.setGroupId(groupId);
                            sysCampaignGroupCustomer.setDelFlag("0");
                            sysCampaignGroupCustomer.setSecondPushStatus("0");
                            //groupCustomer.setPushStatus("1");
                        }

                    }

                }
                if (ROLE_BRANCH.equals(roleName)||gr_executer.equals(sysCampaign.getExecuter())||hh_executer.equals(sysCampaign.getExecuter())){
                    for (int i = 0; i < gridInfoTsList.size(); i++) {
                        DeptAndOutlets deptAndOutlet = sysCampaignMapper.selectDeptAndOutletsByUserName(gridInfoTsList.get(i).getUserName());
                        BeanUtils.copyProperties(deptAndOutlet,sysCampaignGroupCustomer);
                        if (campaignGroupStatusSetTs(sysCampaign,sysCampaignGroupCustomer,gridInfoTsList.get(i))==null){
                            //能找到归属关系，但是归属关系里无客户id，推送失败
                            initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                            sysCampaignGroupCustomer.setPushStatus("2");
                            campaignGroupCustomers.add(sysCampaignGroupCustomer);
                            //groupCustomer.setPushStatus("2");
                            continue;
                        }
                        initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                        campaignGroupCustomers.add(sysCampaignGroupCustomer);
                        //groupCustomer.setPushStatus("1");
                        sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                        sysCampaignGroupCustomer.setGroupId(groupId);
                        sysCampaignGroupCustomer.setDelFlag("0");
                        sysCampaignGroupCustomer.setSecondPushStatus("0");
                        //sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomer(sysCampaignGroupCustomer);


                    }
                }


            }

        });
        sysGroupCustomers.removeAll(distributeDzList);

    }
    //管户分配方式
    public void distributeGH(SysCampaign sysCampaign,List<SysGroupCustomer> sysGroupCustomers,String groupId,String campaignId,List<SysCampaignGroupCustomer> campaignGroupCustomers,String distributeRule){
        String roleName = userRole();
        String codeLevel1 = distributeRule.substring(0, 3);
        String codeLevel2 = distributeRule.substring(3,6);
        List<SysGroupCustomer> distributeGHList = new ArrayList<>();
        sysGroupCustomers.forEach(groupCustomer -> {
            SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            BeanUtils.copyProperties(groupCustomer, sysCampaignGroupCustomer);


            CustDeptUserCmpm custDeptUserCmpm= new CustDeptUserCmpm();
            String custId = groupCustomer.getCustId();
            custDeptUserCmpm.setCodeNoLevel1(codeLevel1);
            custDeptUserCmpm.setCodeNoLevel2(codeLevel2);
            //根据匹配表中关联关系查询到对应的客户归属
            custDeptUserCmpm.setCustId(custId);
            if (ROLE_BRANCH.equals(roleName)){
                custDeptUserCmpm.setDeptId(getDeptId());
            }
            List<CustDeptUserCmpm> custDeptUserCmpms = custDeptUserCmpmMapper.selectCustDeptUserCmpmList(custDeptUserCmpm);
            custDeptUserCmpms = custDeptUserCmpms.stream().filter(c->c.getDeptId()!=null).collect(Collectors.toList());
            //归属用户不为空，则分配成功
            if (custDeptUserCmpms.size()>0) {
                //能找到归属关系，则直接去除该客户，避免二次分配
                distributeGHList.add(groupCustomer);
                logger.info(groupCustomer.getCustId()+"客户归属关系情况"+custDeptUserCmpms);
                Map<Long,List<CustDeptUserCmpm>> custMaps = custDeptUserCmpms.stream().collect(Collectors.groupingBy(CustDeptUserCmpm::getDeptId));
                if (jg_executer.equals(sysCampaign.getExecuter()) || wd_executer.equals(sysCampaign.getExecuter())){
                    //执行人为机构的情况下，即使有多条管户关系，也只需要推送到同一个客户到同一个机构下一条
                    for (Long l : custMaps.keySet()){
                        List<CustDeptUserCmpm> custDeptUserCmpmList = custMaps.get(l);
                        if (custDeptUserCmpmList.size()>=1){
                            BeanUtils.copyProperties(custDeptUserCmpmList.get(0), sysCampaignGroupCustomer);
                            //取导入模板里面的电话与证件号
                            sysCampaignGroupCustomer.setCustIdc(groupCustomer.getCustIdc());
                            campaignGroupStatusSetCmpm(sysCampaign,sysCampaignGroupCustomer,custDeptUserCmpmList.get(0));
                            campaignGroupCustomers.add(sysCampaignGroupCustomer);
                            initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                            sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                            sysCampaignGroupCustomer.setGroupId(groupId);
                            sysCampaignGroupCustomer.setDelFlag("0");
                            sysCampaignGroupCustomer.setSecondPushStatus("0");
                            //groupCustomer.setPushStatus("1");
                        }

                    }

                }
                if (ROLE_BRANCH.equals(roleName)||gr_executer.equals(sysCampaign.getExecuter())||hh_executer.equals(sysCampaign.getExecuter())){
                    for (int i = 0; i < custDeptUserCmpms.size(); i++) {
                        BeanUtils.copyProperties(custDeptUserCmpms.get(i), sysCampaignGroupCustomer);
                        //取导入模板里面的电话与证件号
                        sysCampaignGroupCustomer.setCustIdc(groupCustomer.getCustIdc());
                        if (campaignGroupStatusSetCmpm(sysCampaign,sysCampaignGroupCustomer,custDeptUserCmpms.get(i))==null){
                            //能找到归属关系，但是归属关系里无客户id，推送失败
                            groupCustomer.setPushStatus("2");
                            continue;
                        }
                        initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                        campaignGroupCustomers.add(sysCampaignGroupCustomer);
                        //groupCustomer.setPushStatus("1");
                        sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                        sysCampaignGroupCustomer.setGroupId(groupId);
                        sysCampaignGroupCustomer.setDelFlag("0");
                        sysCampaignGroupCustomer.setSecondPushStatus("0");
                        //sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomer(sysCampaignGroupCustomer);


                    }
                }


            }

        });
        sysGroupCustomers.removeAll(distributeGHList);

    }
    //随机分配
    public void distributeSJ(SysCampaign sysCampaign,List<SysGroupCustomer> sysGroupCustomers,String groupId,String campaignId,List<SysCampaignGroupCustomer> campaignGroupCustomers){
        List<Long> userIds = sysCampaign.getUserIds();
        if (userIds==null||userIds.size()==0){
            return;
        }
        List<DeptAndOutlets> deptAndOutlets = selectDeptAndOutletsByUserIds(userIds);
        //客户数小于用户数，直接分配给第一个用户
        if (sysGroupCustomers.size()<userIds.size()){
            SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            for (int i = 0; i < sysGroupCustomers.size(); i++) {
                SysGroupCustomer groupCustomer = sysGroupCustomers.get(i);
                BeanUtils.copyProperties(groupCustomer, sysCampaignGroupCustomer);
                initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                grStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
                DeptAndOutlets deptAndOutlet = selectDeptAndOutletsByUserId(deptAndOutlets,userIds.get(0));
                BeanUtils.copyProperties(deptAndOutlet,sysCampaignGroupCustomer);
                //sysCampaignGroupCustomer.setUserId(userIds.get(0));
                campaignGroupCustomers.add(sysCampaignGroupCustomer);
                sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            }

        }else{
            int length = sysGroupCustomers.size()/userIds.size();
            int remainder = sysGroupCustomers.size()%userIds.size();
            List<List<SysGroupCustomer>> splitLists = splitList(sysGroupCustomers,length);
            for (int i = 0; i < userIds.size(); i++) {
                List<SysGroupCustomer> splitGroupCustomerList = splitLists.get(i);
                for (int j = 0; j < splitGroupCustomerList.size(); j++) {
                    SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                    SysGroupCustomer groupCustomer = splitGroupCustomerList.get(j);
                    BeanUtils.copyProperties(groupCustomer, sysCampaignGroupCustomer);
                    initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                    grStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
                    DeptAndOutlets deptAndOutlet = selectDeptAndOutletsByUserId(deptAndOutlets,userIds.get(i));
                    BeanUtils.copyProperties(deptAndOutlet,sysCampaignGroupCustomer);
                    //sysCampaignGroupCustomer.setUserId(userIds.get(i));
                    campaignGroupCustomers.add(sysCampaignGroupCustomer);
                    sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                }

            }
            for (int i = sysGroupCustomers.size()-1 ; i >= sysGroupCustomers.size()-remainder;  i--) {
                    SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                    SysGroupCustomer groupCustomer = sysGroupCustomers.get(i);
                    BeanUtils.copyProperties(groupCustomer, sysCampaignGroupCustomer);
                    initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                    grStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
                    DeptAndOutlets deptAndOutlet = selectDeptAndOutletsByUserId(deptAndOutlets,userIds.get(0));
                    BeanUtils.copyProperties(deptAndOutlet,sysCampaignGroupCustomer);
                    //sysCampaignGroupCustomer.setUserId(userIds.get(0));
                    campaignGroupCustomers.add(sysCampaignGroupCustomer);
                    sysCampaignGroupCustomer = new SysCampaignGroupCustomer();

            }


        }
        //随机分配后，待推送客群置空
        sysGroupCustomers.clear();
        //todo随机分配时分配客户经理的机构号和网点号
    }


    public SysCampaignGroupCustomer initSysCampaignGroupCustomer(SysCampaignGroupCustomer sysCampaignGroupCustomer,String campaignId){
        String roleName = userRole();
        sysCampaignGroupCustomer.setPushStatus("1");
        sysCampaignGroupCustomer.setListType("0");
        if (ROLE_HEAD.equals(roleName)){
            sysCampaignGroupCustomer.setCreateRole("0");
        } else if (ROLE_BRANCH.equals(roleName)){
            sysCampaignGroupCustomer.setCreateRole("5");
        } else if (ROLE_HeadOps.equals(roleName)){
            sysCampaignGroupCustomer.setCreateRole("3");
        } else if (ROLE_HeadPublic.equals(roleName)){
            sysCampaignGroupCustomer.setCreateRole("2");
        } else if (ROLE_HeadPrivate.equals(roleName)){
            sysCampaignGroupCustomer.setCreateRole("1");
        }
        sysCampaignGroupCustomer.setCampaignId(campaignId);
        sysCampaignGroupCustomer.setCreateTime(new Date());
        sysCampaignGroupCustomer.setCreateBy(getUsername());
        sysCampaignGroupCustomer.setSecondPushStatus("0");
        sysCampaignGroupCustomer.setDelFlag("0");
        return sysCampaignGroupCustomer;
    }

    //活动相关机构认领状态，机构分配状态，客户经理认领状态设置
    public SysCampaignGroupCustomer campaignGroupStatusSet(SysCampaign sysCampaign,SysCampaignGroupCustomer sysCampaignGroupCustomer,CustDeptUserGrid custDeptUserGrid){
        String roleName = userRole();
        if (jg_executer.equals(sysCampaign.getExecuter()) || wd_executer.equals(sysCampaign.getExecuter())) {
            //执行人为机构的情况下,仅将客群分配到机构
            jgStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
        }
        //支行管理员默认只能分配到个人
        if (ROLE_BRANCH.equals(roleName)||gr_executer.equals(sysCampaign.getExecuter())) {
            //需要分配到个人，但归属关系表里无客户经理id，则直接返回，无法分配
            if (custDeptUserGrid.getUserId()==null){
                return null;
            }
            grStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
        }
        if (hh_executer.equals(sysCampaign.getExecuter())) {
            //执行人为执行人为混合分配的情况下,若客户对应客户经理id存在，则直接分配个人
            if (custDeptUserGrid.getUserId()!=null){
                grStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
            }
            //执行人为执行人为混合分配的情况下,若无归属用户但有归属机构，则分配到机构
            if (custDeptUserGrid.getUserId()==null&&custDeptUserGrid.getDeptId()!=null){
                //执行人为混合分配,强制认领时，设置客户经理认领状态为已认领
                jgStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
            }
        }

        return sysCampaignGroupCustomer;

    }

    public SysCampaignGroupCustomer campaignGroupStatusSetXN(SysCampaign sysCampaign,SysCampaignGroupCustomer sysCampaignGroupCustomer,VirtualCustUser virtualCustUser){
        String roleName = userRole();
        if (jg_executer.equals(sysCampaign.getExecuter()) || wd_executer.equals(sysCampaign.getExecuter())) {
            //执行人为机构的情况下,仅将客群分配到机构
            jgStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
        }
        //支行管理员默认只能分配到个人
        if (ROLE_BRANCH.equals(roleName)||gr_executer.equals(sysCampaign.getExecuter())) {
            //需要分配到个人，但归属关系表里无客户经理id，则直接返回，无法分配
            if (virtualCustUser.getUserName()==null){
                return null;
            }
            grStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
        }
        if (hh_executer.equals(sysCampaign.getExecuter())) {
            //执行人为执行人为混合分配的情况下,若客户对应客户经理id存在，则直接分配个人
            if (virtualCustUser.getUserName()!=null){
                grStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
            }
            //执行人为执行人为混合分配的情况下,若无归属用户但有归属机构，则分配到机构
            if (virtualCustUser.getUserName()==null&&virtualCustUser.getRelateDeptId()!=null){
                //执行人为混合分配,强制认领时，设置客户经理认领状态为已认领
                jgStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
            }
        }

        return sysCampaignGroupCustomer;

    }

    public SysCampaignGroupCustomer campaignGroupStatusSetTs(SysCampaign sysCampaign,SysCampaignGroupCustomer sysCampaignGroupCustomer,GridInfoTs gridInfoTs){
        String roleName = userRole();
        if (jg_executer.equals(sysCampaign.getExecuter()) || wd_executer.equals(sysCampaign.getExecuter())) {
            //执行人为机构的情况下,仅将客群分配到机构
            jgStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
        }
        //支行管理员默认只能分配到个人
        if (ROLE_BRANCH.equals(roleName)||gr_executer.equals(sysCampaign.getExecuter())) {
            //需要分配到个人，但归属关系表里无客户经理id，则直接返回，无法分配
            if (gridInfoTs.getUserName()==null){
                return null;
            }
            grStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
        }
        if (hh_executer.equals(sysCampaign.getExecuter())) {
            //执行人为执行人为混合分配的情况下,若客户对应客户经理id存在，则直接分配个人
            if (gridInfoTs.getUserName()!=null){
                grStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
            }
            //执行人为执行人为混合分配的情况下,若无归属用户但有归属机构，则分配到机构
            if (gridInfoTs.getUserName()==null&&gridInfoTs.getRelateDeptId()!=null){
                //执行人为混合分配,强制认领时，设置客户经理认领状态为已认领
                jgStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
            }
        }

        return sysCampaignGroupCustomer;

    }

    public SysCampaignGroupCustomer campaignGroupStatusSetCmpm(SysCampaign sysCampaign,SysCampaignGroupCustomer sysCampaignGroupCustomer,CustDeptUserCmpm custDeptUserCmpm){
        String roleName = userRole();
        if (jg_executer.equals(sysCampaign.getExecuter()) || wd_executer.equals(sysCampaign.getExecuter())) {
            //执行人为机构的情况下,仅将客群分配到机构
            jgStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
        }
        //支行管理员默认只能分配到个人
        if (ROLE_BRANCH.equals(roleName)||gr_executer.equals(sysCampaign.getExecuter())) {
            //需要分配到个人，但归属关系表里无客户经理id，则直接返回，无法分配
            if (custDeptUserCmpm.getUserId()==null){
                return null;
            }
            grStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
        }
        if (hh_executer.equals(sysCampaign.getExecuter())) {
            //执行人为执行人为混合分配的情况下,若客户对应客户经理id存在，则直接分配个人
            if (custDeptUserCmpm.getUserId()!=null){
                grStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
            }
            //执行人为执行人为混合分配的情况下,若无归属用户但有归属机构，则分配到机构
            if (custDeptUserCmpm.getUserId()==null&&custDeptUserCmpm.getDeptId()!=null){
                jgStatusSet(sysCampaignGroupCustomer,sysCampaign.getClaimType());
            }
        }

        return sysCampaignGroupCustomer;

    }
    //分配到机构时状态设置
    public void jgStatusSet(SysCampaignGroupCustomer sysCampaignGroupCustomer,String claimType){
        sysCampaignGroupCustomer.setUserId(null);
        //强制认领
        if (qz_claimType.equals(claimType)){
            sysCampaignGroupCustomer.setOrgClaimStatus("1");
        }else {
            sysCampaignGroupCustomer.setOrgClaimStatus("0");
        }
        sysCampaignGroupCustomer.setOrgDistributeStatus("0");
        sysCampaignGroupCustomer.setCustClaimStatus("0");
    }
    //分配到个人时状态设置
    public void grStatusSet(SysCampaignGroupCustomer sysCampaignGroupCustomer,String claimType){
        sysCampaignGroupCustomer.setOrgClaimStatus("1");
        sysCampaignGroupCustomer.setOrgDistributeStatus("1");
        //执行人为个人,强制认领时，客户经理认领状态为已认领
        if (("0").equals(claimType)) {
            sysCampaignGroupCustomer.setCustClaimStatus("1");
        } else {
            sysCampaignGroupCustomer.setCustClaimStatus("0");
        }
    }

    //筛选出清单中至少包含联系方式和地址其中一项的数据
    public List<SysGroupCustomer> filterAddressAndPhone(List<SysGroupCustomer> sysGroupCustomers,List<SysCampaignGroupCustomer> campaignGroupCustomers,String campaignId) throws ServerException {
        String custType = null;
        if (sysGroupCustomers.size()>0){
            custType  = sysGroupCustomers.get(0).getCustType();
        }
        //筛选出模板中有电话的，可以直接推送
        List<SysGroupCustomer> directDistributeLists = sysGroupCustomers.stream().filter(s->StringUtils.isNotBlank(s.getCustPhone())).
                collect(Collectors.toList());
        sysGroupCustomers.removeAll(directDistributeLists);
        List<String> custIds = sysGroupCustomers.stream().map(s->{return s.getCustId();}).collect(Collectors.toList());
        //根据客户id与客户类型去对应客户表查询是否存在客户地址与客户电话，若都不存在则去除
        if (custIds.size()>0){
            List<AddressAndPhone> addressAndPhones = sysCampaignMapper.selectAddressAndPhoneByCustTypeAndCustIds(custType,custIds);
            List<String> errorCustIds  = addressAndPhones.stream().filter(a->StringUtils.isBlank(a.getCustLocation())&&StringUtils.isBlank(a.getRegisterLocation())&&
                    StringUtils.isBlank(a.getJobLocation())&&StringUtils.isBlank(a.getCustPhone())&&StringUtils.isBlank(a.getTel())
            ).map(s->{return s.getCustId();}).collect(Collectors.toList());
            logger.info("地址与电话都为空的客户id列表"+errorCustIds);
            if(errorCustIds.size() == custIds.size()){
                throw new ServerException("无有地址/电话客户可分配");
            }

            if (errorCustIds.size() > 0) {
                List<SysGroupCustomer> sysGroupCustomersError = sysGroupCustomers.stream().filter(s->errorCustIds.contains(s.getCustId())).collect(Collectors.toList());
                sysGroupCustomersError.forEach(groupCustomer -> {
                            SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                            BeanUtils.copyProperties(groupCustomer, sysCampaignGroupCustomer);
                            initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                            //设置推送状态为无法推送
                            sysCampaignGroupCustomer.setPushStatus("3");
                            campaignGroupCustomers.add(sysCampaignGroupCustomer);
                });
                sysGroupCustomers.removeAll(sysGroupCustomersError);


            }

            logger.info("筛除后的列表为"+sysGroupCustomers);
        }
        sysGroupCustomers.addAll(directDistributeLists);
        return sysGroupCustomers;
    }


    @Override

    public AjaxResult insertSysCampaign(String groupId, String campaignId,String distributeType,Long[] userIds,Long[]  virtualGridIds,Long[]  layerIds,SysCampaignSecondVo sysCampaignSecondVo) throws ServerException {
        SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
        sysCampaignGroupCustomer.setCampaignId(campaignId);
//        sysCampaignGroupCustomer.setGroupId(groupId);
//        sysCampaignGroupCustomer.setCreateRole("0");
        if (userRole().equals("branch")){
            sysCampaignGroupCustomer.setDeptId(getDeptId());
        }else {
            sysCampaignGroupCustomer.setOutletsId(getDeptId());
        }
        SysCampaign campaign = sysCampaignMapper.selectSysCampaignByCampaignId(campaignId);



        Date now = new Date();
        if (campaign!=null){
            if (now.getTime()>campaign.getEndTime().getTime()||now.getTime()<campaign.getStartTime().getTime()){
                return error("当前时间不在活动时间范围内，无法进行二次分配");
            }
        }

        campaign.setCreateTime(DateUtils.getNowDate());
        campaign.setDeptId(getDeptId());
        campaign.setUserId(getUserId());
        campaign.setCreateBy(getUsername());
        if(layerIds !=null  &&  layerIds.length !=0) {
            StringBuilder lys = new StringBuilder();
            for (int i = 0; i < layerIds.length; i++) {
                lys.append(layerIds[i]);
                if (i < layerIds.length - 1) {
                    lys.append(",");
                }
            }
            campaign.setDistributeType2(lys.toString());
        }
        if(virtualGridIds !=null  &&  virtualGridIds.length !=0) {
            StringBuilder lys = new StringBuilder();
            for (int i = 0; i < virtualGridIds.length; i++) {
                lys.append(virtualGridIds[i]);
                if (i < virtualGridIds.length - 1) {
                    lys.append(",");
                }
            }
            campaign.setDistributeType3(lys.toString());
        }
        campaign.setDistributeCont(sysCampaignSecondVo.getDistributeCont());
        campaign.setDistributeCont2(sysCampaignSecondVo.getDistributeCont2());
        campaign.setDistributeCont3(sysCampaignSecondVo.getDistributeCont3());
        sysCampaignMapper.insertSysCampaignSecond(campaign);

        List<SysCampaignGroupCustomer> sysCampaignGroupCustomers = sysCampaignGroupCustomerMapper.selectSysCampaignGroupCustomerList(sysCampaignGroupCustomer);
        List<SysCampaignGroupCustomer> sysCampaignGroupCustomersInsert = new ArrayList<>();
        List<SysCampaignGroupCustomer> sysCampaignGroupCustomersUpdate = new ArrayList<>();

        //只需筛选出该机构下未分配到具体用户的数据去二次分配
        sysCampaignGroupCustomers = sysCampaignGroupCustomers.stream().filter(c->c.getUserId()==null&&!"3".equals(c.getPushStatus())).collect(Collectors.toList());
        if (distributeType != null) {
            //按照管户关系分配或者地址分配
            List<String> distributeRules = Arrays.asList(distributeType.split(","));
            // TODO: 2025/7/31
            distributeSecond(campaign,distributeRules,sysCampaignGroupCustomer,groupId,campaignId,sysCampaignGroupCustomers,sysCampaignGroupCustomersInsert,sysCampaignGroupCustomersUpdate,userIds,virtualGridIds,layerIds);
        }


        sysCampaignGroupCustomersInsert.forEach(e -> e.setSecondPushStatus("1"));
        sysCampaignGroupCustomersUpdate.forEach(e -> e.setSecondPushStatus("1"));

        if (sysCampaignGroupCustomersInsert.size()>0){
            List<SysCampaignGroupCustomer> campaignGroupCustomersRemove = new ArrayList<>();
            sysCampaignGroupCustomersInsert.forEach( e ->{
                SysCampaignGroupCustomer sysCampaignGroupCustomer1 = new SysCampaignGroupCustomer();
                sysCampaignGroupCustomer1.setCampaignId(campaignId);
                sysCampaignGroupCustomer1.setCampaignId(e.getCustId());
                sysCampaignGroupCustomer1.setDeptId(e.getDeptId());
                sysCampaignGroupCustomer1.setUserId(e.getUserId());
                sysCampaignGroupCustomer.setDeptFlag(e.getUserId() == null ? "ture" : null);
                List<SysCampaignGroupCustomer> sysCampaignGroupCustomers2 = sysCampaignGroupCustomerMapper.selectSysCampaignGroupCustomerList(sysCampaignGroupCustomer1);
                if(sysCampaignGroupCustomers2.size() > 0){
                    campaignGroupCustomersRemove.add(e);
                }
            });
            log.info("重复添加的活动客户-》"+ campaignGroupCustomersRemove.stream().map(SysCampaignGroupCustomer:: getCustId).collect(Collectors.toList()));
            sysCampaignGroupCustomersInsert.removeAll(campaignGroupCustomersRemove);
            if(sysCampaignGroupCustomersInsert.size()>0) {
                sysCampaignGroupCustomersInsert.forEach(e->{
                    //支行创建的时候， 无论是否到客户经理，一定要有  PushUserLevel
                    // 二次推送一定是支行
//                    e.setPushUserLevel(ROLE_HEAD.equalsIgnoreCase(userRoleHeadOrBranch()) ? "head" : "branch");
                    e.setPushUserLevel(campaign.getExecuter().equals(jg_executer) ? "branch" : "outlet");
                    //总行创建的时候， 如果推送到客户经理，没有二次推送状态，如果推送失败，也没有二次推送状态
                    e.setSecondPushStatus(ROLE_HEAD.equalsIgnoreCase(userRoleHeadOrBranch())  ? e.getUserId()!=null || e.getDeptId() == null ? null : "0"
                            :  e.getUserId()!=null ?  "1" : Arrays.asList(distributeType.split(",")).contains("0") ? "0" : "2");

                });

            }
        }
        if (sysCampaignGroupCustomersUpdate.size()>0){
            List<SysCampaignGroupCustomer> campaignGroupCustomersRemove = new ArrayList<>();
            sysCampaignGroupCustomersUpdate.forEach(e->{
                //支行创建的时候， 无论是否到客户经理，一定要有  PushUserLevel
//                e.setPushUserLevel(ROLE_HEAD.equalsIgnoreCase(userRoleHeadOrBranch()) ? "head" : "branch");
                e.setPushUserLevel(campaign.getExecuter().equals(jg_executer) ? "branch" : "outlet");
                e.setSecondPushStatus(ROLE_HEAD.equalsIgnoreCase(userRoleHeadOrBranch())  ? e.getUserId()!=null || e.getDeptId() == null ? null : "0"
                        :  e.getUserId()!=null ?  "1" : Arrays.asList(distributeType.split(",")).contains("0") ? "0" : "2");
                e.setOrgDistributeStatus("1");
            });
            sysCampaignGroupCustomersUpdate.forEach( e ->{
                SysCampaignGroupCustomer sysCampaignGroupCustomeree = new SysCampaignGroupCustomer();
                sysCampaignGroupCustomeree.setCampaignId(e.getCampaignId());
                sysCampaignGroupCustomeree.setCustId(e.getCustId());
                sysCampaignGroupCustomeree.setDeptId(e.getDeptId());
                sysCampaignGroupCustomeree.setUserId(e.getUserId());
                sysCampaignGroupCustomeree.setOrgDistributeStatus(e.getOrgDistributeStatus());
                sysCampaignGroupCustomeree.setSecondPushStatus(e.getSecondPushStatus());
                sysCampaignGroupCustomeree.setDeptFlag(e.getUserId() == null ? "ture" : null);
                List<SysCampaignGroupCustomer> sysCampaignGroupCustomersForupdate = sysCampaignGroupCustomerMapper.selectSysCampaignGroupCustomerList(sysCampaignGroupCustomeree);
                if(sysCampaignGroupCustomersForupdate.size() > 0){
                    campaignGroupCustomersRemove.add(e);
                }
            });
            log.info("重复update的活动客户-》"+ campaignGroupCustomersRemove.stream().map(SysCampaignGroupCustomer:: getCustId).collect(Collectors.toList()));
            sysCampaignGroupCustomersUpdate.removeAll(campaignGroupCustomersRemove);





        }
//        if (sysCampaignGroupCustomersInsert.size() == 0 && sysCampaignGroupCustomersUpdate.size() == 0 ){
//            throw  new ServerException("本次分配中，无任何客户可被分配！");
//        }
        if(sysCampaignGroupCustomersInsert.size()>0) {
            sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomerBatch(sysCampaignGroupCustomersInsert);
        }
        if (sysCampaignGroupCustomersUpdate.size()>0) {
            sysCampaignGroupCustomerMapper.updateSysCampaignGroupCustomerBatch(sysCampaignGroupCustomersUpdate);
        }




        SysCampaign sysCampaignForUpdate = new SysCampaign();
        sysCampaignForUpdate.setUpdateBy(getUsername());
        sysCampaignForUpdate.setUpdateTime(new Date());
        sysCampaignForUpdate.setId(campaign.getId());
        sysCampaignMapper.updateSysCampaign(sysCampaignForUpdate);

        return success("二次分配成功");
    }
    //支行二次推送
    public void distributeSecond(SysCampaign sysCampaign,List<String> distributeRules,SysCampaignGroupCustomer sysCampaignGroupCustomer,String groupId,String campaignId,List<SysCampaignGroupCustomer> campaignGroupCustomers
            ,List<SysCampaignGroupCustomer> campaignGroupCustomersInsert,List<SysCampaignGroupCustomer> campaignGroupCustomersUpdate,Long[] userIds,Long[]  virGridIds,Long[]  lIds){
        String roleName = userRole();
        if (distributeRules != null&&distributeRules.size()>0) {
            int k = 0;//虚拟网格分配方式计数
            int l = 0;//特色网格分配方式计数

            for (int j = 0; j <distributeRules.size();j++){
                //按照地址分配
                if (distributeRules.get(j).length()==2&&'2'==distributeRules.get(j).charAt(0)) {
                    String opsDept = distributeRules.get(j).substring(1);
                    distributeDZSecond(sysCampaign,sysCampaignGroupCustomer,groupId,campaignId,campaignGroupCustomers,campaignGroupCustomersInsert,campaignGroupCustomersUpdate,opsDept);
                }
                //按照特色网格
                if (distributeRules.get(j).length()==2&&'4'==distributeRules.get(j).charAt(0)) {
                    //todo 根据部室与特色网格类型查询特色网格列表
                    List<Long> layerIds = Arrays.asList(lIds);
                    String opsDept = String.valueOf(distributeRules.get(j).charAt(1));
                    if (layerIds.size()>l){
                        Long layerId = layerIds.get(l);
                        LayerGridDTO layerGridDTO = new LayerGridDTO();
                        layerGridDTO.setLayerId(layerId);
                        layerGridDTO.setOpsDept(opsDept);
                        List<DrawGrid> drawGrids = drawLayerService.getDrawGridList(layerGridDTO);
                        List<Long> gridIds = drawGrids.stream().map(DrawGrid::getGridId).collect(Collectors.toList());
                        if (gridIds.size()>0){
                            distributeTsSecond(sysCampaign,sysCampaignGroupCustomer,groupId,campaignId,campaignGroupCustomers,campaignGroupCustomersInsert,campaignGroupCustomersUpdate,gridIds);
                        }
                        ++l;
                    }

                }
                //按照虚拟网格
                if (distributeRules.get(j).length()==2&&'5'==distributeRules.get(j).charAt(0)) {
                    //todo 根据部室与虚拟网格名称查询虚拟网格列表
                    List<Long> virtualGridIds = Arrays.asList(virGridIds);
                    if (virtualGridIds.size()>k){
                        Long gridId = virtualGridIds.get(k);
                        distributeXNSecond(sysCampaign,sysCampaignGroupCustomer,groupId,campaignId,campaignGroupCustomers,campaignGroupCustomersInsert,campaignGroupCustomersUpdate,gridId);
                        ++k;
                    }

                }
                //按照管户关系分配
                if (distributeRules.get(j).length()>3){
                    distributeGHSecond(sysCampaign,sysCampaignGroupCustomer,groupId,campaignId,campaignGroupCustomers,campaignGroupCustomersInsert,campaignGroupCustomersUpdate,distributeRules.get(j));
                }
                //随机平均分配
                if (sj_campaignDistributeType.equals(distributeRules.get(j))){
                    distributeSJSecond(sysCampaign,groupId,campaignId,campaignGroupCustomers,campaignGroupCustomersInsert,campaignGroupCustomersUpdate,Arrays.asList(userIds));
                }
            }
            //表里无详细归属关系，但是仍要置为已分配
            if (campaignGroupCustomers.size()>0){
                for (SysCampaignGroupCustomer campaignGroupCustomer : campaignGroupCustomers){
                    campaignGroupCustomer.setOrgDistributeStatus("1");
                    campaignGroupCustomer.setSecondPushStatus("1");
                    campaignGroupCustomersUpdate.add(campaignGroupCustomer);
                }

            }


        }

    }

    public void distributeDZSecond(SysCampaign campaign,SysCampaignGroupCustomer sysCampaignGroupCustomer ,String groupId,String campaignId,List<SysCampaignGroupCustomer> campaignGroupCustomers
            ,List<SysCampaignGroupCustomer> campaignGroupCustomersInsert,List<SysCampaignGroupCustomer> campaignGroupCustomersUpdate,String opsDept){
        List<SysCampaignGroupCustomer> campaignGroupCustomersRemove = new ArrayList<>();
        campaignGroupCustomers.forEach(campaignGroupCustomer -> {
            SysCampaignGroupCustomer newSysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            BeanUtils.copyProperties(campaignGroupCustomer, sysCampaignGroupCustomer);
            CustDeptUserGrid custDeptUserGrid = new CustDeptUserGrid();
            custDeptUserGrid.setCustId(campaignGroupCustomer.getCustId());
            custDeptUserGrid.setDeptId(getDeptId());
            custDeptUserGrid.setOpsDept(opsDept);
            List<CustDeptUserGrid> custDeptUserGrids = custDeptUserGridMapper.selectCustDeptUserGridList(custDeptUserGrid);
            custDeptUserGrids = custDeptUserGrids.stream().filter(c->c.getUserId()!=null).collect(Collectors.toList());
            if (custDeptUserGrids != null&&custDeptUserGrids.size()>0) {
                for (int i = 0; i < custDeptUserGrids.size(); i++) {
                    //归属用户不为空，则分配成功
                    if (custDeptUserGrids.get(i).getUserId()!=null){
                        BeanUtils.copyProperties(custDeptUserGrids.get(i), newSysCampaignGroupCustomer);
                        newSysCampaignGroupCustomer.setPushStatus("1");
                        //活动为强制认领则客户经理认领状态为已认领
                        grStatusSetSecond(newSysCampaignGroupCustomer,campaign.getClaimType());
                        SecondCampaignGroupCustomerInit(newSysCampaignGroupCustomer,groupId,campaignId);
                        if (i==0){
                            newSysCampaignGroupCustomer.setId(campaignGroupCustomer.getId());
                            campaignGroupCustomersUpdate.add(newSysCampaignGroupCustomer);
                            //sysCampaignGroupCustomerMapper.updateSysCampaignGroupCustomer(newSysCampaignGroupCustomer);
                        }else {
                            campaignGroupCustomersInsert.add(newSysCampaignGroupCustomer);
                            //sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomer(newSysCampaignGroupCustomer);
                        }
                        if(  jg_executer.equals(campaign.getExecuter())){
                            newSysCampaignGroupCustomer.setOutletsId(null);
                            newSysCampaignGroupCustomer.setOutlets(null);
                        }
                        campaignGroupCustomersRemove.add(campaignGroupCustomer);

                    }

                }
            }


        });
        campaignGroupCustomers.removeAll(campaignGroupCustomersRemove);

    }

    //虚拟网格分配方式
    public void distributeXNSecond(SysCampaign campaign,SysCampaignGroupCustomer sysCampaignGroupCustomer ,String groupId,String campaignId,List<SysCampaignGroupCustomer> campaignGroupCustomers
            ,List<SysCampaignGroupCustomer> campaignGroupCustomersInsert,List<SysCampaignGroupCustomer> campaignGroupCustomersUpdate,Long gridId){
        List<SysCampaignGroupCustomer> campaignGroupCustomersRemove = new ArrayList<>();
        campaignGroupCustomers.forEach(campaignGroupCustomer -> {
            SysCampaignGroupCustomer newSysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            BeanUtils.copyProperties(campaignGroupCustomer, sysCampaignGroupCustomer);
            VirtualCustUser virtualCustUser  = new VirtualCustUser();
            String custId = campaignGroupCustomer.getCustId();
            virtualCustUser.setCustId(custId);
            virtualCustUser.setRelateDeptId(getDeptId());
            virtualCustUser.setGridId(gridId);
            List<VirtualCustUser> virtualCustUsers = virtualCustUserMapper.selectVirtualCustUserList(virtualCustUser);
            virtualCustUsers = virtualCustUsers.stream().filter(c->c.getUserName()!=null).collect(Collectors.toList());
            if (virtualCustUsers != null&&virtualCustUsers.size()>0) {
                for (int i = 0; i < virtualCustUsers.size(); i++) {
                    //归属用户不为空，则分配成功
                    if (virtualCustUsers.get(i).getUserName()!=null){
                        DeptAndOutlets deptAndOutlet = sysCampaignMapper.selectDeptAndOutletsByUserName(virtualCustUsers.get(i).getUserName());
                        BeanUtils.copyProperties(deptAndOutlet,newSysCampaignGroupCustomer);
                        newSysCampaignGroupCustomer.setPushStatus("1");
                        //活动为强制认领则客户经理认领状态为已认领
                        grStatusSetSecond(newSysCampaignGroupCustomer,campaign.getClaimType());
                        SecondCampaignGroupCustomerInit(newSysCampaignGroupCustomer,groupId,campaignId);
                        if (i==0){
                            newSysCampaignGroupCustomer.setId(campaignGroupCustomer.getId());
                            campaignGroupCustomersUpdate.add(newSysCampaignGroupCustomer);
                            //sysCampaignGroupCustomerMapper.updateSysCampaignGroupCustomer(newSysCampaignGroupCustomer);
                        }else {
                            campaignGroupCustomersInsert.add(newSysCampaignGroupCustomer);
                            //sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomer(newSysCampaignGroupCustomer);
                        }
                        if(  jg_executer.equals(campaign.getExecuter())){
                            newSysCampaignGroupCustomer.setOutletsId(null);
                            newSysCampaignGroupCustomer.setOutlets(null);
                        }
                        campaignGroupCustomersRemove.add(campaignGroupCustomer);

                    }

                }
            }


        });
        campaignGroupCustomers.removeAll(campaignGroupCustomersRemove);

    }

    //特色分配方式
    public void distributeTsSecond(SysCampaign campaign,SysCampaignGroupCustomer sysCampaignGroupCustomer ,String groupId,String campaignId,List<SysCampaignGroupCustomer> campaignGroupCustomers
            ,List<SysCampaignGroupCustomer> campaignGroupCustomersInsert,List<SysCampaignGroupCustomer> campaignGroupCustomersUpdate,List<Long> gridIds){
        List<SysCampaignGroupCustomer> campaignGroupCustomersRemove = new ArrayList<>();
        campaignGroupCustomers.forEach(campaignGroupCustomer -> {
            SysCampaignGroupCustomer newSysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            BeanUtils.copyProperties(campaignGroupCustomer, sysCampaignGroupCustomer);
            List<GridInfoTs> gridInfos = sysCampaignMapper.selectGridInfoTsByGridIds(gridIds);
            List<GridInfoTs> gridInfoTsList = gridInfos.stream().filter(c->c.getCustId().equals(campaignGroupCustomer.getCustId())).collect(Collectors.toList());
            if (gridInfoTsList != null&&gridInfoTsList.size()>0) {
                for (int i = 0; i < gridInfoTsList.size(); i++) {
                    //归属用户不为空，则分配成功
                    if (gridInfoTsList.get(i).getUserName()!=null){
                        DeptAndOutlets deptAndOutlet = sysCampaignMapper.selectDeptAndOutletsByUserName(gridInfoTsList.get(i).getUserName());
                        BeanUtils.copyProperties(deptAndOutlet,newSysCampaignGroupCustomer);
                        newSysCampaignGroupCustomer.setPushStatus("1");
                        //活动为强制认领则客户经理认领状态为已认领
                        grStatusSetSecond(newSysCampaignGroupCustomer,campaign.getClaimType());
                        SecondCampaignGroupCustomerInit(newSysCampaignGroupCustomer,groupId,campaignId);
                        if (i==0){
                            newSysCampaignGroupCustomer.setId(campaignGroupCustomer.getId());
                            campaignGroupCustomersUpdate.add(newSysCampaignGroupCustomer);
                            //sysCampaignGroupCustomerMapper.updateSysCampaignGroupCustomer(newSysCampaignGroupCustomer);
                        }else {
                            campaignGroupCustomersInsert.add(newSysCampaignGroupCustomer);
                            //sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomer(newSysCampaignGroupCustomer);
                        }
                        if(  jg_executer.equals(campaign.getExecuter())){
                            newSysCampaignGroupCustomer.setOutletsId(null);
                            newSysCampaignGroupCustomer.setOutlets(null);
                        }
                        campaignGroupCustomersRemove.add(campaignGroupCustomer);

                    }

                }
            }


        });
        campaignGroupCustomers.removeAll(campaignGroupCustomersRemove);

    }

    public void distributeGHSecond(SysCampaign campaign,SysCampaignGroupCustomer sysCampaignGroupCustomer ,String groupId,String campaignId,List<SysCampaignGroupCustomer> campaignGroupCustomers
            ,List<SysCampaignGroupCustomer> campaignGroupCustomersInsert,List<SysCampaignGroupCustomer> campaignGroupCustomersUpdate,String distributeRule){
        String roleName = userRole();
        String codeLevel1 = distributeRule.substring(0, 3);
        String codeLevel2 = distributeRule.substring(3,6);
        List<SysCampaignGroupCustomer> campaignGroupCustomersRemove = new ArrayList<>();
        campaignGroupCustomers.forEach(campaignGroupCustomer -> {
            SysCampaignGroupCustomer newSysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            BeanUtils.copyProperties(campaignGroupCustomer, sysCampaignGroupCustomer);
            CustDeptUserCmpm custDeptUserCmpm= new CustDeptUserCmpm();
            String custId = campaignGroupCustomer.getCustId();
            custDeptUserCmpm.setCodeNoLevel1(codeLevel1);
            custDeptUserCmpm.setCodeNoLevel2(codeLevel2);
            //根据匹配表中关联关系查询到对应的客户归属
            custDeptUserCmpm.setCustId(custId);
            custDeptUserCmpm.setDeptId(getDeptId());

            List<CustDeptUserCmpm> custDeptUserCmpms = custDeptUserCmpmMapper.selectCustDeptUserCmpmList(custDeptUserCmpm);
            if (custDeptUserCmpms != null&&custDeptUserCmpms.size()>0) {
                for (int i = 0; i < custDeptUserCmpms.size(); i++) {
                    //归属用户不为空，则分配成功
                    if (custDeptUserCmpms.get(i).getUserId()!=null){
                        BeanUtils.copyProperties(custDeptUserCmpms.get(i), newSysCampaignGroupCustomer);
                        newSysCampaignGroupCustomer.setPushStatus("1");
                        //活动为强制认领则客户经理认领状态为已认领
                        grStatusSetSecond(newSysCampaignGroupCustomer,campaign.getClaimType());
                        SecondCampaignGroupCustomerInit(newSysCampaignGroupCustomer,groupId,campaignId);
                        if (i==0){
                            newSysCampaignGroupCustomer.setId(campaignGroupCustomer.getId());
                            campaignGroupCustomersUpdate.add(newSysCampaignGroupCustomer);
                            //sysCampaignGroupCustomerMapper.updateSysCampaignGroupCustomer(newSysCampaignGroupCustomer);
                        }else {
                            campaignGroupCustomersInsert.add(newSysCampaignGroupCustomer);
                            //sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomer(newSysCampaignGroupCustomer);
                        }
                        if(  jg_executer.equals(campaign.getExecuter())){
                            newSysCampaignGroupCustomer.setOutletsId(null);
                            newSysCampaignGroupCustomer.setOutlets(null);
                        }
                        campaignGroupCustomersRemove.add(campaignGroupCustomer);

                    }

                }
            }

        });
        campaignGroupCustomers.removeAll(campaignGroupCustomersRemove);

    }

    public void grStatusSetSecond(SysCampaignGroupCustomer sysCampaignGroupCustomer,String claimType){
        sysCampaignGroupCustomer.setOrgClaimStatus("1");
        sysCampaignGroupCustomer.setOrgDistributeStatus("1");
        //执行人为个人,强制认领时，客户经理认领状态为已认领
        if (("0").equals(claimType)) {
            sysCampaignGroupCustomer.setCustClaimStatus("1");
        } else {
            sysCampaignGroupCustomer.setCustClaimStatus("0");
        }
    }

    public void distributeSJSecond(SysCampaign sysCampaign,String groupId,String campaignId,List<SysCampaignGroupCustomer> campaignGroupCustomers,
                                   List<SysCampaignGroupCustomer> campaignGroupCustomersInsert,List<SysCampaignGroupCustomer> campaignGroupCustomersUpdate,List<Long> userIds){
        if (userIds==null||userIds.size()==0){
            throw new RuntimeException("请选择客户经理");
        }
        List<DeptAndOutlets> deptAndOutlets = selectDeptAndOutletsByUserIds(userIds);
        //客户数小于用户数，直接分配给第一个用户
        if (campaignGroupCustomers.size()<userIds.size()){
            SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            for (int i = 0; i < campaignGroupCustomers.size(); i++) {
                SysCampaignGroupCustomer groupCustomer = campaignGroupCustomers.get(i);
                BeanUtils.copyProperties(groupCustomer, sysCampaignGroupCustomer);
                initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                grStatusSetSecond(sysCampaignGroupCustomer,sysCampaign.getClaimType());
                DeptAndOutlets deptAndOutlet = selectDeptAndOutletsByUserId(deptAndOutlets,userIds.get(0));
                BeanUtils.copyProperties(deptAndOutlet,sysCampaignGroupCustomer);
                //sysCampaignGroupCustomer.setUserId(userIds.get(0));
                campaignGroupCustomersUpdate.add(sysCampaignGroupCustomer);
                campaignGroupCustomers.remove(sysCampaignGroupCustomer);
                sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
            }

        }else{
            int length = campaignGroupCustomers.size()/userIds.size();
            int remainder = campaignGroupCustomers.size()%userIds.size();
            List<List<SysCampaignGroupCustomer>> splitLists = splitList(campaignGroupCustomers,length);
            for (int i = 0; i < userIds.size(); i++) {
                List<SysCampaignGroupCustomer> splitGroupCustomerList = splitLists.get(i);
                for (int j = 0; j < splitGroupCustomerList.size(); j++) {
                    SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                    SysCampaignGroupCustomer groupCustomer = splitGroupCustomerList.get(j);
                    BeanUtils.copyProperties(groupCustomer, sysCampaignGroupCustomer);
                    initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                    grStatusSetSecond(sysCampaignGroupCustomer,sysCampaign.getClaimType());
                    DeptAndOutlets deptAndOutlet = selectDeptAndOutletsByUserId(deptAndOutlets,userIds.get(i));
                    BeanUtils.copyProperties(deptAndOutlet,sysCampaignGroupCustomer);
                    //sysCampaignGroupCustomer.setUserId(userIds.get(i));
                    campaignGroupCustomersUpdate.add(sysCampaignGroupCustomer);
                    campaignGroupCustomers.remove(sysCampaignGroupCustomer);
                    sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                }

            }
            for (int i = campaignGroupCustomers.size()-1 ; i >= campaignGroupCustomers.size()-remainder;  i--) {
                SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                SysCampaignGroupCustomer groupCustomer = campaignGroupCustomers.get(i);
                BeanUtils.copyProperties(groupCustomer, sysCampaignGroupCustomer);
                initSysCampaignGroupCustomer(sysCampaignGroupCustomer,campaignId);
                grStatusSetSecond(sysCampaignGroupCustomer,sysCampaign.getClaimType());
                DeptAndOutlets deptAndOutlet = selectDeptAndOutletsByUserId(deptAndOutlets,userIds.get(0));
                BeanUtils.copyProperties(deptAndOutlet,sysCampaignGroupCustomer);
                //sysCampaignGroupCustomer.setUserId(userIds.get(0));
                campaignGroupCustomersUpdate.add(sysCampaignGroupCustomer);
                campaignGroupCustomers.remove(sysCampaignGroupCustomer);
                sysCampaignGroupCustomer = new SysCampaignGroupCustomer();

            }


        }
        //随机分配后，待推送客群置空
        campaignGroupCustomers.clear();
        //todo随机分配时分配客户经理的机构号和网点号
    }
    public void SecondCampaignGroupCustomerInit(SysCampaignGroupCustomer sysCampaignGroupCustomer,String groupId,String campaignId){
        sysCampaignGroupCustomer.setListType("0");
        sysCampaignGroupCustomer.setId(null);
        sysCampaignGroupCustomer.setCampaignId(campaignId);
        sysCampaignGroupCustomer.setGroupId(groupId);
        sysCampaignGroupCustomer.setCreateTime(new Date());
        sysCampaignGroupCustomer.setCreateBy(getUsername());
        sysCampaignGroupCustomer.setCreateRole("1");
        sysCampaignGroupCustomer.setSecondPushStatus("1");
        sysCampaignGroupCustomer.setDelFlag("0");
    }

    /**
     * 修改活动
     * 
     * @param sysCampaign 活动
     * @return 结果
     */
    @Override
    public int updateSysCampaign(SysCampaign sysCampaign)
    {
        sysCampaign.setUpdateTime(DateUtils.getNowDate());
        return sysCampaignMapper.updateSysCampaign(sysCampaign);
    }

    /**
     * 批量删除活动
     * 
     * @param ids 需要删除的活动主键
     * @return 结果
     */
    @Override
    public int deleteSysCampaignByIds(Long[] ids)
    {
        return sysCampaignMapper.deleteSysCampaignByIds(ids);
    }

    /**
     * 删除活动信息
     * 
     * @param id 活动主键
     * @return 结果
     */
    @Override
    public int deleteSysCampaignById(Long id)
    {
        return sysCampaignMapper.deleteSysCampaignById(id);
    }

    @Override
    public SysCampaign selectSysCampaignByCampaignId(String campaignId) {
       return  sysCampaignMapper.selectSysCampaignByCampaignId(campaignId);
    }

    @Override
    public int selectByCampaignName(String campaignName) {
        return sysCampaignMapper.selectCountByCampaignName(campaignName);
    }

    @Override
    public List<DeptAndOutlets> selectDeptAndOutletsByUserIds(List<Long> userIds) {
        List<DeptAndOutlets> deptAndOutlets = sysCampaignMapper.selectDeptAndOutletsByUserId(userIds);
        deptAndOutlets =  deptAndOutlets.stream().map(d->{
            if (d.getDeptType().equals("branch") || d.getDeptType().equals("head")){
//                d.setOutletsId(null);
//                d.setOutlets(null);
            }
            return d;
        }).collect(Collectors.toList());
        return deptAndOutlets;
    }

    @Override
    public List<DeptAndOutlets> selectDeptAndOutletsByDeptIds(List<Long> deptIds) {
        List<DeptAndOutlets> deptAndOutlets = sysCampaignMapper.selectDeptAndOutletsBydeptIds(deptIds);
        deptAndOutlets =  deptAndOutlets.stream().map(d->{
            if (d.getDeptType().equals("branch") || d.getDeptType().equals("head")){
                d.setOutletsId(null);
                d.setOutlets(null);
            }
            return d;
        }).collect(Collectors.toList());
        return deptAndOutlets;
    }

    public DeptAndOutlets selectDeptAndOutletsByUserId(List<DeptAndOutlets> deptAndOutlets,Long userId) {
        for (int i = 0; i <deptAndOutlets.size(); i++) {
            if (deptAndOutlets.get(i).getUserId().equals(userId)){
                return deptAndOutlets.get(i);
            }
        }
        DeptAndOutlets deptAndOutlets1 = new DeptAndOutlets();
        return deptAndOutlets1;
    }

    public DeptAndOutlets selectDeptAndOutletsByDeptId(List<DeptAndOutlets> deptAndOutlets,Long deptId) {
        for (int i = 0; i <deptAndOutlets.size(); i++) {
            if (deptAndOutlets.get(i).getDeptId().equals(deptId)){
                return deptAndOutlets.get(i);
            }
        }
        DeptAndOutlets deptAndOutlets1 = new DeptAndOutlets();
        return deptAndOutlets1;
    }
    @Override
    public List<VisitInfoVO> selectVisitInfoVoList(VisitInfoDTO visitInfoDTO){
        visitInfoDTO.setUserName(SecurityUtils.getUsername());
        visitInfoDTO.setUserRole(SecurityUtils.userRole());
        visitInfoDTO.setDeptId(String.valueOf(SecurityUtils.getDeptId()));
        if ("875".equals(SecurityUtils.getHeadId())) {
            return sysCampaignMapper.selectVisitInfoList875(visitInfoDTO);
        }
        return sysCampaignMapper.selectVisitInfoList(visitInfoDTO);
    }

    @Override
    public int updateVisitInfoFeedback(VisitInfoFeedbackUpdateDTO updateDTO) {
        if (updateDTO == null || updateDTO.getId() == null) {
            throw new ServiceException("走访记录ID不能为空");
        }
        String deptId = String.valueOf(SecurityUtils.getDeptId());
        if (!deptId.startsWith("875")) {
            throw new ServiceException("当前机构无权维护PAD走访反馈");
        }
        updateDTO.setUserName(SecurityUtils.getUsername());
        updateDTO.setUserRole(SecurityUtils.userRole());
        updateDTO.setDeptId(deptId);
        updateDTO.setSource(StringUtils.trimToNull(updateDTO.getSource()));
        updateDTO.setRemark(StringUtils.trimToNull(updateDTO.getRemark()));
        updateDTO.setIntentionProductValue(buildIntentionProductValue(updateDTO.getFeedbackItems()));
        int rows = sysCampaignMapper.updateVisitInfoFeedback(updateDTO);
        return rows;
    }

    @Override
    public int deleteSysCampaign(String campaignId) {
        SysCampaign sysCampaign = sysCampaignMapper.selectSysCampaignByCampaignId(campaignId);
        if (Objects.isNull(sysCampaign)){
            throw new ServiceException("活动不存在");
        }
        return sysCampaignMapper.deleteSysCampaignByCampaignId(campaignId);
    }
    private String buildIntentionProductValue(List<VisitFeedbackItemDTO> feedbackItems) {
        if (feedbackItems == null || feedbackItems.isEmpty()) {
            return null;
        }
        String joinedValue = feedbackItems.stream()
                .filter(Objects::nonNull)
                .map(item -> {
                    String feedbackType = StringUtils.trimToNull(item.getFeedbackType());
                    List<String> products = Optional.ofNullable(item.getProducts())
                            .orElse(Collections.emptyList())
                            .stream()
                            .map(StringUtils::trimToNull)
                            .filter(Objects::nonNull)
                            .distinct()
                            .collect(Collectors.toList());
                    if (feedbackType == null || products.isEmpty()) {
                        return null;
                    }
                    return feedbackType + ":" + String.join(",", products);
                })
                .filter(Objects::nonNull)
                .collect(Collectors.joining(";"));
        return StringUtils.trimToNull(joinedValue);
    }
}
