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

import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.CustInfoBusiness;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.ibs.grid.domain.vo.NewAnchor;
import com.ruoyi.ibs.grid.service.AnchorService;
import com.ruoyi.ibs.list.domain.*;
import com.ruoyi.ibs.list.mapper.SysCampaignMapper;
import com.ruoyi.ibs.list.mapper.SysGroupCustomerMapper;
import com.ruoyi.ibs.list.mapper.SysGroupMapper;
import com.ruoyi.ibs.list.service.*;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
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 org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.rmi.ServerException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.success;
import static com.ruoyi.common.utils.SecurityUtils.*;
import static com.ruoyi.ibs.enumertion.CustTypeEnum.*;
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
public class SysGroupServiceImpl implements ISysGroupService {
    private static Logger logger = LoggerFactory.getLogger(SysGroupServiceImpl.class);

    @Autowired
    private SysGroupMapper sysGroupMapper;

    @Autowired
    private SysGroupCustomerMapper sysGroupCustomerMapper;
    @Autowired
    private ISysGroupCustomerService sysGroupCustomerService;

    @Autowired
    private ICustInfoRetailService custInfoRetailService;

    @Autowired
    private ICustInfoMerchantService custInfoMerchantService;

    @Autowired
    private ICustInfoBusinessService custInfoBusinessService;

    @Autowired
    private SysCampaignMapper sysCampaignMapper;

    @Autowired
    private AnchorService anchorService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    /**
     * 查询客群圈选分群
     *
     * @param id 客群圈选分群主键
     * @return 客群圈选分群
     */
    @Override
    public SysGroup selectSysGroupById(Long id) {
        return sysGroupMapper.selectSysGroupById(id);
    }

    @Override
    public SysGroup selectSysGroupByGroupId(String groupId) {
        return sysGroupMapper.selectSysGroupByGroupId(groupId);
    }

    @Override
    public String selectSysGroupNameByGroupId(String groupId) {
        return sysGroupMapper.selectSysGroupNameByGroupId(groupId);
    }

    @Override
    public List<SysGroup> selectSysGroupListBydeptId() {
        String roleName = userRole();
        Long deptId = getDeptId();
        if ("admin".equals(roleName)) {
            return sysGroupMapper.selectSysGroupBydeptId(null);
        }
        if ("branch".equals(roleName)) {
            return sysGroupMapper.selectSysGroupBydeptId1(deptId);
        }
        if ("manager".equals(roleName)) {
            return sysGroupMapper.selectSysGroupBydeptIdAndUserId(deptId, getUsername());
        }else {
            return sysGroupMapper.selectSysGroupBydeptId(deptId);
        }
    }

    /**
     * 查询客群圈选分群列表
     *
     * @param groupName 客群圈选分群
     * @return 客群圈选分群
     */
    @Override
    public List<SysGroupVo> selectSysGroupList(String groupName, String groupType, String createBy, SysGroupSortVo groupSortVo, String type) {
        String roleName = userRole();
        List<SysGroupVo> sysGroups = new ArrayList<>();
        //总行管理员查询到所有客群
        if ("admin".equals(roleName)) {
            //总行管理员无别人推荐给我的客群
            sysGroups = sysGroupMapper.selectSysGroupList(groupName, null, createBy, groupSortVo.getCustomerNumSort(), groupSortVo.getUpdateTimeSort(), type);
        }
        if (ROLE_HEAD.equals(roleName) || ROLE_HeadPublic.equals(roleName) || ROLE_HeadPrivate.equals(roleName) || ROLE_HeadOps.equals(roleName)) {
            //总行管理员无别人推荐给我的客群
            sysGroups = sysGroupMapper.selectSysGroupList(groupName, getDeptId() / 1000, createBy, groupSortVo.getCustomerNumSort(), groupSortVo.getUpdateTimeSort(), type);
            List<SysGroupVo> filteredCustomerLists = new ArrayList<>();
            if (ROLE_HeadPublic.equals(roleName)) {              //公司部门管理员，查看导出企业类型
                filteredCustomerLists = sysGroups.stream()
                        .filter(customer -> "2".equals(customer.getCustType()))
                        .peek(customer -> customer.setCheckType("1")).collect(Collectors.toList());
            } else if (ROLE_HeadPrivate.equals(roleName)) {       //零售部门管理员，查看导出个人、商户类型
                filteredCustomerLists = sysGroups.stream()
                        .filter(customer -> "0".equals(customer.getCustType()) || "1".equals(customer.getCustType()))
                        .peek(customer -> customer.setCheckType("1")).collect(Collectors.toList());
            } else if (ROLE_HEAD.equals(roleName) || ROLE_HeadOps.equals(roleName)) {
                filteredCustomerLists = sysGroups.stream()
                        .peek(customer -> customer.setCheckType("1")).collect(Collectors.toList());
            }

        }
        if (ROLE_BRANCH.equals(roleName) || ROLE_Outlet.equals(roleName)) {
            //支行管理员，我创建的，查询该机构下所有的客群
            if ("1".equals(groupType)) {
                sysGroups = sysGroupMapper.selectSysGroupList1(groupName, getDeptId(), createBy, groupSortVo.getCustomerNumSort(), groupSortVo.getUpdateTimeSort(), type);
            }
            sysGroups = sysGroups.stream()
                    .peek(customer -> customer.setCheckType("1")).collect(Collectors.toList());
        }
        if ("manager".equals(roleName) ) {
            //客户经理，我创建的，查询该机构下所有的客群
            if ("1".equals(groupType)) {
                String userName = SecurityUtils.getUsername();
                sysGroups = sysGroupMapper.selectSysGroupList1(groupName, null, userName, groupSortVo.getCustomerNumSort(), groupSortVo.getUpdateTimeSort(), type);
            }
            sysGroups = sysGroups.stream()
                    .peek(customer -> customer.setCheckType("1")).collect(Collectors.toList());
        }
        sysGroups.forEach(group -> {
            if (("0").equalsIgnoreCase(group.getCreateRole())) {
                group.setCreateRole("headAdmin");
            } else if (("1").equalsIgnoreCase(group.getCreateRole())) {
                group.setCreateRole("branchAdmin");
            } else if (("2").equalsIgnoreCase(group.getCreateRole())) {
                group.setCreateRole("headPublic");
            } else if (("3").equalsIgnoreCase(group.getCreateRole())) {
                group.setCreateRole("headPrivate");
            } else if (("4").equalsIgnoreCase(group.getCreateRole())) {
                group.setCreateRole("headOps");
            }
        });
        return sysGroups;
    }


    @Override
    public List<CustomerList> selectCustomerList(String groupId, CustomerList customerList, String groupType) {
        List<CustomerList> customerLists = new ArrayList<>();
        //总行管理员查询到所有客群用户
        String roleName = userRole();
        if (ROLE_HEAD.equals(roleName) || ROLE_HeadPublic.equals(roleName) || ROLE_HeadPrivate.equals(roleName) || ROLE_HeadOps.equals(roleName)) {
            customerLists = sysGroupMapper.selectSysGroupListImport(groupId, null, customerList.getCustId(), customerList.getCustIdc(), customerList.getCustName(), customerList.getSocialCreditCode(), customerList.getTellerId(), customerList.getPushStatus());
        }
        if (ROLE_BRANCH.equals(roleName) || ROLE_Outlet.equals(roleName)) {
            //支行管理员查询我导入的客群下全部客户
            if (groupType == null || "1".equals(groupType)) {
                customerLists = sysGroupMapper.selectSysGroupListImport(groupId, null, customerList.getCustId(), customerList.getCustIdc(), customerList.getCustName(), customerList.getSocialCreditCode(), customerList.getTellerId(), customerList.getPushStatus());
            } else if ("0".equals(groupType)) {
                customerLists = sysGroupMapper.selectSysGroupList2(groupId, getDeptId(), customerList.getCustId(), customerList.getCustIdc(), customerList.getCustName(), customerList.getCustIsn(), customerList.getGridName()
                        , customerList.getGridName2(), customerList.getDeptName(), customerList.getOutlets(), customerList.getUserName(), customerList.getSocialCreditCode(), customerList.getPushStatus());
            }


        }
        if ("manager".equals(roleName)) {
            //支行管理员查询我导入的客群下全部客户
            if (groupType == null || "1".equals(groupType)) {
                customerLists = sysGroupMapper.selectSysGroupListImport(groupId, null, customerList.getCustId(), customerList.getCustIdc(), customerList.getCustName(), customerList.getSocialCreditCode(), customerList.getTellerId(), customerList.getPushStatus());
            }
        }
        return customerLists;
    }

    @Override
    public List<CustomerList> selectCustomerListDetail(String groupId, CustomerList customerList, String groupType) {
        return sysGroupMapper.selectCustomerList(groupId, null, customerList.getCustId(), customerList.getCustIdc(), customerList.getCustName(), customerList.getCustIsn(), customerList.getGridName()
                , customerList.getGridName2(), customerList.getDeptName(), customerList.getOutlets(), customerList.getUserName(), customerList.getSocialCreditCode(), customerList.getPushStatus());
    }


    @Override
    public HashMap isHead(String username) {
        String roleName = userRole();
        HashMap map = new HashMap();
        if ("admin".equals(roleName)) {
            map.put(RoleEnum.admin.getRoleKey(), RoleEnum.admin.getRoleName());
        } else if ("head".equals(roleName)) {
            map.put(RoleEnum.headAdmin.getRoleKey(), RoleEnum.headAdmin.getRoleName());
        } else if ("public".equals(roleName)) {
            map.put(RoleEnum.headPublic.getRoleKey(), RoleEnum.headPublic.getRoleName());
        } else if ("private".equals(roleName)) {
            map.put(RoleEnum.headPrivate.getRoleKey(), RoleEnum.headPrivate.getRoleName());
        } else if ("ops".equals(roleName)) {
            map.put(RoleEnum.headOps.getRoleKey(), RoleEnum.headOps.getRoleName());
        } else if ("branch".equals(roleName)) {
            map.put(RoleEnum.branchAdmin.getRoleKey(), RoleEnum.branchAdmin.getRoleName());
        } else if ("outlet".equals(roleName)) {
            map.put(RoleEnum.outletAdmin.getRoleKey(), RoleEnum.outletAdmin.getRoleName());
        } else if ("manager".equals(roleName)) {
            map.put(RoleEnum.commonManager.getRoleKey(), RoleEnum.commonManager.getRoleName());
        } else {
            map.put(RoleEnum.otherUser.getRoleKey(), RoleEnum.otherUser.getRoleName());
        }
        return map;


    }

    /**
     * 新增客群圈选分群
     *
     * @param sysGroup 客群圈选分群
     * @return 结果
     */
    @Override
    public int insertSysGroup(SysGroup sysGroup) throws ServerException {
        if (StringUtils.isNotBlank(sysGroup.getGroupName())) {
            int count = selectByGroupName(sysGroup.getGroupName());
            if (count > 0) {
                throw new ServerException("系统中已有重名客群,请修改客群名称");
            }
        }
        String uuid = UUID.randomUUID().toString();
        sysGroup.setGroupId(uuid);
        sysGroup.setCreateTime(new Date());
        sysGroup.setCreateBy(getUsername());
        sysGroup.setUserId(getUserId());
        sysGroup.setDeptId(getDeptId());
        sysGroup.setCreateType("1");
        sysGroup.setStatus("运行中");
        return sysGroupMapper.insertSysGroup(sysGroup);
    }

    @Override
    @Transactional
    public CustIncrementVo insertSysGroupAndCustomer(MultipartFile file, String groupName, String custType, String groupId, String importType) throws IOException {
        ExcelUtil<SysGroupCustomer> util = new ExcelUtil<>(SysGroupCustomer.class);
        List<SysGroupCustomer> customersList = util.importExcel(file.getInputStream());
        int size = 0;
        SysGroup group = new SysGroup();
        if (StringUtils.isBlank(groupId)) {
//            int count = selectByGroupName(groupName);
//            if (count>0){
//                throw new ServerException("系统中已有重名客群,请修改客群名称");
//            }
            String uuid = UUID.randomUUID().toString();
            group.setGroupId(uuid);
            group.setCustType(custType);
            group.setGroupName(groupName);
            group.setCreateTime(DateUtils.getNowDate());
            group.setCreateType("0");
            //先默认更新方式为手动更新
            group.setUpdateType("1");
            group.setStatus("运行中");
            group.setUpdateTime(DateUtils.getNowDate());
            group.setCreateBy(getUsername());
            group.setGroupType("1");
            group.setDeptId(getDeptId());
            group.setUserId(getUserId());
            String roleName = userRole();
            if (ROLE_HEAD.equals(roleName)) {
                group.setCreateRole("0");
            } else if (ROLE_BRANCH.equals(roleName)) {
                group.setCreateRole("1");
            } else if (ROLE_HeadPublic.equals(roleName)) {
                group.setCreateRole("2");
            } else if (ROLE_HeadPrivate.equals(roleName)) {
                group.setCreateRole("3");
            } else if (ROLE_HeadOps.equals(roleName)) {
                group.setCreateRole("4");
            }
        } else {
            group = selectSysGroupByGroupId(groupId);
            group.setUpdateTime(DateUtils.getNowDate());
            group.setUpdateBy(getUsername());
        }
        //去除空格
        customersList.stream().forEach(customer -> {
            if(Objects.nonNull(customer.getCustId())){
                customer.setCustId(customer.getCustId().trim());
            }
        });

        String operName = getUsername();
        String error = "第 ";
        Boolean flag = true;
        if (PERSONAL.getCode().equals(custType)) {
            for (SysGroupCustomer customer : customersList) {
                //客户经理导入将推送客户经理设置为自己
                if (userRole().equals("manager")){
                    customer.setTellerId(SecurityUtils.getUsername());
                }
                //todo 补充支行和网点id，判断该客户是否导入成功
                if (customer.getRemark() == null)
                    customer.setRemark("");
                if (customer.getCustType() != null) {
                    //校验输入是否是个人、客户号开头是否是101
                    if (!customer.getCustType().equals("个人"))
                        customer.setRemark(customer.getRemark() + "、填写客户类型与选择不一致");
                    customer.setPushStatus("2");
                }
                if (customer.getDeptId() != null) {
                    //查询机构号是什么类型，是网点就补充父节点支行，是支行则补充名字。若未查询到，则推送状态变为失败
                    SysDept dept = deptMapper.selectDeptById(customer.getDeptId());
                    if (dept != null && dept.getDeptType().equals("outlet")) {
                        customer.setOutletsId(customer.getDeptId());
                        customer.setOutlets(dept.getDeptName());
                        customer.setDeptId(dept.getParentId());
                        customer.setDeptName(deptMapper.selectDeptById(dept.getParentId()).getDeptName());
                    } else if (dept == null) {
                        //未查到
                        customer.setRemark(customer.getRemark() + "、推送机构号不存在");
                        customer.setPushStatus("2");
                    } else if (dept.getDeptType().equals("branch")) {
                        customer.setDeptName(dept.getDeptName());
                    }
                }
                if (customer.getCustId() == null || customer.getCustId().length() != 21) {
                    customer.setRemark(customer.getRemark() + "、客户号不正确");
                    customer.setPushStatus("2");
                } else if (!customer.getCustId().substring(0, 3).equals("101")) {
                    customer.setRemark(customer.getRemark() + "、客户号前缀与所选类型不匹配");
                    customer.setPushStatus("2");
                } else {
                    customer.setCustIdc(customer.getCustId().substring(3));
                    //验证客户姓名
                    CustInfoRetail retail = custInfoRetailService.selectCustInfoRetailByCustId(customer.getCustId());
                    if (customer.getCustName()==null||customer.getCustName().equals("")){
                        if (retail==null||retail.getCustName()==null||retail.getCustName().equals("")){
                            customer.setRemark(customer.getRemark() + "、新客必须录入客户名称");
                            customer.setPushStatus("2");
                        }else{
                            customer.setCustName(retail.getCustName());
                        }
                    }
                }
                if (StringUtils.isBlank(customer.getIdType())) {
                    customer.setIdType("居民二代身份证");
                }
                //去除客户号等数据前后空格
                if (StringUtils.isNotEmpty(customer.getCustId())) {
                    customer.setCustId(customer.getCustId().trim());
                }
                if (StringUtils.isNotEmpty(customer.getCustIdc())) {
                    customer.setCustIdc(customer.getCustIdc().trim());
                }
                if (StringUtils.isNotEmpty(customer.getSocialCreditCode())) {
                    customer.setSocialCreditCode(customer.getSocialCreditCode().trim());
                }
                if (StringUtils.isNotEmpty(customer.getTellerId())) {
                    SysUser user = userMapper.selectUserByUserName(customer.getTellerId());
                    if (user == null) {
                        customer.setPushStatus("2");
                        customer.setRemark(customer.getRemark() + "、推送柜员号不存在");
//                        throw new ServerException("导入失败，请检查柜员号是否存在");
                    } else {
                        SysDept userDept = deptMapper.selectDeptById(user.getDeptId());
                        if ((userDept != null && userDept.getDeptType().equals("branch")) || (userDept != null && userDept.getDeptType().equals("head"))) {
                            if (customer.getDeptId() != null && !userDept.getDeptId().equals(customer.getDeptId())) {
                                customer.setPushStatus("2");
                                customer.setRemark(customer.getRemark() + "、填写支行或网点号与客户经理不匹配");
                            } else {
                                customer.setDeptId(userDept.getDeptId());
                                customer.setDeptName(userDept.getDeptName());
                            }
                        } else {
                            if (userDept != null && userDept.getDeptType().equals("outlet")) {
                                SysDept dept = deptMapper.selectDeptById(userDept.getParentId());
                                if (customer.getDeptId() != null && !dept.getDeptId().equals(customer.getDeptId())) {
                                    customer.setPushStatus("2");
                                    customer.setRemark(customer.getRemark() + "、填写支行或网点号与客户经理不匹配");
                                } else {
                                    customer.setOutletsId(userDept.getDeptId());
                                    customer.setOutlets(userDept.getDeptName());
                                    customer.setDeptId(dept.getDeptId());
                                    customer.setDeptName(dept.getDeptName());
                                }
                            }
                        }
                    }
                }
            }
//            boolean anyHaveSocialCreditCode = customersList.stream()
//                    .anyMatch(business -> business.getCustIdc() != null && !business.getCustIdc().isEmpty());
//            if (!anyHaveSocialCreditCode) {
//                throw new ServerException("导入失败，请检查模板以及数据准确性");
//            }
        }
        //商户或企业客群因导入模板不同，需要转换对象后插入客群表
        else if (MERCHANT.getCode().equals(custType)) {
            for (SysGroupCustomer customer : customersList) {
                //客户经理导入将推送客户经理设置为自己
                if (userRole().equals("manager")){
                    customer.setTellerId(SecurityUtils.getUsername());
                }
                //todo 补充支行和网点id，判断该客户是否导入成功
                if (customer.getRemark() == null)
                    customer.setRemark("");
                if (customer.getCustType() != null) {
                    //校验输入是否是个人、客户号开头是否是101
                    if (!customer.getCustType().equals("商户"))
                        customer.setRemark(customer.getRemark() + "、填写客户类型与选择不一致");
                    customer.setPushStatus("2");
                }
                if (customer.getDeptId() != null) {
                    SysDept dept = deptMapper.selectDeptById(customer.getDeptId());
                    if (dept != null && dept.getDeptType().equals("outlet")) {
                        customer.setOutletsId(customer.getDeptId());
                        customer.setOutlets(dept.getDeptName());
                        customer.setDeptId(dept.getParentId());
                        customer.setDeptName(deptMapper.selectDeptById(dept.getParentId()).getDeptName());
                    } else if (dept == null) {
                        customer.setRemark(customer.getRemark() + "、推送机构号不存在");
                        customer.setPushStatus("2");
                    } else if (dept.getDeptType().equals("branch")) {
                        customer.setDeptName(dept.getDeptName());
                    }
                }
                //填充证件号
                if (customer.getCustId() == null || customer.getCustId().length() != 21) {
                    customer.setRemark(customer.getRemark() + "、客户号不正确");
                    customer.setPushStatus("2");
                } else if (!customer.getCustId().substring(0, 3).equals("202")) {
                    customer.setRemark(customer.getRemark() + "、客户号前缀与所选类型不匹配");
                    customer.setPushStatus("2");
                } else {
                    customer.setSocialCreditCode(customer.getCustId().substring(3));
                    customer.setSocialCreditCode(customer.getSocialCreditCode().toUpperCase());
                    CustInfoMerchant merchant = custInfoMerchantService.selectCustInfoMerchantByCustId(customer.getCustId());
                    if (customer.getCustName()==null||customer.getCustName().equals("")){
                        if (merchant==null||merchant.getCustName()==null||merchant.getCustName().equals("")){
                            customer.setRemark(customer.getRemark() + "、新客必须录入客户名称");
                            customer.setPushStatus("2");
                        }else{
                            customer.setCustName(merchant.getCustName());
                        }
                    }

                }
                if (StringUtils.isBlank(customer.getIdType())) {
                    customer.setIdType("居民二代身份证");
                }
                if (StringUtils.isBlank(customer.getSocialCreditCodeType())) {
                    customer.setSocialCreditCodeType("营业执照");
                }
                //去除客户号等数据前后空格
                if (StringUtils.isNotEmpty(customer.getCustId())) {
                    customer.setCustId(customer.getCustId().trim());
                }
                if (StringUtils.isNotEmpty(customer.getCustIdc())) {
                    customer.setCustIdc(customer.getCustIdc().trim());
                }
                if (StringUtils.isNotEmpty(customer.getSocialCreditCode())) {
                    customer.setSocialCreditCode(customer.getSocialCreditCode().trim());
                }
                if (StringUtils.isNotEmpty(customer.getTellerId())) {
                    SysUser user = userMapper.selectUserByUserName(customer.getTellerId());
                    if (user == null) {
                        customer.setPushStatus("2");
                        customer.setRemark(customer.getRemark() + "、推送柜员号不存在");
//                        throw new ServerException("导入失败，请检查柜员号是否存在");
                    } else {
                        SysDept userDept = deptMapper.selectDeptById(user.getDeptId());
                        if ((userDept != null && userDept.getDeptType().equals("branch")) || (userDept != null && userDept.getDeptType().equals("head"))) {
                            if (customer.getDeptId() != null && !userDept.getDeptId().equals(customer.getDeptId())) {
                                customer.setPushStatus("2");
                                customer.setRemark(customer.getRemark() + "、填写支行或网点号与客户经理不匹配");
                            } else {
                                customer.setDeptId(userDept.getDeptId());
                                customer.setDeptName(userDept.getDeptName());
                            }
                        } else {
                            if (userDept != null && userDept.getDeptType().equals("outlet")) {
                                SysDept dept = deptMapper.selectDeptById(userDept.getParentId());
                                if (customer.getDeptId() != null && !dept.getDeptId().equals(customer.getDeptId())) {
                                    customer.setPushStatus("2");
                                    customer.setRemark(customer.getRemark() + "、填写支行或网点号与客户经理不匹配");
                                } else {
                                    customer.setOutletsId(userDept.getDeptId());
                                    customer.setOutlets(userDept.getDeptName());
                                    customer.setDeptId(dept.getDeptId());
                                    customer.setDeptName(dept.getDeptName());
                                }
                            }
                        }
                    }
                }
            }
            boolean anyHaveSocialCreditCode = customersList.stream()
                    .anyMatch(business -> business.getSocialCreditCode() != null && !business.getSocialCreditCode().isEmpty());
            if (!anyHaveSocialCreditCode) {
                throw new ServerException("导入失败，请检查模板以及数据准确性");
            }
        } else if (ENTERPRISE.getCode().equals(custType)) {
            for (SysGroupCustomer customer : customersList) {
                //客户经理导入将推送客户经理设置为自己
                if (userRole().equals("manager")){
                    customer.setTellerId(SecurityUtils.getUsername());
                }
                //todo 补充支行和网点id，判断该客户是否导入成功
                if (customer.getRemark() == null)
                    customer.setRemark("");
                if (customer.getCustType() != null) {
                    //校验输入是否是个人、客户号开头是否是202

                    if (!customer.getCustType().equals("企业"))
                        customer.setRemark(customer.getRemark() + "、填写客户类型与选择不一致");
                    customer.setPushStatus("2");
                }
                if (customer.getDeptId() != null) {
                    SysDept dept = deptMapper.selectDeptById(customer.getDeptId());
                    if (dept != null && dept.getDeptType().equals("outlet")) {
                        customer.setOutletsId(customer.getDeptId());
                        customer.setOutlets(dept.getDeptName());
                        customer.setDeptId(dept.getParentId());
                        customer.setDeptName(deptMapper.selectDeptById(dept.getParentId()).getDeptName());
                    } else if (dept == null) {
                        customer.setRemark(customer.getRemark() + "、推送机构号不存在");
                        customer.setPushStatus("2");
                    } else if (dept.getDeptType().equals("branch")) {
                        customer.setDeptName(dept.getDeptName());
                    }
                }
                //填充证件号
                if (customer.getCustId() == null || customer.getCustId().length() != 21) {
                    customer.setRemark(customer.getRemark() + "、客户号不正确");
                    customer.setPushStatus("2");
                } else if (!customer.getCustId().substring(0, 3).equals("202")) {
                    customer.setRemark(customer.getRemark() + "、客户号前缀与所选类型不匹配");
                    customer.setPushStatus("2");
                } else {
                    customer.setSocialCreditCode(customer.getCustId().substring(3));
                    customer.setSocialCreditCode(customer.getSocialCreditCode().toUpperCase());
                    CustInfoBusiness business = custInfoBusinessService.selectCustInfoBusinessByCustId(customer.getCustId());
                    if (customer.getCustName()==null||customer.getCustName().equals("")){
                        if (business==null||business.getCustName()==null||business.getCustName().equals("")){
                            customer.setRemark(customer.getRemark() + "、新客必须录入客户名称");
                            customer.setPushStatus("2");
                        }else{
                            customer.setCustName(business.getCustName());
                        }
                    }
                }
                if (StringUtils.isBlank(customer.getIdType())) {
                    customer.setIdType("居民二代身份证");
                }
                if (StringUtils.isBlank(customer.getSocialCreditCodeType())) {
                    customer.setSocialCreditCodeType("营业执照");
                }
                //去除客户号等数据前后空格
                if (StringUtils.isNotEmpty(customer.getCustId())) {
                    customer.setCustId(customer.getCustId().trim());
                }
                if (StringUtils.isNotEmpty(customer.getCustIdc())) {
                    customer.setCustIdc(customer.getCustIdc().trim());
                }
                if (StringUtils.isNotEmpty(customer.getSocialCreditCode())) {
                    customer.setSocialCreditCode(customer.getSocialCreditCode().trim());
                }
                if (StringUtils.isNotEmpty(customer.getTellerId())) {
                    SysUser user = userMapper.selectUserByUserName(customer.getTellerId());
                    if (user == null) {
                        customer.setPushStatus("2");
                        customer.setRemark(customer.getRemark() + "、推送柜员号不存在");
//                        throw new ServerException("导入失败，请检查柜员号是否存在");
                    } else {
                        SysDept userDept = deptMapper.selectDeptById(user.getDeptId());
                        if ((userDept != null && userDept.getDeptType().equals("branch")) || (userDept != null && userDept.getDeptType().equals("head"))) {
                            if (customer.getDeptId() != null && !userDept.getDeptId().equals(customer.getDeptId())) {
                                customer.setPushStatus("2");
                                customer.setRemark(customer.getRemark() + "、填写支行或网点号与客户经理不匹配");
                            } else {
                                customer.setDeptId(userDept.getDeptId());
                                customer.setDeptName(userDept.getDeptName());
                            }
                        } else {
                            if (userDept != null && userDept.getDeptType().equals("outlet")) {
                                SysDept dept = deptMapper.selectDeptById(userDept.getParentId());
                                if (customer.getDeptId() != null && !dept.getDeptId().equals(customer.getDeptId())) {
                                    customer.setPushStatus("2");
                                    customer.setRemark(customer.getRemark() + "、填写支行或网点号与客户经理不匹配");
                                } else {
                                    customer.setOutletsId(userDept.getDeptId());
                                    customer.setOutlets(userDept.getDeptName());
                                    customer.setDeptId(dept.getDeptId());
                                    customer.setDeptName(dept.getDeptName());
                                }
                            }
                        }
                    }
                }
            }
            boolean anyHaveSocialCreditCode = customersList.stream()
                    .anyMatch(business -> business.getSocialCreditCode() != null && !business.getSocialCreditCode().isEmpty());
            if (!anyHaveSocialCreditCode) {
                throw new ServerException("导入失败，请检查模板以及数据准确性");
            }
        }

        //筛选出必填项不为空的数据
        List<SysGroupCustomer> notEmptyList = getNotEmptyList(customersList, operName, group.getGroupId(), custType);

        if (notEmptyList != null && notEmptyList.size() > 0) {
            long distinctCustNameCount = notEmptyList.stream().map(SysGroupCustomer::getCustName).distinct().count();
//            if (PERSONAL.getCode().equals(custType)) {
            long distinctIdCount = notEmptyList.stream().map(SysGroupCustomer::getCustId).distinct().count();
            if (distinctIdCount < distinctCustNameCount) {
                throw new ServerException("导入失败，请检查模板以及数据准确性");
            }
//            } else if (MERCHANT.getCode().equals(custType) || ENTERPRISE.getCode().equals(custType)) {
//                long distinctIdcCount = notEmptyList.stream().map(SysGroupCustomer::getSocialCreditCode).distinct().count();
//                if (distinctIdcCount < distinctCustNameCount) {
//                    throw new ServerException("导入失败，请检查模板以及数据准确性");
//                }
//            }
        }
        //首次导入，有重复数据时导入失败
        if ("0".equalsIgnoreCase(importType)) {
            // 使用一个集合来记录重复的 custId
            Set<String> duplicateCustIds = notEmptyList.stream()
                    .collect(Collectors.groupingBy(SysGroupCustomer::getCustId, Collectors.counting()))
                    .entrySet().stream().filter(entry -> entry.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toSet());
            if (!duplicateCustIds.isEmpty()) {
                String warningStr = "客户号：" + String.join(", ", duplicateCustIds) + " 重复";
                throw new ServerException("导入失败，" + warningStr);
            }
        }
        notEmptyList = filterAddressAndPhone(notEmptyList, custType);
        //记录错误行数据返回
//        error = error + getErrorList(customersList,custType);
        //todo 筛选出导入模板里面客户号错误的数据，无法导入
//        List<String> custIds = notEmptyList.stream().map(s->{return s.getCustId();}).collect(Collectors.toList());
//        //查询出数据库存在的客户id列表
//        List<String> custIdsExit = sysGroupCustomerMapper.selectCustIds(custType,custIds);
//        List<SysGroupCustomer> sysGroupCustomersExit = notEmptyList.stream().filter(s->custIdsExit.contains(s.getCustId())).collect(Collectors.toList());
//        if ("0".equalsIgnoreCase(importType)) {
//            size = notEmptyList.size();
//        } else if ("1".equalsIgnoreCase(importType)) {
//            size = notEmptyList.size() + group.getCustomerNum().intValue();
//        }

        String warningStr = "";
        if ("1".equalsIgnoreCase(importType)) {
            List<String> conditionList = new ArrayList<>();
//            if (PERSONAL.getCode().equals(custType)) {
                conditionList = notEmptyList.stream().map(p -> p.getCustId()).distinct().collect(Collectors.toList());
                List<SysGroupCustomer> custIdcList = sysGroupCustomerMapper.selectCustIdcList(conditionList, custType, groupId);//重复数据集合
            if (custIdcList != null && custIdcList.size() > 0) {
                for (SysGroupCustomer customer : custIdcList) {
                    if ("1".equalsIgnoreCase(customer.getPushStatus())) {
                        notEmptyList = notEmptyList.stream().filter(p -> !p.getCustId().equals(customer.getCustId())).collect(Collectors.toList());
                    } else if ("2".equalsIgnoreCase(customer.getPushStatus())) {
                        sysGroupCustomerMapper.deleteSysGroupCustomerByCustId(customer.getGroupId(),customer.getCustId());
                    }
                }
                notEmptyList = notEmptyList.stream().filter(p -> !custIdcList.contains(p.getCustId())).collect(Collectors.toList());
                List<String> custIdList = custIdcList.stream().map(custIdc -> custIdc.getCustId()).collect(Collectors.toList());
                if (custIdList != null && custIdList.size() > 0){
                    warningStr = "客户号：" + String.join(", ", custIdList) + " 已存在";
                }
            }
            size = notEmptyList.size() + group.getCustomerNum().intValue();
        }

        this.filterCustInfo(notEmptyList, custType);
        notEmptyList = notEmptyList.stream().distinct().collect(Collectors.toList());
        notEmptyList = notEmptyList.stream().peek(s -> {
            if (s.getRemark() != null && !s.getRemark().equals("")) {
                s.setRemark(s.getRemark().substring(1));
            }
        }).collect(Collectors.toList());
        notEmptyList = notEmptyList.stream().peek(s -> {
            if (s.getRemark() == null || s.getRemark().equals("")) {
                s.setPushStatus("1");
            }
        }).collect(Collectors.toList());
        if ("0".equalsIgnoreCase(importType)) {
            size = notEmptyList.size();
        } else if ("1".equalsIgnoreCase(importType)) {
            size = notEmptyList.size() + group.getCustomerNum().intValue();
        }
//        if (size == 0) {
//            throw new ServerException("当前导入模板中无符合条件的合规数据");
//        }
        //客群客户以1000个一组，批量导入
        List<List<SysGroupCustomer>> splitLists = splitList(notEmptyList, 1000);

        AtomicInteger count = new AtomicInteger(0);
        List<Integer> countList = new ArrayList<>();
        for (int i = 0; i < splitLists.size(); i++) {
            //4.10,因客户输入客户号，不需要补全前缀
//            List<SysGroupCustomer> updatedBatch = splitLists.get(i).stream()
//                    .map(customer -> {
//                        count.incrementAndGet();
//                        if ("2".equals(customer.getPushStatus())) {
//                            countList.add(count.get());
//                        }
//                        if (PERSONAL.getCode().equals(custType)) {
//                            customer.setCustId("101" + customer.getCustIdc());
//                        } else if (ENTERPRISE.getCode().equals(custType) || MERCHANT.getCode().equals(custType)) {
//                            customer.setCustId("202" + customer.getSocialCreditCode());
//                        }
//                        return customer;
//                    }).collect(Collectors.toList())

            sysGroupCustomerService.insertSysGroupCustomerBatch(splitLists.get(i));
        }
//        if (countList != null && countList.size() > 0)
//            warningStr = "第 " + countList.stream().map(String::valueOf).collect(Collectors.joining("、"))
//                    + " 条数据导入失败，缺少必要信息，数据库无地址且无联系方式！";
        if ("0".equalsIgnoreCase(importType)) {
            //根据客群Id,用户名批量修改对应的客户归属机构id与用户id
//            sysGroupCustomerService.updateOutletsIdAndUserIdByUsername(group.getGroupId());
            group.setCustomerNum((long) size);
            sysGroupMapper.insertSysGroup(group);
        } else if ("1".equalsIgnoreCase(importType)) {        //向已有客群插入客户时更新数据
            group.setCustomerNum((long) size);
            sysGroupMapper.updateSysGroupByIdc(group);
        }

//        if (error.length() > 2) {
//            throw new ServerException("导入客群创建成功,但" + error + "数据缺乏必填项,未导入成功,其余数据已导入");
//        }
        CustIncrementVo vo = new CustIncrementVo();
        vo.setNotEmptyList(notEmptyList);
        vo.setWarningStr(warningStr);
        //地址导入锚点库
        List<NewAnchor> anchorList = new ArrayList<>();
        notEmptyList.stream().forEach(item->{
            if (item.getDetailAddress()!=null && !item.getDetailAddress().equals("") && !item.getPushStatus().equals("2")) {
                NewAnchor anchor = new NewAnchor();
                anchor.setAddress(item.getDetailAddress());
                anchor.setAnchorName(item.getCustName());
                anchor.setBelongBusiness(item.getIndustry());
                anchor.setLegalId(item.getCustId().substring(3));
                if (MERCHANT.getCode().equals(custType)) {
                    anchor.setCustType(custType);
                    anchor.setCustIdType("营业执照");
                    anchor.setAddressName("经营地址");
                } else if (ENTERPRISE.getCode().equals(custType)) {
                    anchor.setCustType(custType);
                    anchor.setCustIdType("营业执照");
                    anchor.setAddressName("经营地址");
                } else if (PERSONAL.getCode().equals(custType)) {
                    anchor.setCustType(custType);
                    anchor.setCustIdType("二代身份证");
                    anchor.setAddressName("联系地址");
                }
                anchorList.add(anchor);
            }
        });
        if (anchorList.size()>0){
            anchorService.insertNewAnchor(anchorList);
        }
        return vo;

    }

    public void filterCustInfo(List<SysGroupCustomer> notEmptyList, String custType) {
        //撞库匹配
        List<SysGroupCustomer> resultList = new ArrayList<>();
        if (PERSONAL.getCode().equals(custType)) {
            List<String> idcConditionList = notEmptyList.stream().filter(p -> p.getCustIdc() != null && !p.getCustIdc().isEmpty())
                    .map(p -> p.getCustIdc()).distinct().collect(Collectors.toList());
            if (idcConditionList != null && idcConditionList.size() > 0) {
                List<String> custIdcList = custInfoRetailService.selectCustInfoRetailBycustIdcList(idcConditionList);

                notEmptyList.stream()
                        .filter(sysGroupCustomer -> custIdcList.contains(sysGroupCustomer.getCustIdc()))
                        .forEach(sysGroupCustomer -> sysGroupCustomer.setCustLb("0"));
                notEmptyList.stream()
                        .filter(sysGroupCustomer -> !custIdcList.contains(sysGroupCustomer.getCustIdc()))
                        .forEach(sysGroupCustomer -> sysGroupCustomer.setCustLb("1"));

                if (custIdcList != null && custIdcList.size() > 0) {
                    logger.info("查找到{}条证件号码相同数据", custIdcList.size());
                }
                resultList = notEmptyList.stream().filter(p -> !custIdcList.contains(p.getCustIdc())).collect(Collectors.toList());

            } else {
                resultList = notEmptyList;
                notEmptyList.stream().forEach(customer -> customer.setCustLb("1"));
                logger.info("开始执行数据入库处理==>");
            }
            if (resultList != null && resultList.size() > 0) {
                List<SysGroupCustomer> filteredList = resultList.stream()       //过滤掉电话号码为空的新客
                        .filter(customer -> customer.getCustPhone() != null && !customer.getCustPhone().isEmpty())
                        .collect(Collectors.toList());
                List<SysGroupCustomer> emptyPhoneList = resultList.stream()
                        .filter(item -> StringUtils.isBlank(item.getCustPhone()))
                        .collect(Collectors.toList());
                List<String> custIdcList = emptyPhoneList.stream()
                        .map(customer -> customer.getCustIdc())
                        .collect(Collectors.toList());
                notEmptyList.forEach(item -> {
                    if (custIdcList.contains(item.getCustIdc()) && !SecurityUtils.getHeadId().equals("932")) {
                        item.setPushStatus("2");
                        if (!item.getRemark().contains("新客联系方式为空")) {
                            item.setRemark(item.getRemark() + "、新客联系方式为空");
                        }
                    }
                });
                //新客户入库
                if (filteredList != null && filteredList.size() > 0) {
                    filteredList = filteredList.stream()
                            .map(customer -> {
                                SysGroupCustomer updatedCustomer = new SysGroupCustomer();
                                BeanUtils.copyProperties(customer, updatedCustomer);
                                updatedCustomer.setCustId("101" + updatedCustomer.getCustIdc());
                                return updatedCustomer;
                            }).collect(Collectors.toList());
                    int cnt = custInfoRetailService.insertCustomersToRetailByCustId(filteredList);
                    logger.info("insert new customer success! cnt={}", cnt);
                }
            }

        } else if (MERCHANT.getCode().equals(custType) || ENTERPRISE.getCode().equals(custType)) {
            List<String> idcConditionList = notEmptyList.stream().filter(p -> p.getSocialCreditCode() != null && !p.getSocialCreditCode().isEmpty())
                    .map(p -> p.getSocialCreditCode()).distinct().collect(Collectors.toList());
            if (idcConditionList != null && idcConditionList.size() > 0) {
                List<String> custIdcList = custInfoMerchantService.selectCustInfoByScCodeList(idcConditionList, custType);

                notEmptyList.stream()
                        .filter(sysGroupCustomer -> custIdcList.contains(sysGroupCustomer.getSocialCreditCode()))
                        .forEach(sysGroupCustomer -> sysGroupCustomer.setCustLb("0"));
                notEmptyList.stream()
                        .filter(sysGroupCustomer -> !custIdcList.contains(sysGroupCustomer.getSocialCreditCode()))
                        .forEach(sysGroupCustomer -> sysGroupCustomer.setCustLb("1"));

                if (custIdcList != null && custIdcList.size() > 0) {
                    logger.info("查找到{}条统信码相同数据", custIdcList.size());
                }
                resultList = notEmptyList.stream().filter(p -> !custIdcList.contains(p.getSocialCreditCode())).collect(Collectors.toList());

            } else {
                resultList = notEmptyList;
                notEmptyList.stream().forEach(customer -> customer.setCustLb("1"));
                logger.info("开始执行数据入库处理==>");
            }
            if (resultList != null && resultList.size() > 0) {
                List<SysGroupCustomer> filteredList = resultList.stream()       //过滤掉电话号码为空的新客
                        .filter(customer -> customer.getCustPhone() != null && !customer.getCustPhone().isEmpty())
                        .collect(Collectors.toList());
                List<SysGroupCustomer> emptyPhoneList = resultList.stream()
                        .filter(item -> StringUtils.isBlank(item.getCustPhone()))
                        .collect(Collectors.toList());
                List<String> custIdcList = emptyPhoneList.stream()
                        .map(customer -> customer.getCustId())
                        .collect(Collectors.toList());
                notEmptyList.forEach(item -> {
                    if (custIdcList.contains(item.getCustId()) && !SecurityUtils.getHeadId().equals("932")) {
                        item.setPushStatus("2");
                        if (!item.getRemark().contains("新客联系方式为空")) {
                            item.setRemark(item.getRemark() + "、新客联系方式为空");
                        }
                    }
                });


                //新客户入库
                if (filteredList != null && filteredList.size() > 0) {
                    filteredList = filteredList.stream()
                            .map(customer -> {
                                SysGroupCustomer updatedCustomer = new SysGroupCustomer();
                                BeanUtils.copyProperties(customer, updatedCustomer);
                                updatedCustomer.setCustId("202" + updatedCustomer.getSocialCreditCode());
                                return updatedCustomer;
                            }).collect(Collectors.toList());
                    int cnt = 0;
                    if (MERCHANT.getCode().equals(custType)) {
                        cnt = custInfoMerchantService.insertCustomersToMmerchantByScCode(filteredList);
                    } else if (ENTERPRISE.getCode().equals(custType)) {
                        cnt = custInfoBusinessService.insertCustomersToBusinessByScCode(filteredList);
                    }
                    logger.info("insert new customer success! cnt={}", cnt);
                }
            }
        }
    }

    public List<SysGroupCustomer> filterAddressAndPhone(List<SysGroupCustomer> sysGroupCustomers, String custType) {
//        String custType = null;
//        if (sysGroupCustomers.size() > 0) {
//            custType = sysGroupCustomers.get(0).getCustType();
//        }
        List<SysGroupCustomer> nullIdcList = new ArrayList<>();
        //吧证件号和类型出错的筛选出来，避免后续空指针异常
        if (custType.equals(PERSONAL.getCode())) {
            nullIdcList = sysGroupCustomers.stream().filter(s -> (s.getCustIdc() == null || s.getCustIdc().equals(""))).collect(Collectors.toList());
        } else {
            nullIdcList = sysGroupCustomers.stream().filter(s -> (s.getSocialCreditCode() == null || s.getSocialCreditCode().equals(""))).collect(Collectors.toList());
        }
        sysGroupCustomers.remove(nullIdcList);
        //筛选出模板中有电话的，可以直接推送
        List<SysGroupCustomer> directDistributeLists = sysGroupCustomers.stream().filter(s -> StringUtils.isNotBlank(s.getCustPhone())).
                collect(Collectors.toList());
        directDistributeLists.forEach(customer -> {
            if (customer.getPushStatus() != null && !customer.getPushStatus().equals("2")) {
                customer.setPushStatus("1");
            }
        });
        sysGroupCustomers.removeAll(directDistributeLists);
        List<String> custIds = new ArrayList<>();
        if (custType.equals(PERSONAL.getCode())) {
            custIds = sysGroupCustomers.stream().map(s -> {
                return s.getCustIdc();
            }).collect(Collectors.toList());             //根据证件号筛选
        } else if (custType.equals(MERCHANT.getCode()) || custType.equals(ENTERPRISE.getCode())) {
            custIds = sysGroupCustomers.stream().map(s -> {
                return s.getSocialCreditCode();
            }).collect(Collectors.toList());   //根据统信码筛选
        }
        //根据证件号或统信码与客户类型去对应客户表查询是否存在客户地址与客户电话，若都不存在则去除
        if (custIds.size() > 0 && !SecurityUtils.getDeptId().equals("932")) {
            List<AddressAndPhone> addressAndPhones = sysCampaignMapper.selectAddressAndPhoneByCustTypeAndCustIds(custType, custIds);
            if (custType.equals(PERSONAL.getCode())) {
                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.getCustIdc();
                }).collect(Collectors.toList());
                if (errorCustIds.size() > 0) {
                    List<SysGroupCustomer> sysGroupCustomersError = sysGroupCustomers.stream().filter(s -> errorCustIds.contains(s.getCustIdc())).collect(Collectors.toList());
                    sysGroupCustomersError.forEach(groupCustomer -> {
                        groupCustomer.setPushStatus("2");
                        groupCustomer.setRemark(groupCustomer.getRemark() + "、客户地址或联系方式为空");
                    });

                }
            } else if (custType.equals(MERCHANT.getCode()) || custType.equals(ENTERPRISE.getCode())) {
                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.getSocialCreditCode();
                }).collect(Collectors.toList());
                if (errorCustIds.size() > 0) {
                    List<SysGroupCustomer> sysGroupCustomersError = sysGroupCustomers.stream().filter(s -> errorCustIds.contains(s.getSocialCreditCode())).collect(Collectors.toList());
                    sysGroupCustomersError.forEach(groupCustomer -> {
                        groupCustomer.setPushStatus("2");
                        groupCustomer.setRemark(groupCustomer.getRemark() + "、客户地址或联系方式为空");
                    });
                }
            }
        }
        sysGroupCustomers.addAll(nullIdcList);
        sysGroupCustomers.addAll(directDistributeLists);
        //去除失败备注的第一个符号
//        sysGroupCustomers = sysGroupCustomers.stream().peek(s->{if (s.getRemark()!=null&&!s.getRemark().equals("")){ s.setRemark(s.getRemark().substring(1));}}).collect(Collectors.toList());
//        sysGroupCustomers = sysGroupCustomers.stream().peek(s->{if (s.getRemark()==null||s.getRemark().equals("")){ s.setPushStatus("1");}}).collect(Collectors.toList());
//        sysGroupCustomers = sysGroupCustomers.stream().distinct().collect(Collectors.toList());
        return sysGroupCustomers;
    }


    public List<SysGroupCustomer> getNotEmptyList(List<SysGroupCustomer> customersList, String operName, String uuid, String custType) {
        if (customersList != null) {
//            List<SysGroupCustomer> all = customersList;
//            customersList = customersList.stream()
////                    .filter(c -> c.getCustIdc() != null && !"".equals(c.getCustIdc()))
//                    .filter(c -> c.getCustName() != null && !"".equals(c.getCustName()))
//                    .collect(Collectors.toList());
//            if (MERCHANT.getCode().equals(custType) || ENTERPRISE.getCode().equals(custType)) {
//                customersList = customersList.stream()
////                        .filter(c -> c.getLpName() != null && !"".equals(c.getLpName()))
//                        .filter(c -> c.getSocialCreditCode() != null && !"".equals(c.getSocialCreditCode())).
////                        filter(c -> c.getSocialCreditCodeType() != null && !"".equals(c.getSocialCreditCodeType())).
//        collect(Collectors.toList());
//            }
            customersList = customersList.stream().peek(c -> c.setCreateBy(operName)).peek(c -> c.setCreateTime(new Date()))
                    .peek(c -> c.setGroupId(uuid)).peek(c -> c.setDelFlag("0")).peek(c -> c.setCustType(custType)).collect(Collectors.toList());
//            all.removeAll(customersList);
//            all = all.stream().peek(c -> c.setCreateBy(operName)).peek(c -> c.setCreateTime(new Date()))
//                    .peek(c -> c.setGroupId(uuid)).peek(c -> c.setPushStatus("2")).peek(c -> c.setRemark(c.getRemark() + "、客户号为空"))
//                    .peek(c -> c.setDelFlag("0")).peek(c -> c.setCustType(custType)).collect(Collectors.toList());
//            customersList.addAll(all);
        }
        return customersList;
    }

    public String getErrorList(List<SysGroupCustomer> customersList, String custType) {
        String error = "";
        if (customersList != null) {
            for (int i = 0; i < customersList.size(); i++) {
                SysGroupCustomer groupCustomer = customersList.get(i);
                if (isEmpty(groupCustomer, custType)) {
                    groupCustomer.setPushStatus("2");
                    error = error + (i + 1) + " 行,";
                    continue;
                }
            }
        }
        return error;
    }

    //判断某条客户数据是否为空或身份证号是否合法
    public boolean isEmpty(SysGroupCustomer groupCustomer, String custType) {
        boolean flag = true;
        flag = groupCustomer.getCustName() == null || "".equals(groupCustomer.getCustName());
//                ||groupCustomer.getCustIdc()==null||"".equals(groupCustomer.getCustIdc());
        if (MERCHANT.getCode().equals(custType) || ENTERPRISE.getCode().equals(custType)) {
            flag = flag || (groupCustomer.getSocialCreditCode() == null || "".equals(groupCustomer.getSocialCreditCode()));
//                    ||groupCustomer.getLpName()==null||"".equals(groupCustomer.getLpName())
//                    ||groupCustomer.getSocialCreditCodeType()==null||"".equals(groupCustomer.getSocialCreditCodeType()));
        }
        return flag;
    }


    /**
     * 修改客群圈选分群
     *
     * @param sysGroup 客群圈选分群
     * @return 结果
     */
    @Override
    public int updateSysGroup(SysGroup sysGroup) {
        sysGroup.setUpdateTime(DateUtils.getNowDate());
        return sysGroupMapper.updateSysGroup(sysGroup);
    }

    /**
     * 批量删除客群圈选分群
     *
     * @param ids 需要删除的客群圈选分群主键
     * @return 结果
     */
    @Override
    public int deleteSysGroupByIds(Long[] ids) {
        return sysGroupMapper.deleteSysGroupByIds(ids);
    }

    /**
     * 删除客群圈选分群信息
     *
     * @param id 客群圈选分群主键
     * @return 结果
     */
    @Override
    public int deleteSysGroupById(Long id) {
        return sysGroupMapper.deleteSysGroupById(id);
    }

    @Override
    public int selectByGroupName(String groupName) {
        return sysGroupMapper.selectCountByGroupName(groupName, SecurityUtils.getHeadId());
    }

    @Override
    public AjaxResult insertSysGroupAndCustomerBySelect(String groupName, String custType, List<CustomerSelect> customerSelects) {
        int size = 0;
        SysGroup group = new SysGroup();
        String uuid = UUID.randomUUID().toString();
        group.setGroupId(uuid);
        group.setCustType(custType);
        group.setGroupName(groupName);
        group.setCreateTime(DateUtils.getNowDate());
        //建群方式为锚点建群
        group.setCreateType("2");
        //先默认更新方式为手动更新
        group.setUpdateType("1");
        group.setStatus("运行中");
        group.setUpdateTime(DateUtils.getNowDate());
        group.setCreateBy(getUsername());
        group.setGroupType("1");
        group.setDeptId(getDeptId());
        group.setUserId(getUserId());
        String roleName = userRole();
        if ("head".equals(roleName) || "admin".equals(roleName)) {
            group.setCreateRole("0");
        } else if ("branch".equals(roleName)) {
            group.setCreateRole("1");
        }
        List<String> custIdcs = new ArrayList<>();
        List<String> socialCreditCodes = new ArrayList<>();
        if (customerSelects != null && customerSelects.size() > 0) {
            size = customerSelects.size();
            List<SysGroupCustomer> groupCustomers = new ArrayList<>();
            for (int i = 0; i < customerSelects.size(); i++) {
                SysGroupCustomer sysGroupCustomer = new SysGroupCustomer();
                sysGroupCustomer.setIdType("居民二代身份证");
                sysGroupCustomer.setGroupId(uuid);
                sysGroupCustomer.setCustName(customerSelects.get(i).getCustName());
                sysGroupCustomer.setCustType(custType);
                if (custType.equals(MERCHANT.getCode()) || custType.equals(ENTERPRISE.getCode())) {
                    String socialCreditCode = customerSelects.get(i).getSocialCreditCode();
                    sysGroupCustomer.setSocialCreditCode(socialCreditCode);
                    sysGroupCustomer.setSocialCreditCodeType("营业执照");
                    socialCreditCodes.add(socialCreditCode);
                } else if (custType.equals(PERSONAL.getCode())) {
                    sysGroupCustomer.setCustIdc(customerSelects.get(i).getCustIdc());
                }
                sysGroupCustomer.setPushStatus("1");    //导入成功标志
                sysGroupCustomer.setCustLb("0");        //是行内客户
                sysGroupCustomer.setCreateTime(DateUtils.getNowDate());
                if (sysGroupCustomer.getCustIdc() != null && !sysGroupCustomer.getCustIdc().isEmpty()) {
                    custIdcs.add(sysGroupCustomer.getCustIdc());
                }
                groupCustomers.add(sysGroupCustomer);

            }
            sysGroupCustomerService.insertSysGroupCustomerBatch(groupCustomers);
            if (custType.equals(PERSONAL.getCode()) && custIdcs.size() > 0) {
                sysGroupCustomerService.updateCustIdAndCustIsn(uuid, custType, custIdcs);
            }
            if (socialCreditCodes.size() > 0) {
                sysGroupCustomerService.updateCustIdAndCustIsnBySocialCreditCode(uuid, custType, socialCreditCodes);
            }
        }
        group.setCustomerNum((long) size);
        sysGroupMapper.insertSysGroup(group);
        return success("锚点分群创建成功");
    }

    @Override
    @Transactional
    @Async("excelImportExecutor")
    public void insertSysGroupAndCustomerAsync(MultipartFile file, String groupName, String custType, String groupId, String importType) throws IOException {
        //客群初始化
        SysGroup group = new SysGroup();
        if (selectSysGroupByGroupId(groupId) == null){
            group.setGroupId(groupId);
            group.setCustType(custType);
            group.setGroupName(groupName);
            group.setCreateTime(DateUtils.getNowDate());
            group.setCreateType("0");
            //先默认更新方式为手动更新
            group.setUpdateType("1");
            group.setStatus("运行中");
            group.setUpdateTime(DateUtils.getNowDate());
            group.setCreateBy(getUsername());
            group.setGroupType("1");
            group.setDeptId(getDeptId());
            group.setUserId(getUserId());
            String roleName = userRole();
            if (ROLE_HEAD.equals(roleName)) {
                group.setCreateRole("0");
            } else if (ROLE_BRANCH.equals(roleName)) {
                group.setCreateRole("1");
            } else if (ROLE_HeadPublic.equals(roleName)) {
                group.setCreateRole("2");
            } else if (ROLE_HeadPrivate.equals(roleName)) {
                group.setCreateRole("3");
            } else if (ROLE_HeadOps.equals(roleName)) {
                group.setCreateRole("4");
            }
        }else {
            group = selectSysGroupByGroupId(groupId);
            group.setUpdateTime(DateUtils.getNowDate());
            group.setUpdateBy(getUsername());
        }
        //读取文件
        InputStream inputStream = new ByteArrayInputStream(file.getBytes());
        List<SysGroupCustomer> customersList = EasyExcel.read(inputStream).head(SysGroupCustomer.class).sheet().doReadSync();
        //校验
        int size = 0;
        String operName = getUsername();
        if (PERSONAL.getCode().equals(custType)) {
            for (SysGroupCustomer customer : customersList) {
                //客户经理导入将推送客户经理设置为自己
                if (userRole().equals("manager")){
                    customer.setTellerId(SecurityUtils.getUsername());
                }
                //todo 补充支行和网点id，判断该客户是否导入成功
                if (customer.getRemark() == null)
                    customer.setRemark("");
                if (customer.getCustType() != null) {
                    //校验输入是否是个人、客户号开头是否是101
                    if (!customer.getCustType().equals("个人"))
                        customer.setRemark(customer.getRemark() + "、填写客户类型与选择不一致");
                    customer.setPushStatus("2");
                }
                if (customer.getDeptId() != null) {
                    //查询机构号是什么类型，是网点就补充父节点支行，是支行则补充名字。若未查询到，则推送状态变为失败
                    SysDept dept = deptMapper.selectDeptById(customer.getDeptId());
                    if (dept != null && dept.getDeptType().equals("outlet")) {
                        customer.setOutletsId(customer.getDeptId());
                        customer.setOutlets(dept.getDeptName());
                        customer.setDeptId(dept.getParentId());
                        customer.setDeptName(deptMapper.selectDeptById(dept.getParentId()).getDeptName());
                    } else if (dept == null) {
                        //未查到
                        customer.setRemark(customer.getRemark() + "、推送机构号不存在");
                        customer.setPushStatus("2");
                    } else if (dept.getDeptType().equals("branch")) {
                        customer.setDeptName(dept.getDeptName());
                    }
                }
                if (customer.getCustId() == null || customer.getCustId().length() != 21) {
                    customer.setRemark(customer.getRemark() + "、客户号不正确");
                    customer.setPushStatus("2");
                } else if (!customer.getCustId().substring(0, 3).equals("101")) {
                    customer.setRemark(customer.getRemark() + "、客户号前缀与所选类型不匹配");
                    customer.setPushStatus("2");
                } else {
                    customer.setCustIdc(customer.getCustId().substring(3));
                    //验证客户姓名
                    CustInfoRetail retail = custInfoRetailService.selectCustInfoRetailByCustId(customer.getCustId());
                    if (customer.getCustName()==null||customer.getCustName().equals("")){
                        if (retail==null||retail.getCustName()==null||retail.getCustName().equals("")){
                            customer.setRemark(customer.getRemark() + "、新客必须录入客户名称");
                            customer.setPushStatus("2");
                        }else{
                            customer.setCustName(retail.getCustName());
                        }
                    }
                }
                if (StringUtils.isBlank(customer.getIdType())) {
                    customer.setIdType("居民二代身份证");
                }
                //去除客户号等数据前后空格
                if (StringUtils.isNotEmpty(customer.getCustId())) {
                    customer.setCustId(customer.getCustId().trim());
                }
                if (StringUtils.isNotEmpty(customer.getCustIdc())) {
                    customer.setCustIdc(customer.getCustIdc().trim());
                }
                if (StringUtils.isNotEmpty(customer.getSocialCreditCode())) {
                    customer.setSocialCreditCode(customer.getSocialCreditCode().trim());
                }
                if (StringUtils.isNotEmpty(customer.getTellerId())) {
                    SysUser user = userMapper.selectUserByUserName(customer.getTellerId());
                    if (user == null) {
                        customer.setPushStatus("2");
                        customer.setRemark(customer.getRemark() + "、推送柜员号不存在");
                    } else {
                        SysDept userDept = deptMapper.selectDeptById(user.getDeptId());
                        if ((userDept != null && userDept.getDeptType().equals("branch")) || (userDept != null && userDept.getDeptType().equals("head"))) {
                            if (customer.getDeptId() != null && !userDept.getDeptId().equals(customer.getDeptId())) {
                                customer.setPushStatus("2");
                                customer.setRemark(customer.getRemark() + "、填写支行或网点号与客户经理不匹配");
                            } else {
                                customer.setDeptId(userDept.getDeptId());
                                customer.setDeptName(userDept.getDeptName());
                            }
                        } else {
                            if (userDept != null && userDept.getDeptType().equals("outlet")) {
                                SysDept dept = deptMapper.selectDeptById(userDept.getParentId());
                                if (customer.getDeptId() != null && !dept.getDeptId().equals(customer.getDeptId())) {
                                    customer.setPushStatus("2");
                                    customer.setRemark(customer.getRemark() + "、填写支行或网点号与客户经理不匹配");
                                } else {
                                    customer.setOutletsId(userDept.getDeptId());
                                    customer.setOutlets(userDept.getDeptName());
                                    customer.setDeptId(dept.getDeptId());
                                    customer.setDeptName(dept.getDeptName());
                                }
                            }
                        }
                    }
                }
            }
            boolean anyHaveSocialCreditCode = customersList.stream()
                    .anyMatch(business -> business.getCustIdc() != null && !business.getCustIdc().isEmpty());
            if (!anyHaveSocialCreditCode) {
                throw new ServerException("导入失败，请检查模板以及数据准确性");
            }
        }
        //商户或企业客群因导入模板不同，需要转换对象后插入客群表
        else if (MERCHANT.getCode().equals(custType)) {
            for (SysGroupCustomer customer : customersList) {
                //客户经理导入将推送客户经理设置为自己
                if (userRole().equals("manager")){
                    customer.setTellerId(SecurityUtils.getUsername());
                }
                //todo 补充支行和网点id，判断该客户是否导入成功
                if (customer.getRemark() == null)
                    customer.setRemark("");
                if (customer.getCustType() != null) {
                    //校验输入是否是个人、客户号开头是否是101
                    if (!customer.getCustType().equals("商户"))
                        customer.setRemark(customer.getRemark() + "、填写客户类型与选择不一致");
                    customer.setPushStatus("2");
                }
                if (customer.getDeptId() != null) {
                    SysDept dept = deptMapper.selectDeptById(customer.getDeptId());
                    if (dept != null && dept.getDeptType().equals("outlet")) {
                        customer.setOutletsId(customer.getDeptId());
                        customer.setOutlets(dept.getDeptName());
                        customer.setDeptId(dept.getParentId());
                        customer.setDeptName(deptMapper.selectDeptById(dept.getParentId()).getDeptName());
                    } else if (dept == null) {
                        customer.setRemark(customer.getRemark() + "、推送机构号不存在");
                        customer.setPushStatus("2");
                    } else if (dept.getDeptType().equals("branch")) {
                        customer.setDeptName(dept.getDeptName());
                    }
                }
                //填充证件号
                if (customer.getCustId() == null || customer.getCustId().length() != 21) {
                    customer.setRemark(customer.getRemark() + "、客户号不正确");
                    customer.setPushStatus("2");
                } else if (!customer.getCustId().substring(0, 3).equals("202")) {
                    customer.setRemark(customer.getRemark() + "、客户号前缀与所选类型不匹配");
                    customer.setPushStatus("2");
                } else {
                    customer.setSocialCreditCode(customer.getCustId().substring(3));
                    customer.setSocialCreditCode(customer.getSocialCreditCode().toUpperCase());
                    CustInfoMerchant merchant = custInfoMerchantService.selectCustInfoMerchantByCustId(customer.getCustId());
                    if (customer.getCustName()==null||customer.getCustName().equals("")){
                        if (merchant==null||merchant.getCustName()==null||merchant.getCustName().equals("")){
                            customer.setRemark(customer.getRemark() + "、新客必须录入客户名称");
                            customer.setPushStatus("2");
                        }else{
                            customer.setCustName(merchant.getCustName());
                        }
                    }
                }
                if (StringUtils.isBlank(customer.getIdType())) {
                    customer.setIdType("居民二代身份证");
                }
                if (StringUtils.isBlank(customer.getSocialCreditCodeType())) {
                    customer.setSocialCreditCodeType("营业执照");
                }
                //去除客户号等数据前后空格
                if (StringUtils.isNotEmpty(customer.getCustId())) {
                    customer.setCustId(customer.getCustId().trim());
                }
                if (StringUtils.isNotEmpty(customer.getCustIdc())) {
                    customer.setCustIdc(customer.getCustIdc().trim());
                }
                if (StringUtils.isNotEmpty(customer.getSocialCreditCode())) {
                    customer.setSocialCreditCode(customer.getSocialCreditCode().trim());
                }
                if (StringUtils.isNotEmpty(customer.getTellerId())) {
                    SysUser user = userMapper.selectUserByUserName(customer.getTellerId());
                    if (user == null) {
                        customer.setPushStatus("2");
                        customer.setRemark(customer.getRemark() + "、推送柜员号不存在");
                    } else {
                        SysDept userDept = deptMapper.selectDeptById(user.getDeptId());
                        if ((userDept != null && userDept.getDeptType().equals("branch")) || (userDept != null && userDept.getDeptType().equals("head"))) {
                            if (customer.getDeptId() != null && !userDept.getDeptId().equals(customer.getDeptId())) {
                                customer.setPushStatus("2");
                                customer.setRemark(customer.getRemark() + "、填写支行或网点号与客户经理不匹配");
                            } else {
                                customer.setDeptId(userDept.getDeptId());
                                customer.setDeptName(userDept.getDeptName());
                            }
                        } else {
                            if (userDept != null && userDept.getDeptType().equals("outlet")) {
                                SysDept dept = deptMapper.selectDeptById(userDept.getParentId());
                                if (customer.getDeptId() != null && !dept.getDeptId().equals(customer.getDeptId())) {
                                    customer.setPushStatus("2");
                                    customer.setRemark(customer.getRemark() + "、填写支行或网点号与客户经理不匹配");
                                } else {
                                    customer.setOutletsId(userDept.getDeptId());
                                    customer.setOutlets(userDept.getDeptName());
                                    customer.setDeptId(dept.getDeptId());
                                    customer.setDeptName(dept.getDeptName());
                                }
                            }
                        }
                    }
                }
            }
            boolean anyHaveSocialCreditCode = customersList.stream()
                    .anyMatch(business -> business.getSocialCreditCode() != null && !business.getSocialCreditCode().isEmpty());
            if (!anyHaveSocialCreditCode) {
                throw new ServerException("导入失败，请检查模板以及数据准确性");
            }
        } else if (ENTERPRISE.getCode().equals(custType)) {
            for (SysGroupCustomer customer : customersList) {
                //客户经理导入将推送客户经理设置为自己
                if (userRole().equals("manager")){
                    customer.setTellerId(SecurityUtils.getUsername());
                }
                //todo 补充支行和网点id，判断该客户是否导入成功
                if (customer.getRemark() == null)
                    customer.setRemark("");
                if (customer.getCustType() != null) {
                    //校验输入是否是个人、客户号开头是否是202
                    if (!customer.getCustType().equals("企业"))
                        customer.setRemark(customer.getRemark() + "、填写客户类型与选择不一致");
                    customer.setPushStatus("2");
                }
                if (customer.getDeptId() != null) {
                    SysDept dept = deptMapper.selectDeptById(customer.getDeptId());
                    if (dept != null && dept.getDeptType().equals("outlet")) {
                        customer.setOutletsId(customer.getDeptId());
                        customer.setOutlets(dept.getDeptName());
                        customer.setDeptId(dept.getParentId());
                        customer.setDeptName(deptMapper.selectDeptById(dept.getParentId()).getDeptName());
                    } else if (dept == null) {
                        customer.setRemark(customer.getRemark() + "、推送机构号不存在");
                        customer.setPushStatus("2");
                    } else if (dept.getDeptType().equals("branch")) {
                        customer.setDeptName(dept.getDeptName());
                    }
                }
                //填充证件号
                if (customer.getCustId() == null || customer.getCustId().length() != 21) {
                    customer.setRemark(customer.getRemark() + "、客户号不正确");
                    customer.setPushStatus("2");
                } else if (!customer.getCustId().substring(0, 3).equals("202")) {
                    customer.setRemark(customer.getRemark() + "、客户号前缀与所选类型不匹配");
                    customer.setPushStatus("2");
                } else {
                    customer.setSocialCreditCode(customer.getCustId().substring(3));
                    customer.setSocialCreditCode(customer.getSocialCreditCode().toUpperCase());
                    CustInfoBusiness business = custInfoBusinessService.selectCustInfoBusinessByCustId(customer.getCustId());
                    if (customer.getCustName()==null||customer.getCustName().equals("")){
                        if (business==null||business.getCustName()==null||business.getCustName().equals("")){
                            customer.setRemark(customer.getRemark() + "、新客必须录入客户名称");
                            customer.setPushStatus("2");
                        }else{
                            customer.setCustName(business.getCustName());
                        }
                    }
                }
                if (StringUtils.isBlank(customer.getIdType())) {
                    customer.setIdType("居民二代身份证");
                }
                if (StringUtils.isBlank(customer.getSocialCreditCodeType())) {
                    customer.setSocialCreditCodeType("营业执照");
                }
                //去除客户号等数据前后空格
                if (StringUtils.isNotEmpty(customer.getCustId())) {
                    customer.setCustId(customer.getCustId().trim());
                }
                if (StringUtils.isNotEmpty(customer.getCustIdc())) {
                    customer.setCustIdc(customer.getCustIdc().trim());
                }
                if (StringUtils.isNotEmpty(customer.getSocialCreditCode())) {
                    customer.setSocialCreditCode(customer.getSocialCreditCode().trim());
                }
                if (StringUtils.isNotEmpty(customer.getTellerId())) {
                    SysUser user = userMapper.selectUserByUserName(customer.getTellerId());
                    if (user == null) {
                        customer.setPushStatus("2");
                        customer.setRemark(customer.getRemark() + "、推送柜员号不存在");
                    } else {
                        SysDept userDept = deptMapper.selectDeptById(user.getDeptId());
                        if ((userDept != null && userDept.getDeptType().equals("branch")) || (userDept != null && userDept.getDeptType().equals("head"))) {
                            if (customer.getDeptId() != null && !userDept.getDeptId().equals(customer.getDeptId())) {
                                customer.setPushStatus("2");
                                customer.setRemark(customer.getRemark() + "、填写支行或网点号与客户经理不匹配");
                            } else {
                                customer.setDeptId(userDept.getDeptId());
                                customer.setDeptName(userDept.getDeptName());
                            }
                        } else {
                            if (userDept != null && userDept.getDeptType().equals("outlet")) {
                                SysDept dept = deptMapper.selectDeptById(userDept.getParentId());
                                if (customer.getDeptId() != null && !dept.getDeptId().equals(customer.getDeptId())) {
                                    customer.setPushStatus("2");
                                    customer.setRemark(customer.getRemark() + "、填写支行或网点号与客户经理不匹配");
                                } else {
                                    customer.setOutletsId(userDept.getDeptId());
                                    customer.setOutlets(userDept.getDeptName());
                                    customer.setDeptId(dept.getDeptId());
                                    customer.setDeptName(dept.getDeptName());
                                }
                            }
                        }
                    }
                }
            }
            boolean anyHaveSocialCreditCode = customersList.stream()
                    .anyMatch(business -> business.getSocialCreditCode() != null && !business.getSocialCreditCode().isEmpty());
            if (!anyHaveSocialCreditCode) {
                throw new ServerException("导入失败，请检查模板以及数据准确性");
            }
        }
        //筛选出必填项不为空的数据
        List<SysGroupCustomer> notEmptyList = getNotEmptyList(customersList, operName, group.getGroupId(), custType);

        if (notEmptyList != null && notEmptyList.size() > 0) {
            long distinctCustNameCount = notEmptyList.stream().map(SysGroupCustomer::getCustName).distinct().count();
            long distinctIdCount = notEmptyList.stream().map(SysGroupCustomer::getCustId).distinct().count();
            if (distinctIdCount < distinctCustNameCount) {
                throw new ServerException("导入失败，请检查模板以及数据准确性");
            }
        }
        //首次导入，有重复数据时导入失败
        if ("0".equalsIgnoreCase(importType)) {
            // 使用一个集合来记录重复的 custId
            Set<String> duplicateCustIds = notEmptyList.stream()
                    .collect(Collectors.groupingBy(SysGroupCustomer::getCustId, Collectors.counting()))
                    .entrySet().stream().filter(entry -> entry.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toSet());
            if (!duplicateCustIds.isEmpty()) {
                String warningStr = "客户号：" + String.join(", ", duplicateCustIds) + " 重复";
                throw new ServerException("导入失败，" + warningStr);
            }
        }
        notEmptyList = filterAddressAndPhone(notEmptyList, custType);
        String warningStr = "";
        if ("1".equalsIgnoreCase(importType)) {
            List<String> conditionList;
            conditionList = notEmptyList.stream().map(p -> p.getCustId()).distinct().collect(Collectors.toList());
            List<SysGroupCustomer> custIdcList = sysGroupCustomerMapper.selectCustIdcList(conditionList, custType, groupId);//重复数据集合
            if (custIdcList != null && custIdcList.size() > 0) {
                for (SysGroupCustomer customer : custIdcList) {
                    if ("1".equalsIgnoreCase(customer.getPushStatus())) {
                        notEmptyList = notEmptyList.stream().filter(p -> !p.getCustId().equals(customer.getCustId())).collect(Collectors.toList());
                    } else if ("2".equalsIgnoreCase(customer.getPushStatus())) {
                        sysGroupCustomerMapper.deleteSysGroupCustomerByCustId(customer.getGroupId(),customer.getCustId());
                    }
                }
                notEmptyList = notEmptyList.stream().filter(p -> !custIdcList.contains(p.getCustId())).collect(Collectors.toList());
                List<String> custIdList = custIdcList.stream().map(custIdc -> custIdc.getCustId()).collect(Collectors.toList());
                if (custIdList != null && custIdList.size() > 0){
                    warningStr = "客户号：" + String.join(", ", custIdList) + " 已存在";
                }
            }
            size = notEmptyList.size() + group.getCustomerNum().intValue();
        }
        this.filterCustInfo(notEmptyList, custType);
        notEmptyList = notEmptyList.stream().distinct().collect(Collectors.toList());
        notEmptyList = notEmptyList.stream().peek(s -> {
            if (s.getRemark() != null && !s.getRemark().equals("")) {
                s.setRemark(s.getRemark().substring(1));
            }
        }).collect(Collectors.toList());
        notEmptyList = notEmptyList.stream().peek(s -> {
            if (s.getRemark() == null || s.getRemark().equals("")) {
                s.setPushStatus("1");
            }
        }).collect(Collectors.toList());
        if ("0".equalsIgnoreCase(importType)) {
            size = notEmptyList.size();
        } else if ("1".equalsIgnoreCase(importType)) {
            size = notEmptyList.size() + group.getCustomerNum().intValue();
        }

        //批量插入数据
        List<List<SysGroupCustomer>> splitLists = splitList(notEmptyList, 1000);

        for (int i = 0; i < splitLists.size(); i++) {
            sysGroupCustomerService.insertSysGroupCustomerBatch(splitLists.get(i));
        }

        if ("0".equalsIgnoreCase(importType)) {
            group.setCustomerNum((long) size);
            sysGroupMapper.insertSysGroup(group);
        } else if ("1".equalsIgnoreCase(importType)) {        //向已有客群插入客户时更新数据
            group.setCustomerNum((long) size);
            sysGroupMapper.updateSysGroupByIdc(group);
        }

        //地址导入锚点库
        List<NewAnchor> anchorList = new ArrayList<>();
        notEmptyList.stream().forEach(item->{
            if (item.getDetailAddress()!=null && !item.getDetailAddress().equals("") && !item.getPushStatus().equals("2")) {
                NewAnchor anchor = new NewAnchor();
                anchor.setAddress(item.getDetailAddress());
                anchor.setAnchorName(item.getCustName());
                anchor.setBelongBusiness(item.getIndustry());
                anchor.setLegalId(item.getCustId().substring(3));
                if (MERCHANT.getCode().equals(custType)) {
                    anchor.setCustType(custType);
                    anchor.setCustIdType("营业执照");
                    anchor.setAddressName("经营地址");
                } else if (ENTERPRISE.getCode().equals(custType)) {
                    anchor.setCustType(custType);
                    anchor.setCustIdType("营业执照");
                    anchor.setAddressName("经营地址");
                } else if (PERSONAL.getCode().equals(custType)) {
                    anchor.setCustType(custType);
                    anchor.setCustIdType("二代身份证");
                    anchor.setAddressName("联系地址");
                }
                anchorList.add(anchor);
            }
        });
        if (anchorList.size()>0){
            anchorService.insertNewAnchor(anchorList);
        }
    }
}
