package com.hzs.member.empty.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.constant.SysConstants;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
import com.hzs.common.core.constant.msg.DocumentMsgConstants;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.base.BaseException;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.member.account.CuMemberAccount;
import com.hzs.common.domain.member.account.CuMemberTrade;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.base.CuMemberRegister;
import com.hzs.common.domain.member.empty.*;
import com.hzs.common.domain.member.empty.ext.CuMemberEmptyDetailExt;
import com.hzs.common.domain.member.empty.ext.CuMemberEmptyProductDTO;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.domain.sale.order.SaOrderItems;
import com.hzs.common.domain.system.base.BdStorehouse;
import com.hzs.common.domain.system.config.BdAccount;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.member.account.service.ICuMemberAccountService;
import com.hzs.member.account.service.ICuMemberTradeService;
import com.hzs.member.base.service.ICuMemberRegisterService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.empty.dto.EmptyMemberDTO;
import com.hzs.member.empty.dto.EmptyMemberDetailDTO;
import com.hzs.member.empty.dto.MemberEmptyDetailDTO;
import com.hzs.member.empty.dto.MemberEmptyProductDTO;
import com.hzs.member.empty.param.MemberEmptySignParam;
import com.hzs.member.empty.service.*;
import com.hzs.sale.order.ISaOrderServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.ISystemConfigServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IAccountServiceApi;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import com.hzs.system.sys.IApprovalServiceApi;
import com.hzs.system.sys.dto.ApprovalBusinessResultDTO;
import com.hzs.system.sys.dto.ApprovalSubmitDTO;
import com.hzs.system.sys.dto.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 空单处理服务
 * @Author: jiang chao
 * @Time: 2023/6/17 14:07
 * @Classname: MemberEmptyServiceImpl
 * @PackageName: com.hzs.member.empty.service.impl
 */
@Slf4j
@Service
public class MemberEmptyServiceImpl implements IMemberEmptyService {

    @Autowired
    private ICuMemberEmptyService iCuMemberEmptyService;
    @Autowired
    private ICuMemberEmptyDetailService iCuMemberEmptyDetailService;
    @Autowired
    private ICuMemberEmptyCodeService iCuMemberEmptyCodeService;
    @Autowired
    private ICuMemberEmptyProductService iCuMemberEmptyProductService;
    @Autowired
    private ICuMemberEmptyLogService iCuMemberEmptyLogService;
    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private ICuMemberAccountService iCuMemberAccountService;
    @Autowired
    private ICuMemberTradeService iCuMemberTradeService;
    @Autowired
    private ICuMemberRegisterService iCuMemberRegisterService;

    @DubboReference
    private ISystemConfigServiceApi systemConfigServiceApi;
    @DubboReference
    private ICurrencyServiceApi iCurrencyServiceApi;
    @DubboReference
    private IAccountServiceApi iAccountServiceApi;
    @DubboReference
    private ISaOrderServiceApi iSaOrderServiceApi;
    @DubboReference
    private IApprovalServiceApi iApprovalServiceApi;
    @DubboReference
    private IGradeServiceApi iGradeServiceApi;

    @Autowired
    private RedisService redisService;

    @Override
    public void importTemplate(List<MemberEmptyDetailDTO> resultList, List<String> checkMemberList) {
        // 会员编号列表（导入会员编号去重）
        if (null == checkMemberList) {
            checkMemberList = new ArrayList<>();
        }

        // 遍历导入数据，提取各种校验所需要的数据
        for (MemberEmptyDetailDTO detail : resultList) {
            this.checkBase(detail, checkMemberList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<CuMemberEmptyDetailExt> saveDate(List<MemberEmptyDetailDTO> resultList, Long userId, Integer pkCountry) {
        // 入库空单数据
        CuMemberEmpty cuMemberEmpty = new CuMemberEmpty();
        // 入库空单明细数据
        List<CuMemberEmptyDetail> detailList = new ArrayList<>();

        // 新数据，需要添加主表数据
        MemberEmptyDetailDTO tmpDetail = resultList.get(0);
        if (null == tmpDetail.getPkMemberEmpty()) {
            // 新数据，需要添加主表数据
            cuMemberEmpty.setBusinessCode(iCuMemberEmptyService.queryLastCode());
            if (StringUtils.isNotEmpty(tmpDetail.getRemark())) {
                cuMemberEmpty.setRemark(tmpDetail.getRemark());
            }
            cuMemberEmpty.setPkCreator(userId);
            cuMemberEmpty.setCreationTime(new Date());
            cuMemberEmpty.setPkModified(cuMemberEmpty.getPkCreator());
            cuMemberEmpty.setModifiedTime(cuMemberEmpty.getCreationTime());
            cuMemberEmpty.setPkCountry(pkCountry);
        } else {
            cuMemberEmpty.setPkId(tmpDetail.getPkMemberEmpty());
            if (StringUtils.isNotEmpty(tmpDetail.getRemark())) {
                cuMemberEmpty.setRemark(tmpDetail.getRemark());
            }
            cuMemberEmpty.setPkModified(userId);
            cuMemberEmpty.setModifiedTime(new Date());
        }
        // 添加或修改空单批次
        if (iCuMemberEmptyService.saveOrUpdate(cuMemberEmpty)) {
            // 明细SEQ列表
            List<Long> detailSeqList = iCuMemberEmptyDetailService.querySeqList(resultList.size());

            for (int i = 0; i < resultList.size(); i++) {
                MemberEmptyDetailDTO detailDTO = resultList.get(i);

                detailDTO.setPkId(detailSeqList.get(i));
                detailDTO.setPkMemberEmpty(cuMemberEmpty.getPkId());
                CuMemberEmptyDetail detail = BeanUtil.copyProperties(detailDTO, CuMemberEmptyDetail.class);
                detailList.add(detail);
            }
            // 添加或修改空单批次数据
            iCuMemberEmptyDetailService.insertBatch(detailList, userId);

            // 更新空单会员编码表
            UpdateWrapper<CuMemberEmptyCode> emptyCodeUpdateWrapper = new UpdateWrapper<>();
            emptyCodeUpdateWrapper.in("MEMBER_CODE", detailList.stream().map(CuMemberEmptyDetail::getMemberCode).collect(Collectors.toList()));
            emptyCodeUpdateWrapper.eq(SystemFieldConstants.DEL_FLAG, EDelFlag.UN_DELETE.getValue());
            emptyCodeUpdateWrapper.eq("IS_USED", EYesNo.NO.getIntValue());
            emptyCodeUpdateWrapper.set("IS_USED", EYesNo.YES.getIntValue());
            emptyCodeUpdateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
            emptyCodeUpdateWrapper.set(SystemFieldConstants.MODIFIED_TIME, new Date());
            iCuMemberEmptyCodeService.update(emptyCodeUpdateWrapper);

            return iCuMemberEmptyDetailService.queryEmptyDetail(detailSeqList);
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateDate(List<MemberEmptyDetailDTO> resultList, Long userId, Integer pkCountry) {
        // 空单数据
        CuMemberEmpty memberEmpty = new CuMemberEmpty();
        // 空单明细数据
        List<CuMemberEmptyDetail> detailList = new ArrayList<>();
        // 空单明细产品数据
        List<CuMemberEmptyProduct> productList = new ArrayList<>();

        // 空单数据
        MemberEmptyDetailDTO tmpDetail = resultList.get(0);
        memberEmpty.setPkId(tmpDetail.getPkMemberEmpty());
        memberEmpty.setRemark(tmpDetail.getRemark());
        memberEmpty.setPkModified(userId);
        memberEmpty.setModifiedTime(new Date());

        // 空单明细数据
        for (MemberEmptyDetailDTO detailDTO : resultList) {
            detailList.add(BeanUtil.copyProperties(detailDTO, CuMemberEmptyDetail.class));

            // 产品列表数据
            List<MemberEmptyProductDTO> tmpProductList = detailDTO.getProductList();
            if (CollectionUtil.isNotEmpty(tmpProductList)) {
                for (MemberEmptyProductDTO productDTO : tmpProductList) {
                    CuMemberEmptyProduct cuMemberEmptyProduct = new CuMemberEmptyProduct();
                    cuMemberEmptyProduct.setPkMemberEmpty(detailDTO.getPkMemberEmpty());
                    cuMemberEmptyProduct.setPkMemberEmptyDetail(detailDTO.getPkId());
                    cuMemberEmptyProduct.setPkProduct(productDTO.getPkProduct());
                    cuMemberEmptyProduct.setQuantity(productDTO.getQuantity());
                    cuMemberEmptyProduct.setSpecsName(productDTO.getSpecsName());
                    cuMemberEmptyProduct.setSpecsNameId(productDTO.getSpecsNameId());
                    cuMemberEmptyProduct.setPkCountry(pkCountry);
                    productList.add(cuMemberEmptyProduct);
                }
            }
        }

        // 修改空单批次
        iCuMemberEmptyService.updateById(memberEmpty);
        // 更新空单批次明细
        iCuMemberEmptyDetailService.updateBatch(detailList, userId);
        // 删除部分空单产品数据
        iCuMemberEmptyProductService.deleteBatch(productList, userId, tmpDetail.getPkMemberEmpty());
        if (CollectionUtil.isNotEmpty(productList)) {
            // 插入或更新空间批次产品
            iCuMemberEmptyProductService.insertOrUpdateBatch(productList, userId);
        }

        return true;
    }

    @Override
    public Boolean handleDate(List<MemberEmptyDetailDTO> resultList) {
        // true为成功， false为失败
        final Boolean[] bool = new Boolean[1];

        // 会员编号列表（需要查库校验） -> 导入会员编号去重
        List<String> checkMemberList = new ArrayList<>();
        // 推荐编号Set
        Set<String> parentSet = new HashSet<>();
        // 安置编号Set
        Set<String> placeParentSet = new HashSet<>();
//        // 结算国家Set
//        Set<Integer> settleCountryList = new HashSet<>();
//        // 手机号注册次数入参列表
//        List<EmptyMemberDTO> queryPhoneRegisterList = new ArrayList<>();

        // 所属空单批次
        Long pkMemberEmpty = resultList.get(0).getPkMemberEmpty();

        // 遍历导入数据，提取各种校验所需要的数据
        for (MemberEmptyDetailDTO detail : resultList) {
            if (this.checkBase(detail, checkMemberList)) {
                // 已经存在异常，直接返回
                return false;
            }

            // 处理后续需要的各种数据列表
            parentSet.add(detail.getParentCode());
            placeParentSet.add(detail.getPlaceParentCode());
//            settleCountryList.add(detail.getPkSettleCountry());
//            queryPhoneRegisterList.add(EmptyMemberDTO.builder()
//                    .pkSettleCountry(detail.getPkSettleCountry())
//                    .phone(detail.getPhone())
//                    .build());
        }

        for (String checkMember : checkMemberList) {
            // 推荐编号存在导入会员中的，不需要查库
            parentSet.remove(checkMember);
            // 安置编号存在导入会员中的，不需要查库
            placeParentSet.remove(checkMember);
        }

        // 查询会员编号是否存在
        Map<String, Integer> checkCodeMap = iCuMemberService.checkMemberCodeExist(checkMemberList, true, pkMemberEmpty);

        // 查询推荐编号是否存在（在本次推荐数据中的直接排除掉）
        final Map<String, Integer> checkParentCodeMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(parentSet)) {
            checkParentCodeMap.putAll(iCuMemberService.checkMemberCodeExist(parentSet, true, pkMemberEmpty));
        }

        // 查询安置编号是否存在
        final Map<String, Integer> checkPlaceParentCodeMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(placeParentSet)) {
            checkPlaceParentCodeMap.putAll(iCuMemberService.checkMemberCodeExist(placeParentSet, true, pkMemberEmpty));
        }

//        // 手机号查询次数以及对应会员列表
//        Map<String, List<EmptyMemberDetailDTO>> phoneRegisterMap = iCuMemberEmptyDetailService.queryMemberByPhone(queryPhoneRegisterList);
//        // 手机号注册次数
//        Map<Integer, String> phoneCountMap = systemConfigServiceApi.getBonusSystemConfigBatch(settleCountryList, ESystemConfig.REGISTER_NUMBER.getKey()).getData();
//        // 直推校验（第一单是否需要进行校验）
//        Map<Integer, String> parentCheckMap = systemConfigServiceApi.getBonusSystemConfigBatch(settleCountryList, ESystemConfig.PARENT_VALIDATE.getKey()).getData();
//        // 安置位置校验（第一单安置位置）
//        Map<Integer, String> placeCheckMap = systemConfigServiceApi.getBonusSystemConfigBatch(settleCountryList, ESystemConfig.PLACE_POSITION.getKey()).getData();

        resultList.parallelStream().forEach((detail) -> {
            // 处理校验会员编号是否重复
            if (checkCodeMap.size() > 0) {
                if (null != checkCodeMap.get(detail.getMemberCode()) && checkCodeMap.get(detail.getMemberCode()) >= 1) {
                    // 导入的会员编号已经存在数据库中，异常状态
                    detail.setPointStatus(EPointStatus.ABNORMAL.getValue());
                    // 会员编号存在重复
                    detail.setContentAbstract(detail.getContentAbstract().replace(TransactionUtils.getContent(MemberMsgConstants.EMPTY_MEMBER_REPEAT), "") + TransactionUtils.getContent(MemberMsgConstants.EMPTY_MEMBER_REPEAT) + ";");
                    bool[0] = false;
                }
            }
            // 处理校验推荐编号是否存在
            if (!checkMemberList.contains(detail.getParentCode()) && checkParentCodeMap.get(detail.getParentCode()) == null) {
                // 推荐编号不在本次导入的会员中，也不在数据库中，异常状态
                detail.setPointStatus(EPointStatus.ABNORMAL.getValue());
                // 推荐编号不存在
                detail.setContentAbstract(detail.getContentAbstract() + TransactionUtils.getContent(MemberMsgConstants.EMPTY_PARENT_NOT) + ";");
                bool[0] = false;
            }
            // 处理校验安置编号是否存在
            if (!checkMemberList.contains(detail.getPlaceParentCode()) && checkPlaceParentCodeMap.get(detail.getPlaceParentCode()) == null) {
                // 安置编号不在本次导入的会员中，也不在数据库中，异常状态
                detail.setPointStatus(EPointStatus.ABNORMAL.getValue());
                // 安置编号不存在
                detail.setContentAbstract(detail.getContentAbstract() + TransactionUtils.getContent(MemberMsgConstants.EMPTY_PLACE_PARENT_NOT) + ";");
                bool[0] = false;
            }

            // 校验推荐、安置关系（安置必须在推荐血缘伞下（按安置线往上找到推荐））
            String tmpParent = iCuMemberEmptyDetailService.checkPlaceParent(detail.getMemberCode(), detail.getParentCode(), pkMemberEmpty);
            if (StringUtils.isEmpty(tmpParent)) {
                detail.setPointStatus(EPointStatus.ABNORMAL.getValue());
                // 安置编号不在推荐编号伞下
                detail.setContentAbstract(detail.getContentAbstract() + TransactionUtils.getContent(MemberMsgConstants.EMPTY_PLACE_NOT_PARENT) + ";");
                bool[0] = false;
            } else {
//                if (EYesNo.YES.getIntValue() == Integer.parseInt(parentCheckMap.get(detail.getPkSettleCountry()))) {
//                    // 首单校验
//                    // 首单安置位置
//                    int placeDept = Integer.parseInt(placeCheckMap.get(detail.getPkSettleCountry()));
//                    if (1 != placeDept) {
//                        // 安置位置不为任意，需要校验是否有数据
//                        if (null == placeCheckMap.get(placeDept)) {
//                            detail.setPointStatus(EPointStatus.ABNORMAL.getValue());
//                            // 安置首单不存在
//                            detail.setContentAbstract(detail.getContentAbstract() + TransactionUtils.getContent(MemberMsgConstants.EMPTY_PLACE_FIRST_NOT) + ";");
//                            bool[0] = false;
//                        }
//                    }
//                }

                // 安置部门是否有重复
                Map<Integer, List<CuMemberEmptyDetail>> checkPlaceDeptMap = iCuMemberEmptyDetailService.checkPlaceDeptRepeat(detail.getPlaceParentCode());
                // 当前会员编号所在安置位置数据列表
                List<CuMemberEmptyDetail> emptyDetailList = checkPlaceDeptMap.get(detail.getPlaceDept());
                // 去掉安置位置数据列表不等于当前会员的仍然有数据，则安置部门有重复
                if (emptyDetailList.stream().anyMatch(tmpDetail -> !tmpDetail.getMemberCode().equals(detail.getMemberCode()))) {
                    detail.setPointStatus(EPointStatus.ABNORMAL.getValue());
                    // 安置部门存在重复
                    detail.setContentAbstract(detail.getContentAbstract() + TransactionUtils.getContent(MemberMsgConstants.EMPTY_PLACE_REPEAT) + ";");
                    bool[0] = false;
                }
            }

//            // 校验会员姓名、联系方式次数
//            List<EmptyMemberDetailDTO> memberPhoneList = phoneRegisterMap.get(detail.getPhone());
//            if (CollectionUtil.isNotEmpty(memberPhoneList)) {
//                if (memberPhoneList.size() > Integer.parseInt(phoneCountMap.get(detail.getPkSettleCountry()))) {
//                    detail.setPointStatus(EPointStatus.ABNORMAL.getValue());
//                    // 手机注册次数已达系统上限
//                    detail.setContentAbstract(detail.getContentAbstract() + TransactionUtils.getContent(MemberMsgConstants.SYSTEM_REGISTER_COUNT) + ";");
//                    bool[0] = false;
//                }
//                if (!memberPhoneList.stream().allMatch(dto -> detail.getMemberName().equals(dto.getMemberName()))) {
//                    detail.setPointStatus(EPointStatus.ABNORMAL.getValue());
//                    // 手机号码已经被其他会员注册
//                    detail.setContentAbstract(detail.getContentAbstract() + TransactionUtils.getContent(MemberMsgConstants.PHONE_ALREADY_REGISTER) + ";");
//                    bool[0] = false;
//                }
//            }

//            // 联系方式不能跨团队
//            String checkStr = iCuMemberEmptyDetailService.checkPhoneInPlaceParent(detail.getMemberCode(), detail.getPhone(), null);
//            // 此处判断，因为查询的手机号数据里面已经包含了自己，所以需要大于1
//            if (StringUtils.isNotEmpty(checkStr) && (CollectionUtil.isNotEmpty(memberPhoneList) && memberPhoneList.size() > 1)) {
//                // 安置树上面没有当前会员联系方式，但是联系方式已经存在
//                detail.setPointStatus(EPointStatus.ABNORMAL.getValue());
//                // 注册信息在其他团队存在
//                detail.setContentAbstract(detail.getContentAbstract() + TransactionUtils.getContent(MemberMsgConstants.EMPTY_MEMBER_IN_OTHER) + ";");
//                bool[0] = false;
//            }
        });
        return bool[0];
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveEmptyMember(Long pkMemberEmpty, List<CuMemberEmptyDetailExt> detailList, Long userId, Integer pkCountry) {
        // 需要查询的推荐人、安置人数据
        Set<String> queryMemberSet = new HashSet<>();
        // 会员编号对应会员ID（key: 会员编号，value: 会员ID)
        Map<String, Long> memberSeqMap = new HashMap<>();
        // 会员编号对应会员账户ID（key: 会员编号，value: 会员账户ID)
        Map<String, Long> memberAccountSeqMap = new HashMap<>();
        // 需要查询汇率数据（确定要用的国家）
        Set<Integer> queryRateSet = new HashSet<>();
        // 需要查询仓库数据（有可能要用的省）
        Set<Integer> queryStoreHouseSet = new HashSet<>();
        // 需要查询奖金账户数据（有可能用的国家）
        Set<Integer> queryAccountSet = new HashSet<>();

        // 生成需要入库的会员ID列表
        List<Long> memberSeqList = iCuMemberService.querySeqList(detailList.size());
        // 生成需要入库的会员账户ID列表
        List<Long> memberAccountSeqList = iCuMemberAccountService.querySeqList(detailList.size());
        // 订单需要生成seq的数量
        int orderSeqCount = 0;
        // 遍历空单明细数据，提取准备的数据
        for (int i = 0; i < detailList.size(); i++) {
            CuMemberEmptyDetailExt emptyDetail = detailList.get(i);
            // 需要查库的推荐人、安置人
            queryMemberSet.add(emptyDetail.getParentCode());
            queryMemberSet.add(emptyDetail.getPlaceParentCode());

            // 记录会员编号与ID关系
            memberSeqMap.put(emptyDetail.getMemberCode(), memberSeqList.get(i));
            // 记录会员编号与账户ID关系
            memberAccountSeqMap.put(emptyDetail.getMemberCode(), memberAccountSeqList.get(i));

            // 需要查库的汇率数据
            queryRateSet.add(emptyDetail.getPkSettleCountry());

            // 如果选购产品并且存在产品信息
            if (EYesNo.YES.getIntValue() == emptyDetail.getProductFlag() && CollectionUtil.isNotEmpty(emptyDetail.getProductDTOList())) {
                // 累计订单数量
                orderSeqCount++;
                // 记录查询仓库数据
                queryStoreHouseSet.add(emptyDetail.getRecProvince());
            }

            if (null != emptyDetail.getBackAmount() && emptyDetail.getBackAmount().compareTo(BigDecimal.ZERO) > 0) {
                // 回调金额大于0，记录查询账户国家
                queryAccountSet.add(emptyDetail.getPkSettleCountry());
            }
        }

        // 会员编号对应的会员信息（key: 会员编号，value: 会员信息)
        Map<String, CuMember> memberMap = new HashMap<>();
        // 查询推荐人、安置人数据
        List<CuMember> memberList = iCuMemberService.queryMemberListByCode(queryMemberSet);
        if (CollectionUtil.isNotEmpty(memberList)) {
            for (CuMember cuMember : memberList) {
                // 会员编号对应会员ID记录
                memberSeqMap.put(cuMember.getMemberCode(), cuMember.getPkId());
                // 会员编号对应会员信息记录
                memberMap.put(cuMember.getMemberCode(), cuMember);
            }
        }

        // 国家对应汇率（key: 国家ID，value: 汇率ID)
        Map<Integer, Integer> currencyMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(queryRateSet)) {
            // 查询汇率数据
            List<CurrencyDTO> currencyList = iCurrencyServiceApi.getCurrencyByPkCountryList(queryRateSet).getData();
            if (CollectionUtil.isNotEmpty(currencyList)) {
                for (CurrencyDTO currencyDTO : currencyList) {
                    currencyMap.put(currencyDTO.getPkCountry(), currencyDTO.getPkId());
                }
            }
        }

        // 省对应发货仓库（key: 省ID，value: 仓库ID)
        Map<Integer, Integer> storehouseMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(queryStoreHouseSet)) {
            // 查询省对应仓库
            List<BdStorehouse> storehouseList = iCurrencyServiceApi.queryBdStorehouseMapByProvince(queryStoreHouseSet).getData();
            if (CollectionUtil.isNotEmpty(storehouseList)) {
                for (BdStorehouse storehouse : storehouseList) {
                    storehouseMap.put(storehouse.getProvince(), storehouse.getPkId());
                }
            }
        }

        // 回填金额账户数据（key: 国家ID，value: 账户ID)
        Map<Integer, Integer> accountMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(queryAccountSet)) {
            // 查询国家对应奖金币种
            List<BdAccount> accountList = iAccountServiceApi.queryAccountByType(EAccount.BONUS.getValue(), queryAccountSet).getData();
            if (CollectionUtil.isNotEmpty(accountList)) {
                for (BdAccount bdAccount : accountList) {
                    accountMap.put(bdAccount.getPkCountry(), bdAccount.getPkId());
                }
            }
        }

        // 国家等级（key：国家ID，value：等级列表）
        Map<Integer, List<GradeDTO>> gradeMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(queryRateSet)) {
            gradeMap = iGradeServiceApi.queryCountryGradeConfigByCondition(queryRateSet).getData();
        }

        // 生成订单seq数据
        List<Long> orderSeqList = new ArrayList<>(orderSeqCount);
        if (0 != orderSeqCount) {
            orderSeqList = iSaOrderServiceApi.querySeqList(orderSeqCount).getData();
        }
        // 订单seq数据下标
        int orderSeqInt = 0;

        ////////// 封装入口相关数据开始 //////////

        // 当前时间
        Date nowDate = new Date();
        // 入库会员列表
        List<CuMember> saveMemberList = new ArrayList<>(detailList.size());
        // 入库会员账户列表
        List<CuMemberAccount> saveMemberAccountList = new ArrayList<>(detailList.size());
        // 入库会员注册信息列表
        List<CuMemberRegister> registerMemberList = new ArrayList<>(detailList.size());
        // 入库会员账户流水列表
        List<CuMemberTrade> saveMemberTradeList = new ArrayList<>();
        // 入库订单列表
        List<SaOrder> saveOrderList = new ArrayList<>();
        // 入库订单明细列表
        List<SaOrderItems> saveOrderItemList = new ArrayList<>();

        // 查询批次下安置架构顶点
        List<CuMemberEmptyDetailExt> placeTopList = iCuMemberEmptyDetailService.queryPlaceParentTopAndProduct(pkMemberEmpty);
        // 按架构顶点进行封装入库数据
        for (CuMemberEmptyDetail topDetail : placeTopList) {
            // 查询安置下所有用户
            List<CuMemberEmptyDetailExt> placeTreeList = iCuMemberEmptyDetailService.queryPlaceParentTreeAndProduct(topDetail.getPkId(), topDetail.getPkMemberEmpty());
            if (CollectionUtil.isNotEmpty(placeTreeList)) {
                for (CuMemberEmptyDetailExt treeDetail : placeTreeList) {
                    if (!topDetail.getPkId().equals(treeDetail.getPkId())) {
                        // 最顶级的安置人不做处理，需要在下面循环中处理并且上锁

                        // 结算国
                        Integer pkSettleCountry = treeDetail.getPkSettleCountry();
                        // 封装会员以及会员账户数据
                        CuMember cuMember = this.createMember(saveMemberList, saveMemberAccountList, registerMemberList, saveMemberTradeList,
                                memberSeqMap, memberMap, memberAccountSeqMap, treeDetail, memberSeqMap.get(treeDetail.getPlaceParentCode()),
                                accountMap.get(pkSettleCountry), currencyMap.get(pkSettleCountry), userId, nowDate, gradeMap);

                        // 如果选购产品并且存在产品信息
                        if (EYesNo.YES.getIntValue() == treeDetail.getProductFlag() && CollectionUtil.isNotEmpty(treeDetail.getProductDTOList())) {
                            // 获取订单ID
                            Long pkOrder = orderSeqList.get(orderSeqInt++);
                            this.createOrder(saveOrderList, saveOrderItemList, treeDetail, cuMember,
                                    currencyMap.get(pkSettleCountry), storehouseMap.get(treeDetail.getRecCounty()),
                                    pkOrder, userId, nowDate);
                        }
                    }
                }
            }
        }

        // redis进行上锁的key
        List<String> redisLockList = new ArrayList<>(placeTopList.size());
        try {
            // 最后处理顶级安置人数据，并且锁安置进行入库
            for (CuMemberEmptyDetailExt topDetail : placeTopList) {
                // 结算国
                Integer pkSettleCountry = topDetail.getPkSettleCountry();
                // 安置人ID
                Long placePkId = this.placeLock(topDetail, redisLockList);
                // 封装会员以及会员账户数据
                CuMember cuMember = this.createMember(saveMemberList, saveMemberAccountList, registerMemberList, saveMemberTradeList,
                        memberSeqMap, memberMap, memberAccountSeqMap, topDetail, placePkId,
                        accountMap.get(pkSettleCountry), currencyMap.get(pkSettleCountry), userId, nowDate, gradeMap);

                // 如果选购产品并且存在产品信息
                if (EYesNo.YES.getIntValue() == topDetail.getProductFlag() && CollectionUtil.isNotEmpty(topDetail.getProductDTOList())) {
                    // 获取订单ID
                    Long pkOrder = orderSeqList.get(orderSeqInt++);
                    this.createOrder(saveOrderList, saveOrderItemList, topDetail, cuMember,
                            currencyMap.get(pkSettleCountry), storehouseMap.get(topDetail.getRecCounty()),
                            pkOrder, userId, nowDate);
                }
            }
        } catch (Exception e) {
            log.error("空单注册处理异常", e);
            // 释放所有的锁
            redisService.deleteObject(redisLockList);
            return false;
        }

        ////////// 封装入口相关数据结束 //////////

        try {
            // 批量保存会员
            iCuMemberService.insertBatchCuMember(saveMemberList);
            // 批量保存会员账户
            iCuMemberAccountService.insertBatchCuMemberAccount(saveMemberAccountList);
            // 批量保存会员注册信息
            iCuMemberRegisterService.insertBatchMemberRegister(registerMemberList);
            // 批量保存会员账户流水
            if (CollectionUtil.isNotEmpty(saveMemberTradeList)) {
                iCuMemberTradeService.batchSaveTradeByMemberCode(saveMemberTradeList);
            }
            // 全球编号、国际编号先不做处理，在登录的时候校验如果没有则补全

            // 更新空单状态
            UpdateWrapper<CuMemberEmpty> memberEmptyUpdateWrapper = new UpdateWrapper<>();
            memberEmptyUpdateWrapper.eq(SystemFieldConstants.PK_ID, pkMemberEmpty);
            memberEmptyUpdateWrapper.set("STATUS", EApproveStatus.FINISH.getValue());
            memberEmptyUpdateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
            memberEmptyUpdateWrapper.set(SystemFieldConstants.MODIFIED_TIME, nowDate);
            iCuMemberEmptyService.update(memberEmptyUpdateWrapper);

            // 购买产品，订单以及订单明细入库
            if (CollectionUtil.isNotEmpty(saveOrderList)) {
                R orderResult = iSaOrderServiceApi.saveOrderBatch(saveOrderList, saveOrderItemList);
                if (!orderResult.isSuccess()) {
                    throw new BaseException("空单注册生成订单异常");
                }
            }
        } catch (Exception e) {
            log.error("空单注册操作异常", e);
            throw new BaseException("空单注册操作异常");
        } finally {
            // 释放所有的锁
            redisService.deleteObject(redisLockList);
        }
        return true;
    }

    /**
     * 基础校验（列表数据本身是否有重复）
     *
     * @param detail          校验数据
     * @param checkMemberList 会员编号列表
     */
    private boolean checkBase(MemberEmptyDetailDTO detail, List<String> checkMemberList) {
        // 校验之前先为空
        detail.setPointStatus(EPointStatus.NORMAL.getValue());
        detail.setContentAbstract("");
        // 是否有问题
        boolean hasError = false;

        if (detail.getMemberCode().equals(detail.getParentCode())) {
            // 会员编号 == 推荐编号
            detail.setPointStatus(EPointStatus.ABNORMAL.getValue());
            // 会员编号与推荐编号相同
            detail.setContentAbstract(detail.getContentAbstract() + TransactionUtils.getContent(MemberMsgConstants.EMPTY_MEMBER_EQ_PARENT) + ";");
            hasError = true;
        }
        if (detail.getMemberCode().equals(detail.getPlaceParentCode())) {
            // 会员编号 == 安置编号
            detail.setPointStatus(EPointStatus.ABNORMAL.getValue());
            // 会员编号与安置编号相同
            detail.setContentAbstract(detail.getContentAbstract() + TransactionUtils.getContent(MemberMsgConstants.EMPTY_MEMBER_EQ_PLACE) + ";");
            hasError = true;
        }
        if (checkMemberList.contains(detail.getMemberCode())) {
            // 导入的数据存在重复会员编号，异常状态
            detail.setPointStatus(EPointStatus.ABNORMAL.getValue());
            // 会员编号存在重复
            detail.setContentAbstract(detail.getContentAbstract() + TransactionUtils.getContent(MemberMsgConstants.EMPTY_MEMBER_REPEAT) + ";");
            hasError = true;
        } else {
            // 导入数据中不重复的会员编号，需要查库校验是否重复
            checkMemberList.add(detail.getMemberCode());
        }
        return hasError;
    }

    /**
     * 封装会员以及会员账户数据
     *
     * @param saveMemberList        入库会员列表
     * @param saveMemberAccountList 入库会员账户列表
     * @param registerMemberList    入库会员注册信息列表
     * @param saveMemberTradeList   入库会员账户流水列表
     * @param memberSeqMap          会员编号对应的会员ID（key: 会员编号，value: 会员ID)
     * @param memberMap             会员编号对应的会员信息（key: 会员编号，value: 会员信息)
     * @param memberAccountSeqMap   会员编号对应的会员账户ID（key: 会员编号，value: 会员账户ID)
     * @param emptyDetail           空单明细数据
     * @param pkPlaceParent         安置人ID
     * @param pkAccount             奖金账户ID
     * @param pkRate                汇率
     * @param userId                当前会员
     * @param nowDate               当前时间
     * @param gradeMap              等级列表
     */
    private CuMember createMember(List<CuMember> saveMemberList, List<CuMemberAccount> saveMemberAccountList,
                                  List<CuMemberRegister> registerMemberList, List<CuMemberTrade> saveMemberTradeList,
                                  Map<String, Long> memberSeqMap, Map<String, CuMember> memberMap, Map<String, Long> memberAccountSeqMap,
                                  CuMemberEmptyDetail emptyDetail, Long pkPlaceParent, Integer pkAccount, Integer pkRate, Long userId, Date nowDate,
                                  Map<Integer, List<GradeDTO>> gradeMap) {
        // 会员ID
        Long pkMember = memberSeqMap.get(emptyDetail.getMemberCode());
        // 推荐人ID
        Long pkParent = memberSeqMap.get(emptyDetail.getParentCode());
        // 推荐人信息
        CuMember parentMember = memberMap.get(emptyDetail.getParentCode());

        // 封装用户数据
        CuMember cuMember = CuMember.builder()
                .pkId(pkMember)
                .memberCode(emptyDetail.getMemberCode())
                .memberName(emptyDetail.getMemberName())
                .customerType(ECustomerType.EMPTY_ORDER.getValue())
                .phone(emptyDetail.getPhone())
                .pkParent(pkParent)
                .pkPlaceParent(pkPlaceParent)
                .placeDept(emptyDetail.getPlaceDept())
                .pkSettleCountry(emptyDetail.getPkSettleCountry())
                .source(EDataSource.PC.getValue())
                .pkRegisterGrade(emptyDetail.getPkRegisterGrade())
                .pkSettleGrade(emptyDetail.getPkRegisterGrade())
                .pkAwards(emptyDetail.getPkAwards())
                .payTime(nowDate)
                .loginPwd(SecurityUtils.encryptPassword(SysConstants.LOGIN_PASSWORD))
                .payPwd(SecurityUtils.encryptPassword(SysConstants.PAY_PASSWORD))
                .loginPassword(SysConstants.LOGIN_PASSWORD)
                .payPassword(SysConstants.PAY_PASSWORD)
                .payStatus(EPayStatus.PAID.getValue())
                .pkTeamCode(null != parentMember ? parentMember.getPkTeamCode() : null)
                .pkVertex(null != parentMember ? parentMember.getPkVertex() : null)
                .orderSource(emptyDetail.getOrderSource())
                .consumeAchieve(null != emptyDetail.getRegisterAchieve() ? emptyDetail.getRegisterAchieve() : BigDecimal.ZERO)
                .build();

        cuMember.setPkCountry(emptyDetail.getPkCountry());
        cuMember.setPkCreator(userId);
        cuMember.setCreationTime(nowDate);

        // 如果是非会员等级，则给一年的奖金有效期
        List<GradeDTO> gradeList = gradeMap.get(emptyDetail.getPkCountry());
        GradeDTO gradeDTO = gradeList.stream().filter(dto -> dto.getPkId().equals(emptyDetail.getPkRegisterGrade())).findFirst().get();
        if (gradeDTO.getGradeValue() >= EGrade.YOU_KE.getValue()) {
            // 结算等级大于等于铜卡，需要给奖金年包一年时间
            cuMember.setExpireDate(DateUtils.addDays(DateUtils.addYears(cuMember.getCreationTime() != null ? cuMember.getCreationTime() : new Date(), MagicNumberConstants.BOUNS_INIT_YEAR), -1));
        }

        saveMemberList.add(cuMember);

        memberMap.put(emptyDetail.getMemberCode(), cuMember);

        // 封装用户注册数据
        CuMemberRegister cuMemberRegister = new CuMemberRegister();
        cuMemberRegister.setMemberCode(cuMember.getMemberCode());
        cuMemberRegister.setMemberName(cuMember.getMemberName());
        cuMemberRegister.setCustomerType(cuMember.getCustomerType());
        cuMemberRegister.setPhone(cuMember.getPhone());
        cuMemberRegister.setPkCountry(cuMember.getPkCountry());
        cuMemberRegister.setPkSettleCountry(cuMember.getPkSettleCountry());
        cuMemberRegister.setPlaceDept(cuMember.getPlaceDept());
        cuMemberRegister.setSource(cuMember.getSource());
        cuMemberRegister.setPkRegisterGrade(cuMember.getPkRegisterGrade());
        cuMemberRegister.setConsumeAchieve(cuMember.getConsumeAchieve());
        cuMemberRegister.setPayTime(cuMember.getPayTime());
        cuMemberRegister.setCreationTime(cuMember.getCreationTime());
        cuMemberRegister.setPkCreator(cuMember.getPkId());
        cuMemberRegister.setPkParent(cuMember.getPkParent());
        cuMemberRegister.setPkPlaceParent(cuMember.getPkPlaceParent());
        cuMemberRegister.setPkTeamCode(cuMember.getPkTeamCode());
        cuMemberRegister.setPkVertex(cuMember.getPkVertex());
        cuMemberRegister.setPkMember(cuMember.getPkId());
        registerMemberList.add(cuMemberRegister);

        // 回填金额
        BigDecimal backAmount = BigDecimal.ZERO;
        if (null != emptyDetail.getBackAmount() && emptyDetail.getBackAmount().compareTo(BigDecimal.ZERO) > 0) {
            // 回填金额不为空并且大于0，则需要处理回填金额（回填金额直接入账户，显示为负数）
            backAmount = emptyDetail.getBackAmount().abs().negate();

            // 封装用户账户流水数据
            CuMemberTrade cuMemberTrade = CuMemberTrade.builder()
                    .pkMember(pkMember)
                    .tradeCode(CommonUtil.createSerialNumber(EOrderPrefix.TRADE_CODE))
                    .pkAccount(pkAccount)
                    .tradeType(ETradeType.EMPTY_ORDER.getValue())
                    .tradeClassify(ETradeClassify.CONSUME.getValue())
                    .pkRate(pkRate)
                    .tradeBeforeBalance(BigDecimal.ZERO)
                    .tradeAmount(backAmount)
                    .tradeBalance(backAmount)
                    .tradeStatue(ETradeStatus.TAKE_EFFECT.getValue())
                    .build();
            cuMemberTrade.setPkCountry(emptyDetail.getPkSettleCountry());
            cuMemberTrade.setPkCreator(userId);
            cuMemberTrade.setCreationTime(nowDate);
            saveMemberTradeList.add(cuMemberTrade);
        }

        // 封装用户账户数据
        CuMemberAccount cuMemberAccount = CuMemberAccount.builder()
                .pkId(memberAccountSeqMap.get(emptyDetail.getMemberCode()))
                .pkMember(pkMember)
                .account4(backAmount)
                .build();
        cuMemberAccount.setPkCountry(emptyDetail.getPkSettleCountry());
        cuMemberAccount.setPkCreator(userId);
        cuMemberAccount.setCreationTime(nowDate);
        saveMemberAccountList.add(cuMemberAccount);

        return cuMember;
    }

    /**
     * 封装订单以及订单详情数据
     *
     * @param saveOrderList     入库订单列表
     * @param saveOrderItemList 入库订单明细列表
     * @param emptyDetail       空单明细数据
     * @param cuMember          新会员数据
     * @param pkRate            汇率ID
     * @param pkStoreHouse      仓库ID
     * @param pkOrder           订单ID
     * @param userId            当前会员
     * @param nowDate           当前时间
     */
    private void createOrder(List<SaOrder> saveOrderList, List<SaOrderItems> saveOrderItemList,
                             CuMemberEmptyDetailExt emptyDetail, CuMember cuMember,
                             Integer pkRate, Integer pkStoreHouse,
                             Long pkOrder, Long userId, Date nowDate) {
        // 封装订单信息
        SaOrder saOrder = SaOrder.builder()
                .pkId(pkOrder)
                .orderCode(CommonUtil.createSerialNumber(EOrderPrefix.ORDER_CODE))
                .orderType(EOrderType.REGISTER_ORDER.getValue())
                .pkRate(pkRate)
                .orderAmount(BigDecimal.ZERO)
                .orderAchieve(null != emptyDetail.getSettlementAchieve() ? emptyDetail.getSettlementAchieve() : BigDecimal.ZERO)
                .uploadAchieve(null != emptyDetail.getTransferAchieve() ? emptyDetail.getTransferAchieve() : BigDecimal.ZERO)
                .recName(emptyDetail.getRecName())
                .recPhone(emptyDetail.getRecPhone())
                .recProvince(emptyDetail.getRecProvince())
                .recCity(emptyDetail.getRecCity())
                .recCounty(emptyDetail.getRecCounty())
                .recAddress(emptyDetail.getRecAddress())
                .payTime(nowDate)
                .payType(EOrderPayType.WALLET.getValue())
                .orderStatus(EPayStatus.PAID.getValue())
                .pkMember(emptyDetail.getPkId())
                .pkReference(cuMember.getPkParent())
                .pkPlacement(cuMember.getPkPlaceParent())
                .pkVertex(cuMember.getPkVertex())
                .pkStorehouse(pkStoreHouse)
                .build();
        saOrder.setPkCountry(emptyDetail.getPkSettleCountry());
        saOrder.setPkCreator(userId);
        saOrder.setCreationTime(nowDate);
        saveOrderList.add(saOrder);

        // 产品信息
        List<CuMemberEmptyProductDTO> productDTOList = emptyDetail.getProductDTOList();
        if (CollectionUtil.isNotEmpty(productDTOList)) {
            for (CuMemberEmptyProductDTO productDTO : productDTOList) {
                // 封装订单明细停放上
                SaOrderItems saOrderItems = SaOrderItems.builder()
                        .pkOrder(pkOrder)
                        .pkProduct(productDTO.getPkProduct())
                        .pkRate(pkRate)
                        .quantity(productDTO.getQuantity())
                        .pkGrade(cuMember.getPkSettleGrade())
                        .pkAwards(cuMember.getPkAwards())
                        .orderStatus(EOrderStatus.PAY.getValue())
                        .specsName(productDTO.getSpecsName())
                        .specsNameId(productDTO.getSpecsNameId())
                        .waresQuantity(productDTO.getQuantity())
                        .build();
                saOrderItems.setPkCountry(emptyDetail.getPkSettleCountry());
                saOrderItems.setPkCreator(userId);
                saOrderItems.setCreationTime(nowDate);
                saveOrderItemList.add(saOrderItems);
            }
        }
    }

    /**
     * 安置位置验证以及锁定
     *
     * @param emptyDetail   空单明细数据
     * @param redisLockList redis锁定列表
     * @return
     */
    private Long placeLock(CuMemberEmptyDetail emptyDetail, List<String> redisLockList) {
        // 查询最末安置人
        CuMemberExt cuMemberExt = iCuMemberService.queryLastPlaceByMemberCode(emptyDetail.getPlaceParentCode(), emptyDetail.getPlaceDept());
        if (null == cuMemberExt) {
            cuMemberExt = iCuMemberService.getMemberByCode(emptyDetail.getPlaceParentCode());
        }
        // 需要锁安置位置
        String redisLock = CacheConstants.POSITION + cuMemberExt.getPkId() + emptyDetail.getPlaceDept();
        if (redisService.lockKeyOnce(redisLock)) {
            redisLockList.add(redisLock);

            return cuMemberExt.getPkId();
        }
        try {
            Thread.sleep(200);
            return this.placeLock(emptyDetail, redisLockList);
        } catch (Exception e) {
            log.error("空单注册锁定安置异常", e);
            throw new BaseException("空单注册锁定安置异常");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String submit(MemberEmptySignParam param, List<CuMemberEmptyDetailExt> detailList, LoginUser loginUser) {
        String businessCode = CommonUtil.createSerialNumber(EOrderPrefix.HANDLE_BUSINESS);

        CuMemberEmptyLog cuMemberEmptyLog = new CuMemberEmptyLog();
        cuMemberEmptyLog.setPkMemberEmpty(param.getPkId());
        cuMemberEmptyLog.setBusinessCode(businessCode);
        cuMemberEmptyLog.setNewValue(JSONUtil.toJsonStr(detailList));
        cuMemberEmptyLog.setPkCreator(loginUser.getUserId());
        cuMemberEmptyLog.setPkCountry(loginUser.getDataCountry());

        // 添加数据日志
        if (iCuMemberEmptyLogService.save(cuMemberEmptyLog)) {
            // 更新空单注册主表状态
            UpdateWrapper<CuMemberEmpty> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(SystemFieldConstants.PK_ID, param.getPkId());
            updateWrapper.set("STATUS", EApproveStatus.ALREADY_SUBMIT.getValue());
            updateWrapper.set(SystemFieldConstants.PK_MODIFIED, loginUser.getUserId());
            updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, new Date());
            iCuMemberEmptyService.update(updateWrapper);

            // 提交签呈处理
            R<String> resultR = iApprovalServiceApi.submit(
                    ApprovalSubmitDTO.builder()
                            .eApprovalBusiness(EApprovalBusiness.EMPTY_ORDER)
                            .businessCode(businessCode)
                            .signType(ESignType.getEnumByValue(param.getSignType()))
                            .userIdList(param.getUserIdList())
                            .sendIdList(param.getSendIdList())
                            .remark(param.getRemark())
                            .fileList(param.getFileList())
                            .build(),
                    loginUser
            );
            if (resultR.isSuccess()) {
                return null;
            }
            throw new BaseException(TransactionUtils.getContent(CommonMsgConstants.OPERATION_FAILED) + ": " + resultR.getMsg());
        }
        return TransactionUtils.getContent(CommonMsgConstants.OPERATION_FAILED);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String approvalAgree(ApprovalBusinessResultDTO resultDTO) {
        // 用户ID
        Long userId = resultDTO.getLoginUser().getUserId();
        // 所属国家
        Integer pkCountry = resultDTO.getLoginUser().getDataCountry();

        QueryWrapper<CuMemberEmptyLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BUSINESS_CODE", resultDTO.getBusinessCode());
        queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        CuMemberEmptyLog cuMemberEmptyLog = iCuMemberEmptyLogService.getOne(queryWrapper);

        if (null == cuMemberEmptyLog) {
            log.error("空单注册驳回处理失败: 签呈不存在!");
            return TransactionUtils.getContent(CommonMsgConstants.APPROVAL_NOT_EXIST);
        }
        if (EApproveStatus.ALREADY_SUBMIT.getValue() != cuMemberEmptyLog.getApprovalStatus()) {
            log.error("空单注册驳回处理失败: 签呈已处理");
            return TransactionUtils.getContent(CommonMsgConstants.APPROVAL_PROCESSED);
        }

        // 实际明细数据
        List<CuMemberEmptyDetailExt> detailList = JSONUtil.toList(cuMemberEmptyLog.getNewValue(), CuMemberEmptyDetailExt.class);

        // 准备校验以及入库数据
        List<MemberEmptyDetailDTO> paramList = new ArrayList<>();

        for (CuMemberEmptyDetailExt emptyDetail : detailList) {
            MemberEmptyDetailDTO detailDTO = BeanUtil.copyProperties(emptyDetail, MemberEmptyDetailDTO.class);

            if (StringUtils.isNotEmpty(emptyDetail.getProductDTOList())) {
                // 处理产品信息
                detailDTO.setProductList(BeanUtil.copyToList(emptyDetail.getProductDTOList(), MemberEmptyProductDTO.class));
            }
            paramList.add(detailDTO);
        }

        // 校验点位状态
        Boolean bool = this.handleDate(paramList);
        if (null == bool || bool) {
            // 校验成功，入库数据

            // 更新空单审批日志
            if (this.updateApprovalLog(cuMemberEmptyLog.getBusinessCode(), EApproveStatus.FINISH, resultDTO.getApproveRemark(),
                    pkCountry, userId)) {
                try {
                    if (this.saveEmptyMember(cuMemberEmptyLog.getPkMemberEmpty(), detailList, userId, pkCountry)) {
                        return null;
                    }
                } catch (Exception e) {
                    log.error("空单注册同意入库失败：", e);
                    // 保存空单注册数据失败
                    throw new BaseException("签呈处理失败：空单会员数据保存失败");
                }
            }
            log.error("空单注册同意处理失败: 更新数据失败");
            return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_ORDER_ERROR);
        }
        // 点位状态存在异常，请检查
        return TransactionUtils.getContent(MemberMsgConstants.EMPTY_POINT_ERROR);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String approvalReject(ApprovalBusinessResultDTO resultDTO) {
        // 用户ID
        Long userId = resultDTO.getLoginUser().getUserId();
        // 所属国家
        Integer pkCountry = resultDTO.getLoginUser().getDataCountry();

        QueryWrapper<CuMemberEmptyLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BUSINESS_CODE", resultDTO.getBusinessCode());
        queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        CuMemberEmptyLog cuMemberEmptyLog = iCuMemberEmptyLogService.getOne(queryWrapper);

        if (null == cuMemberEmptyLog) {
            log.error("空单注册驳回处理失败: 签呈不存在!");
            return TransactionUtils.getContent(CommonMsgConstants.APPROVAL_NOT_EXIST);
        }
        if (EApproveStatus.ALREADY_SUBMIT.getValue() != cuMemberEmptyLog.getApprovalStatus()) {
            log.error("空单注册驳回处理失败: 签呈已处理");
            return TransactionUtils.getContent(CommonMsgConstants.APPROVAL_PROCESSED);
        }

        // 更新空单审批日志
        if (this.updateApprovalLog(cuMemberEmptyLog.getBusinessCode(), EApproveStatus.REJECTED, resultDTO.getApproveRemark(),
                pkCountry, userId)) {
            // 更新空单批次主表
            UpdateWrapper<CuMemberEmpty> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(SystemFieldConstants.PK_ID, cuMemberEmptyLog.getPkMemberEmpty());
            updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, new Date());
            updateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
            updateWrapper.set("STATUS", EApproveStatus.REJECTED.getValue());
            iCuMemberEmptyService.update(updateWrapper);

            return null;
        }
        log.error("空单注册驳回处理失败: 更新数据失败");
        return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_ORDER_ERROR);
    }

    /**
     * 更新审批日志
     *
     * @param businessCode  业务单号
     * @param approveStatus 审核状态
     * @param remark        备注
     * @param pkCountry     所属国家
     * @param userId        当前会员
     * @return
     */
    private boolean updateApprovalLog(String businessCode, EApproveStatus approveStatus, String remark,
                                      Integer pkCountry, Long userId) {
        UpdateWrapper<CuMemberEmptyLog> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("BUSINESS_CODE", businessCode);
        updateWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        updateWrapper.eq("APPROVAL_STATUS", EApproveStatus.ALREADY_SUBMIT.getValue());
        updateWrapper.set("APPROVAL_STATUS", approveStatus.getValue());
        updateWrapper.set("APPROVAL_REMARK", remark);
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, new Date());
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
        return iCuMemberEmptyLogService.update(updateWrapper);
    }

}
