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

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.ibs.list.domain.DeptAndOutlets;
import com.ruoyi.ibs.list.domain.SysCampaign;
import com.ruoyi.ibs.list.domain.SysCampaignGroupCustomer;
import com.ruoyi.ibs.list.domain.SysGroupCustomer;
import com.ruoyi.ibs.list.mapper.SysCampaignGroupCustomerMapper;
import com.ruoyi.ibs.list.mapper.SysCampaignMapper;
import com.ruoyi.ibs.list.mapper.SysCustAppointSupplementMapper;
import com.ruoyi.ibs.list.mapper.SysGroupCustomerMapper;
import com.ruoyi.ibs.list.service.ISysCampaignGroupCustomerService;
import com.ruoyi.ibs.list.service.ISysCampaignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.ServerException;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.SecurityUtils.*;
import static com.ruoyi.ibs.list.domain.Constans.*;

/**
 * 活动分群客户关联关系，推送成功后，插入一条记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-14
 */
@Service
@Slf4j
public class SysCampaignGroupCustomerServiceImpl implements ISysCampaignGroupCustomerService
{
    @Autowired
    private SysCampaignGroupCustomerMapper sysCampaignGroupCustomerMapper;
    @Autowired
    private SysGroupCustomerMapper sysGroupCustomerMapper;
    @Autowired
    private SysCampaignMapper sysCampaignMapper;
    @Autowired
    private ISysCampaignService sysCampaignService;

    @Autowired
    private SysCustAppointSupplementMapper sysCampaignGroupCustomerSupplementMapper;

    /**
     * 查询活动分群客户关联关系，推送成功后，插入一条记录
     * 
     * @param id 活动分群客户关联关系，推送成功后，插入一条记录主键
     * @return 活动分群客户关联关系，推送成功后，插入一条记录
     */
    @Override
    public SysCampaignGroupCustomer selectSysCampaignGroupCustomerById(Long id)
    {
        return sysCampaignGroupCustomerMapper.selectSysCampaignGroupCustomerById(id);
    }

    /**
     * 查询活动分群客户关联关系，推送成功后，插入一条记录列表
     * 
     * @param sysCampaignGroupCustomer 活动分群客户关联关系，推送成功后，插入一条记录
     * @return 活动分群客户关联关系，推送成功后，插入一条记录
     */
    @Override
    public List<SysCampaignGroupCustomer> selectSysCampaignGroupCustomerList(SysCampaignGroupCustomer sysCampaignGroupCustomer)
    {
        return sysCampaignGroupCustomerMapper.selectSysCampaignGroupCustomerList(sysCampaignGroupCustomer);
    }

    /**
     * 新增活动分群客户关联关系，推送成功后，插入一条记录
     * 
     * @param sysCampaignGroupCustomer 活动分群客户关联关系，推送成功后，插入一条记录
     * @return 结果
     */
    @Override
    public int insertSysCampaignGroupCustomer(SysCampaignGroupCustomer sysCampaignGroupCustomer)
    {
        sysCampaignGroupCustomer.setCreateTime(DateUtils.getNowDate());
        return sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomer(sysCampaignGroupCustomer);
    }

    /**
     * 修改活动分群客户关联关系，推送成功后，插入一条记录
     * 
     * @param sysCampaignGroupCustomer 活动分群客户关联关系，推送成功后，插入一条记录
     * @return 结果
     */
    @Override
    public int updateSysCampaignGroupCustomer(SysCampaignGroupCustomer sysCampaignGroupCustomer)
    {
        sysCampaignGroupCustomer.setUpdateTime(DateUtils.getNowDate());
        return sysCampaignGroupCustomerMapper.updateSysCampaignGroupCustomer(sysCampaignGroupCustomer);
    }

    /**
     * 批量删除活动分群客户关联关系，推送成功后，插入一条记录
     * 
     * @param ids 需要删除的活动分群客户关联关系，推送成功后，插入一条记录主键
     * @return 结果
     */
    @Override
    public int deleteSysCampaignGroupCustomerByIds(Long[] ids)
    {
        return sysCampaignGroupCustomerMapper.deleteSysCampaignGroupCustomerByIds(ids);
    }

    /**
     * 删除活动分群客户关联关系，推送成功后，插入一条记录信息
     * 
     * @param id 活动分群客户关联关系，推送成功后，插入一条记录主键
     * @return 结果
     */
    @Override
    public int deleteSysCampaignGroupCustomerById(Long id)
    {
        return sysCampaignGroupCustomerMapper.deleteSysCampaignGroupCustomerById(id);
    }

    @Override
    public int appointCustCamp(String custId,String custName,String custIdc,String custPhone,String custIsn,String socialCreditCode,String lpName,String campaignId,String custType) throws ServerException {
        // 1 . 根据 客群 确认 客户列表
        //  2.  确认 推送乎哟东列表
        //   3. 确认 推送参数
        //    4. 进行推送

        ArrayList<String> custIds = new ArrayList<>();
        custIds.add(custId);
        SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
        sysCampaignGroupCustomer.setCampaignId(campaignId);
        sysCampaignGroupCustomer.setCustId(custId);
        List<SysCampaignGroupCustomer> sysCampaignGroupCustomers = sysCampaignGroupCustomerMapper.selectSysCampaignGroupCustomerList(sysCampaignGroupCustomer);
        if(sysCampaignGroupCustomers.size()>0){
            throw new ServerException("客户已存在于活动中！");
        }
        ArrayList<String> groupIds = new ArrayList<>();
        groupIds.add("-1");
        Map<String ,SysCampaignGroupCustomer> sysCampaignGroupCustomerVos = new HashMap<>();
        SysCampaignGroupCustomer sysCampaignGroupCustomerVo = new SysCampaignGroupCustomer();
        sysCampaignGroupCustomerVo.setCustId(custId);
        sysCampaignGroupCustomerVo.setCustName(custName);
        sysCampaignGroupCustomerVo.setCustIdc(custIdc);
        sysCampaignGroupCustomerVo.setCustPhone(custPhone);
        sysCampaignGroupCustomerVo.setCustIsn(custIsn);
        sysCampaignGroupCustomerVo.setSocialCreditCode(socialCreditCode);
        sysCampaignGroupCustomerVo.setLpName(lpName);
        sysCampaignGroupCustomerVos.put(custId,sysCampaignGroupCustomerVo);
        sysCampaignService.addSysCampaignHis(campaignId,custIds,sysCampaignGroupCustomerVos,groupIds,custType);

        return 0;
    }
    @Override
    public int appointHisCamp(String groupId, List<String> custIds, List<String> campaignIds) throws ServerException {
        // 1 . 根据 客群 确认 客户列表
        //  2.  确认 推送乎哟东列表
        //   3. 确认 推送参数
        //    4. 进行推送
        List <String>groupIds = new ArrayList<>();
        groupIds.add(groupId);
        Map<String,SysCampaignGroupCustomer> sysCampaignGroupCustomerVos = new HashMap<>();
        List<SysGroupCustomer> sysGroupCustomers = sysGroupCustomerMapper.selectSysGroupCustomerListIds(groupIds,null,custIds==null || custIds.size()==0? null:custIds,"true");

        if(sysGroupCustomers.size()==0){
                throw new ServerException("无未分配客户可共分配！");
            }
            custIds = sysGroupCustomers.stream().map(SysGroupCustomer::getCustId).collect(Collectors.toList());
        if(custIds.size()==0){
                throw new ServerException("无未分配客户可共分配！");
            }sysCampaignGroupCustomerVos = sysGroupCustomers.stream().map(e-> {
                SysCampaignGroupCustomer sysCampaignGroupCustomerVo = new SysCampaignGroupCustomer();
                sysCampaignGroupCustomerVo.setCustId(e.getCustId());
                sysCampaignGroupCustomerVo.setCustName(e.getCustName());
                sysCampaignGroupCustomerVo.setCustIdc(e.getCustIdc());
                sysCampaignGroupCustomerVo.setCustPhone(e.getCustPhone());
                sysCampaignGroupCustomerVo.setLpName(e.getLpName());
                sysCampaignGroupCustomerVo.setSocialCreditCode(e.getSocialCreditCode());
                return sysCampaignGroupCustomerVo;
            }).collect(Collectors.toMap(sysCampaignGroupCustomer -> sysCampaignGroupCustomer.getCustId(), sysCampaignGroupCustomer -> sysCampaignGroupCustomer));


        if(campaignIds==null || campaignIds.size()==0){
            campaignIds = sysCampaignMapper.selectSysCampaignGroupList(groupId);
        }
        for(String campaignId:campaignIds){

            sysCampaignService.addSysCampaignHis(campaignId,custIds,sysCampaignGroupCustomerVos,groupIds,null);
        }

        return 0;
    }


    @Override
    public int appoint(String groupId,String campaignId,List<String> custIds,  List<Long> userIds, List<Long> deptIds,String createRole) {
        SysCampaign sysCampaign = sysCampaignMapper.selectSysCampaignByCampaignId(campaignId);
        List<SysCampaignGroupCustomer> campaignGroupCustomerList    = new ArrayList<>();
        List<SysCampaignGroupCustomer> campaignGroupCustomersInsert = new ArrayList<>();
        List<SysCampaignGroupCustomer> campaignGroupCustomersUpdate = new ArrayList<>();
        //存放某个客户号未推送成功的记录，推送时直接覆盖掉，无需新增
        Map<String,List<SysCampaignGroupCustomer>> custIdsMap = new HashMap<>();
        if (custIds!=null){
             for (int i = 0; i < custIds.size(); i++) {
                 SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                 SysGroupCustomer groupCustomer = new SysGroupCustomer();
                 sysCampaignGroupCustomer.setCampaignId(campaignId);
                 sysCampaignGroupCustomer.setCreateRole(createRole);
                 sysCampaignGroupCustomer.setCreateBy(getUsername());
                 groupCustomer.setGroupId(groupId);
                 groupCustomer.setCustId(custIds.get(i));

                 if(! "-1".equalsIgnoreCase(groupId)) {
                     List<SysGroupCustomer> groupCustomers = sysGroupCustomerMapper.selectSysGroupCustomerList(groupCustomer);
                     if (groupCustomers != null && groupCustomers.size() > 0) {
                         BeanUtils.copyProperties(groupCustomers.get(0), sysCampaignGroupCustomer);
                     }
                 }else{
                     // groupId == -1 表示该客户直接从我的客户中添加到活动，没有归属客群
                     sysCampaignGroupCustomer.setCustId(custIds.get(i));
                 }
                 campaignGroupCustomerList.add(sysCampaignGroupCustomer);
                 SysCampaignGroupCustomer campaignGroupCustomer = new SysCampaignGroupCustomer();
                 campaignGroupCustomer.setCustId(custIds.get(i));
                 campaignGroupCustomer.setCampaignId(campaignId);
//                 campaignGroupCustomer.setGroupId(groupId);
                 List<SysCampaignGroupCustomer> list =  sysCampaignGroupCustomerMapper.selectSysCampaignGroupCustomerListUnsuccess(campaignGroupCustomer);
                 if (list!=null&&list.size()>0){
                     custIdsMap.put(custIds.get(i),list);
                 }
             }
         }

        if (deptIds!=null&&deptIds.size()>0){
            List<DeptAndOutlets> deptAndOutlets = sysCampaignService.selectDeptAndOutletsByDeptIds(deptIds);
            for (int i = 0; i < campaignGroupCustomerList.size(); i++) {
                SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                sysCampaignGroupCustomer = campaignGroupCustomerList.get(i);
                for (int j = 0; j < deptIds.size(); j++) {
                    DeptAndOutlets deptAndOutlet = deptAndOutlets.get(j);
                    BeanUtils.copyProperties(deptAndOutlet,sysCampaignGroupCustomer);
                    sysCampaignGroupCustomer.setPushStatus("1");
                    sysCampaignGroupCustomer.setSecondPushStatus("0");
                    //总行管理员指定推送给机构
                    if ("0".equals(createRole) || "1".equals(createRole) || "2".equals(createRole) || "3".equals(createRole)){
                        //强制认领
                        if (qz_claimType.equals(sysCampaign.getClaimType())){
                            sysCampaignGroupCustomer.setOrgClaimStatus("1");
                            sysCampaignGroupCustomer.setOrgDistributeStatus("0");
                            sysCampaignGroupCustomer.setCustClaimStatus("0");
                        }//可选认领
                        else if (kx_claimType.equals(sysCampaign.getClaimType())){
                            sysCampaignGroupCustomer.setOrgClaimStatus("0");
                            sysCampaignGroupCustomer.setOrgDistributeStatus("0");
                            sysCampaignGroupCustomer.setCustClaimStatus("0");
                        }
                    }
                     Long  deptIde = deptIds.get(j);

                    //  custIdsMap --  有 该客户推送到非客户经理的数据，  且改数据 状态为 未推送/失败的情况下， 且机构与本次机构一致，则覆盖
                    if(! "3".equalsIgnoreCase(sysCampaign.getExecuter())) {
                        if (custIdsMap.get(sysCampaignGroupCustomer.getCustId()) != null
                                && custIdsMap.get(sysCampaignGroupCustomer.getCustId()).size() > 0
                                && (custIdsMap.get(sysCampaignGroupCustomer.getCustId()).stream().filter(c -> (
                                c.getDeptId() != null && c.getDeptId().equals(deptIde))
                                || c.getPushStatus().equalsIgnoreCase("0") || c.getPushStatus().equalsIgnoreCase("2")
                        )).collect(Collectors.toList()).size() > 0) {
                            List<SysCampaignGroupCustomer> campaignGroupCustomers = custIdsMap.get(sysCampaignGroupCustomer.getCustId()).stream().filter(c ->
                                    c.getDeptId() != null && c.getDeptId().equals(deptIde)).collect(Collectors.toList());
                            if (campaignGroupCustomers == null || campaignGroupCustomers.size() == 0) {
                                campaignGroupCustomers = custIdsMap.get(sysCampaignGroupCustomer.getCustId()).stream().filter(c ->
                                        c.getPushStatus().equals("0") || c.getPushStatus().equalsIgnoreCase("2")).collect(Collectors.toList());
                            }
                            SysCampaignGroupCustomer customer = campaignGroupCustomers.get(0);
                            BeanUtils.copyProperties(deptAndOutlet, customer);
                            Long id = customer.getId();
                            BeanUtils.copyProperties(sysCampaignGroupCustomer, customer);
                            customer.setCreateRole(createRole);
                            customer.setCreateBy(getUsername());
                            customer.setPushStatus("1");
                            customer.setId(id);
                            customer.setOutletsId(null);
                            customer.setOutlets(null);
                            campaignGroupCustomersUpdate.add(customer);
                            custIdsMap.remove(sysCampaignGroupCustomer.getCustId());
                        } else {
                            SysCampaignGroupCustomer temp = new SysCampaignGroupCustomer();
                            BeanUtils.copyProperties(sysCampaignGroupCustomer, temp);
                            campaignGroupCustomersInsert.add(temp);
                        }
                    }else if( "3".equalsIgnoreCase(sysCampaign.getExecuter())) {
                        if (custIdsMap.get(sysCampaignGroupCustomer.getCustId()) != null
                                && custIdsMap.get(sysCampaignGroupCustomer.getCustId()).size() > 0
                                && (custIdsMap.get(sysCampaignGroupCustomer.getCustId()).stream().filter(c -> (
                                c.getOutletsId() != null && c.getOutletsId().equals(deptIde))
                                || c.getPushStatus().equalsIgnoreCase("0") || c.getPushStatus().equalsIgnoreCase("2")
                        )).collect(Collectors.toList()).size() > 0) {
                            List<SysCampaignGroupCustomer> campaignGroupCustomers = custIdsMap.get(sysCampaignGroupCustomer.getCustId()).stream().filter(c ->
                                    c.getDeptId() != null && c.getDeptId().equals(deptIde)).collect(Collectors.toList());
                            if (campaignGroupCustomers == null || campaignGroupCustomers.size() == 0) {
                                campaignGroupCustomers = custIdsMap.get(sysCampaignGroupCustomer.getCustId()).stream().filter(c ->
                                        c.getPushStatus().equals("0") || c.getPushStatus().equalsIgnoreCase("2")).collect(Collectors.toList());
                            }
                            SysCampaignGroupCustomer customer = campaignGroupCustomers.get(0);
                            BeanUtils.copyProperties(deptAndOutlet, customer);
                            Long id = customer.getId();
                            BeanUtils.copyProperties(sysCampaignGroupCustomer, customer);
                            customer.setCreateRole(createRole);
                            customer.setCreateBy(getUsername());
                            customer.setPushStatus("1");
                            customer.setId(id);
                            campaignGroupCustomersUpdate.add(customer);
                            custIdsMap.remove(sysCampaignGroupCustomer.getCustId());
                        } else {
                            SysCampaignGroupCustomer temp = new SysCampaignGroupCustomer();
                            BeanUtils.copyProperties(sysCampaignGroupCustomer, temp);
                            campaignGroupCustomersInsert.add(temp);
                        }
                    }

                    //sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomer(sysCampaignGroupCustomer);
                }
            }

        }

        if (userIds!=null&&userIds.size()>0){
            List<DeptAndOutlets> deptAndOutlets = sysCampaignService.selectDeptAndOutletsByUserIds(userIds);
            for (int i = 0; i < userIds.size(); i++) {
                DeptAndOutlets deptAndOutlet = sysCampaignService.selectDeptAndOutletsByUserId(deptAndOutlets,userIds.get(i));
                for (int j = 0; j < campaignGroupCustomerList.size(); j++) {

                    SysCampaignGroupCustomer sysCampaignGroupCustomer = campaignGroupCustomerList.get(j);
                    SysCampaignGroupCustomer customer = new SysCampaignGroupCustomer();
                    BeanUtils.copyProperties(sysCampaignGroupCustomer,customer);
                    customer.setCreateBy(null);
//                    customer.setCreateRole( ROLE_HEAD.equalsIgnoreCase(userRole())? "0" : "1");
                    customer.setDeptId(deptAndOutlet.getDeptId());
                    customer.setOutletsId(deptAndOutlet.getOutletsId());
                    customer.setUserId(null);
                    customer.setPushStatus(null);
                    List<SysCampaignGroupCustomer> list =  sysCampaignGroupCustomerMapper.selectSysCampaignGroupCustomerList(customer);
                    list = list.stream().filter(l->l.getUserId()==null).collect(Collectors.toList());
                    sysCampaignGroupCustomer.setUserId(userIds.get(i));
                    //Long deptId = sysCampaignGroupCustomerMapper.getDeptIdByUserId(userIds.get(i));
                    sysCampaignGroupCustomer.setDeptId(deptAndOutlet.getDeptId());
                    sysCampaignGroupCustomer.setOutletsId(deptAndOutlet.getOutletsId());
                    sysCampaignGroupCustomer.setOutlets(deptAndOutlet.getOutlets());
                    sysCampaignGroupCustomer.setPushStatus("1");
                    sysCampaignGroupCustomer.setSecondPushStatus("1");

                    sysCampaignGroupCustomer.setOrgClaimStatus("1");
                    sysCampaignGroupCustomer.setOrgDistributeStatus("1");

                    //强制认领
                    if (qz_claimType.equals(sysCampaign.getClaimType())){
                        sysCampaignGroupCustomer.setCustClaimStatus("1");
                    }//可选认领
                    else if (kx_claimType.equals(sysCampaign.getClaimType())){
                        sysCampaignGroupCustomer.setCustClaimStatus("0");
                    }
                    if (custIdsMap.get(sysCampaignGroupCustomer.getCustId())!=null&&custIdsMap.get(sysCampaignGroupCustomer.getCustId()).size()>0){
                        List<SysCampaignGroupCustomer> campaignGroupCustomers = custIdsMap.get(sysCampaignGroupCustomer.getCustId());
                        SysCampaignGroupCustomer customer2 = campaignGroupCustomers.get(0);
                        Long id = customer2.getId();
                        BeanUtils.copyProperties(sysCampaignGroupCustomer,customer2);
                        BeanUtils.copyProperties(deptAndOutlet,customer2);
                        customer2.setCreateRole(createRole);
                        customer2.setCreateBy(getUsername());
                        customer2.setPushStatus("1");
                        customer2.setId(id);
                        campaignGroupCustomersUpdate.add(customer2);
                        custIdsMap.remove(sysCampaignGroupCustomer.getCustId());
                    }
                    //若本来就有分配到该机构下的该客户，但是未指定客户经理，则直接更新客户经理即可
                    else if (list.size()>0){
                            SysCampaignGroupCustomer customer1 = list.get(0);
                            BeanUtils.copyProperties(deptAndOutlet,customer1);
                            customer1.setCreateRole(createRole);
                            customer1.setCreateBy(getUsername());
                            //sysCampaignGroupCustomerMapper.updateSysCampaignGroupCustomer(customer1);
                            campaignGroupCustomersUpdate.add(customer1);
                    }else {
                        SysCampaignGroupCustomer temp = new SysCampaignGroupCustomer();
                        BeanUtils.copyProperties(sysCampaignGroupCustomer,temp);
                        campaignGroupCustomersInsert.add(temp);
                        //sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomer(sysCampaignGroupCustomer);
                    }


                }
            }

        }
        List<String> groupIds = new ArrayList<>();
        groupIds.add(groupId);
        if (campaignGroupCustomersInsert.size()>0){
            List<SysCampaignGroupCustomer> campaignGroupCustomersRemove = new ArrayList<>();
            campaignGroupCustomersInsert.forEach( e ->{
                SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                sysCampaignGroupCustomer.setCampaignId(e.getCampaignId());
                sysCampaignGroupCustomer.setCustId(e.getCustId());
                sysCampaignGroupCustomer.setDeptId(e.getDeptId());
                sysCampaignGroupCustomer.setUserId(e.getUserId());
                sysCampaignGroupCustomer.setDeptFlag(e.getUserId() == null ? "ture" : null);
                List<SysCampaignGroupCustomer> sysCampaignGroupCustomers = sysCampaignGroupCustomerMapper.selectSysCampaignGroupCustomerList(sysCampaignGroupCustomer);
                if(sysCampaignGroupCustomers.size() > 0){
                    campaignGroupCustomersRemove.add(e);
                }
            });
            log.info("重复insert的活动客户-》"+ campaignGroupCustomersRemove.stream().map(SysCampaignGroupCustomer:: getCustId).collect(Collectors.toList()));
            campaignGroupCustomersInsert.removeAll(campaignGroupCustomersRemove);



            if (campaignGroupCustomersInsert.size()>0) {
                campaignGroupCustomersInsert.forEach(e->{
                        //支行创建的时候， 无论是否到客户经理，一定要有  PushUserLevel
                        e.setPushUserLevel(ROLE_HEAD.equalsIgnoreCase(userRoleHeadOrBranch())   ? "head" : ROLE_BRANCH.equalsIgnoreCase(userRoleHeadOrBranch())?"branch":"outlet");
                        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");

                    // 更新处理 sys_campaign_group_customer_supplement，指定后。 delete flag 置为 1
                        sysCampaignGroupCustomerSupplementMapper.updateSysCampaignGroupCustomerSupplementDeleteFlag(campaignId,e.getCustId());
                    });
                    //   总行 手动指定到 支行之后， 如果支行有二次推送的情况，如该数据需要二次推送
                if( ROLE_HEAD.equalsIgnoreCase(userRoleHeadOrBranch()) ){
                    // 本次新增客户中，下发到支行的数据列表
                    secondAppoint(campaignGroupCustomersInsert,campaignId,groupIds);
                }
                if(campaignGroupCustomersInsert.size() > 0) {
                    sysCampaignGroupCustomerMapper.insertSysCampaignGroupCustomerBatch(campaignGroupCustomersInsert);
                }
            }
        }
        if (campaignGroupCustomersUpdate.size()>0){
            List<SysCampaignGroupCustomer> campaignGroupCustomersRemove = new ArrayList<>();
            campaignGroupCustomersUpdate.forEach( e ->{
                SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
                sysCampaignGroupCustomer.setCampaignId(e.getCampaignId());
                sysCampaignGroupCustomer.setCustId(e.getCustId());
                sysCampaignGroupCustomer.setDeptId(e.getDeptId());
                sysCampaignGroupCustomer.setUserId(e.getUserId());
                sysCampaignGroupCustomer.setDeptFlag(e.getUserId() == null ? "ture" : null);
                List<SysCampaignGroupCustomer> sysCampaignGroupCustomers = sysCampaignGroupCustomerMapper.selectSysCampaignGroupCustomerList(sysCampaignGroupCustomer);
                if(sysCampaignGroupCustomers.size() > 0){
                    campaignGroupCustomersRemove.add(e);
                }
            });
            log.info("重复update的活动客户-》"+ campaignGroupCustomersRemove.stream().map(SysCampaignGroupCustomer:: getCustId).collect(Collectors.toList()));
            campaignGroupCustomersUpdate.removeAll(campaignGroupCustomersRemove);


            campaignGroupCustomersUpdate.forEach(e->{
                    //支行创建的时候， 无论是否到客户经理，一定要有  PushUserLevel
                    e.setPushUserLevel(ROLE_HEAD.equalsIgnoreCase(userRoleHeadOrBranch()) ?   "head" : ROLE_BRANCH.equalsIgnoreCase(userRoleHeadOrBranch())?"branch":"outlet");
                    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");

                // 更新处理 sys_campaign_group_customer_supplement，指定后。 delete flag 置为 1
                    sysCampaignGroupCustomerSupplementMapper.updateSysCampaignGroupCustomerSupplementDeleteFlag(campaignId,e.getCustId());
                });
            //   总行 手动指定到 支行之后， 如果支行有二次推送的情况，如该数据需要二次推送
            if( ROLE_HEAD.equalsIgnoreCase(userRoleHeadOrBranch()) ){
                // 本次新增客户中，下发到支行的数据列表
                secondAppoint(campaignGroupCustomersUpdate,campaignId,groupIds);
            }
            if (campaignGroupCustomersUpdate.size()>0) {
                sysCampaignGroupCustomerMapper.updateSysCampaignGroupCustomerBatch(campaignGroupCustomersUpdate);
            }
        }
        SysCampaign campaign = new SysCampaign();
        campaign.setCampaignId(campaignId);
        List<SysCampaign> sysCampaigns = sysCampaignMapper.selectSysCampaignVoList(campaign);
        if(campaignGroupCustomersUpdate.size() + campaignGroupCustomersInsert.size()>0    &&  sysCampaigns.size()>0 && sysCampaigns.get(0).getDeptId().compareTo(getDeptId()) == 0){
                sysCampaigns.forEach(e->{
                    SysCampaign ae = new SysCampaign();
                    ae.setId(e.getId());
                    ae.setUpdateBy(getUsername());
                    ae.setUpdateTime(new Date());
                    sysCampaignMapper.updateSysCampaign(ae);
                    e.setUpdateBy(getUsername());
                    e.setCampaignId(campaignId);
                    sysCampaignMapper.updateHeadHandledMissionSysCampaign(e);
                });
        }
         return 1;
    }

    @Override
    public int secondAppoint(List<SysCampaignGroupCustomer> campaignGroupCustomers,String campaignId,List<String> groupIds) {
        SysCampaign sysCampaign = sysCampaignMapper.selectSysCampaignByCampaignId(campaignId);

        List<SysCampaignGroupCustomer> collectDept = new ArrayList<>();
        if(!"3".equalsIgnoreCase(sysCampaign.getExecuter())) {
            campaignGroupCustomers.stream().filter(e -> e.getDeptId() != null && e.getUserId() == null).collect(Collectors.toList());
            if (collectDept != null && collectDept.size() > 0) {
                log.info("本次新增客户需要进行 支行、网点二次分配的列表： " + collectDept.stream().map(SysCampaignGroupCustomer::getCustId).collect(Collectors.toList()));
                campaignGroupCustomers.removeAll(collectDept);
                // 按照支行分组处理
                Map<Long, List<SysCampaignGroupCustomer>> groupedByDeptId = collectDept.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 sysGroupCustomer = new SysGroupCustomer();
                            BeanUtils.copyProperties(e, sysGroupCustomer);
                            // 根据需要设置其他属性
                            return sysGroupCustomer;
                        }).collect(Collectors.toList());

                        sysCampaignService.distribute(sysCampaignBranchSecond, Arrays.asList(sysCampaignBranchSecond.getDistributeType().split(",")), sysGroupCustomersBranch, null, campaignId, sysCampaignGroupBranchCustomers);
                        sysCampaignGroupBranchCustomers.forEach(e -> {
                            e.setOrgClaimStatus("1");
                            e.setOrgDistributeStatus("1");
                            e.setPushUserLevel("branch");
                            e.setPushStatus("1");
                            e.setSecondPushStatus(e.getUserId() != null ? "1" : Arrays.asList(sysCampaignBranchSecond.getDistributeType().split(",")).contains("0") ? "0" : "2");
                        });

                    }
                    campaignGroupCustomers.addAll(sysCampaignGroupBranchCustomers);
                });
            }
        }else{
            //   网点层级
            campaignGroupCustomers.stream().filter(e -> e.getOutletsId() != null && e.getUserId() == null).collect(Collectors.toList());
            if (collectDept != null && collectDept.size() > 0) {
                log.info("本次新增客户需要进行 支行、网点二次分配的列表： " + collectDept.stream().map(SysCampaignGroupCustomer::getCustId).collect(Collectors.toList()));
                campaignGroupCustomers.removeAll(collectDept);
                // 按照支行分组处理
                Map<Long, List<SysCampaignGroupCustomer>> groupedByOutletId = collectDept.stream()
                        .collect(Collectors.groupingBy(SysCampaignGroupCustomer::getOutletsId));
                groupedByOutletId.forEach((deptId, sysCampaignGroupBranchCustomers) -> {
                    // 查询支行二次分配的规则
                    SysCampaign sysCampaignBranchSecond = sysCampaignMapper.selectSysCampaignSecondByCampaignId(campaignId, null,deptId);
                    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 sysGroupCustomer = new SysGroupCustomer();
                            BeanUtils.copyProperties(e, sysGroupCustomer);
                            // 根据需要设置其他属性
                            return sysGroupCustomer;
                        }).collect(Collectors.toList());

                        sysCampaignService.distribute(sysCampaignBranchSecond, Arrays.asList(sysCampaignBranchSecond.getDistributeType().split(",")), sysGroupCustomersBranch, null, campaignId, sysCampaignGroupBranchCustomers);
                        sysCampaignGroupBranchCustomers.forEach(e -> {
                            e.setOrgClaimStatus("1");
                            e.setOrgDistributeStatus("1");
                            e.setPushUserLevel("outlet");
                            e.setPushStatus("1");
                            e.setSecondPushStatus(e.getUserId() != null ? "1" : Arrays.asList(sysCampaignBranchSecond.getDistributeType().split(",")).contains("0") ? "0" : "2");
                        });

                    }
                    campaignGroupCustomers.addAll(sysCampaignGroupBranchCustomers);
                });
            }
        }
        return 1;
    }


    @Override
    public int orgClaim(String groupId, String campaignId) throws ServerException {
        SysCampaign campaign = sysCampaignMapper.selectSysCampaignByCampaignId(campaignId);
        Date now = new Date();
        if (campaign!=null){
            if (now.getTime()>campaign.getClaimEndTime().getTime()||now.getTime()<campaign.getClaimStartTime().getTime()){
                throw new ServerException("当前时间不在认领时间范围内，无法进行认领");
            }
        }
        SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
        sysCampaignGroupCustomer.setGroupId(groupId);
        sysCampaignGroupCustomer.setCampaignId(campaignId);
        if (userRole().equals("branch")){
            sysCampaignGroupCustomer.setDeptId(getDeptId());
        }else {
            sysCampaignGroupCustomer.setOutletsId(getDeptId());
        }
        List<SysCampaignGroupCustomer> campaignGroupCustomerList = sysCampaignGroupCustomerMapper.selectSysCampaignGroupCustomerList(sysCampaignGroupCustomer);
        //只需筛选出该机构下未分配到具体用户的数据认领
        campaignGroupCustomerList = campaignGroupCustomerList.stream().filter(c->c.getUserId()==null).collect(Collectors.toList());
        List<SysCampaignGroupCustomer> list = new ArrayList<>();
        list =campaignGroupCustomerList.stream().map(c->{
            SysCampaignGroupCustomer campaignGroupCustomer = new SysCampaignGroupCustomer();
            campaignGroupCustomer.setId(c.getId());
            campaignGroupCustomer.setOrgClaimStatus("1");
            return campaignGroupCustomer;
                }
        ).collect(Collectors.toList());
        if (list.size()>0){
            sysCampaignGroupCustomerMapper.updateSysCampaignGroupCustomerBatch(list);
        }
        return 1;
    }

    @Override
    public int custClaim(String groupId, String campaignId,List<String> custIds) throws ServerException {
        SysCampaign campaign = sysCampaignMapper.selectSysCampaignByCampaignId(campaignId);
        Date now = new Date();
        if (campaign!=null){
            if (now.getTime()>campaign.getClaimEndTime().getTime()||now.getTime()<campaign.getClaimStartTime().getTime()){
                throw new ServerException("当前时间不在认领时间范围内，无法进行认领");
            }
        }
        SysCampaignGroupCustomer sysCampaignGroupCustomer = new SysCampaignGroupCustomer();
        sysCampaignGroupCustomer.setGroupId(groupId);
        sysCampaignGroupCustomer.setCampaignId(campaignId);
        sysCampaignGroupCustomer.setUserId(getUserId());
        List<Long> userIds = new ArrayList<>();
        userIds.add(getUserId());
        List<DeptAndOutlets> deptAndOutlets= sysCampaignService.selectDeptAndOutletsByUserIds(userIds);
        if (deptAndOutlets.size()>0){
            sysCampaignGroupCustomer.setDeptId(deptAndOutlets.get(0).getDeptId());
        }
        if (custIds!=null&&custIds.size()>0){
            for (int i = 0; i < custIds.size(); i++) {
                String custId = custIds.get(i);
                sysCampaignGroupCustomer.setCustId(custId);
                List<SysCampaignGroupCustomer> campaignGroupCustomerList = sysCampaignGroupCustomerMapper.selectSysCampaignGroupCustomerList(sysCampaignGroupCustomer);
                if (campaignGroupCustomerList!=null){
                    for (int j = 0; j < campaignGroupCustomerList.size(); j++) {
                        SysCampaignGroupCustomer customer = campaignGroupCustomerList.get(j);
                        customer.setCustClaimStatus("1");
                        sysCampaignGroupCustomerMapper.updateSysCampaignGroupCustomer(customer);
                    }

                }
            }
        }
        return 1;
    }
}
