package com.hzs.sale.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.activity.pick.service.IAcPickService;
import com.hzs.common.core.config.BdConfig;
import com.hzs.common.core.constant.*;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
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.ServiceException;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.*;
import com.hzs.common.core.utils.reflect.ReflectUtils;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.account.CuMemberAccount;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.base.CuMemberRegister;
import com.hzs.common.domain.member.base.CuMemberShare;
import com.hzs.common.domain.member.business.UpPolicyCurrency;
import com.hzs.common.domain.member.detail.CuMemberLevel;
import com.hzs.common.domain.member.detail.CuMemberServiceLog;
import com.hzs.common.domain.member.detail.ext.CuMemberAwardsExt;
import com.hzs.common.domain.member.ext.CuMemberAccountExt;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.sale.ext.*;
import com.hzs.common.domain.sale.order.*;
import com.hzs.common.domain.sale.product.BdProduct;
import com.hzs.common.domain.sale.wares.BdWares;
import com.hzs.common.domain.sale.wares.BdWaresExtend;
import com.hzs.common.domain.sale.wares.BdWaresMemberLimit;
import com.hzs.common.domain.system.base.BdCountry;
import com.hzs.common.domain.system.base.ext.BdProductStorehouseExt;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.common.domain.third.pay.ext.TOnlineRefundExt;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.account.IMemberAccountServiceApi;
import com.hzs.member.account.IMemberTradeServiceApi;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.account.dto.MemberAmountDTO;
import com.hzs.member.achieve.IMemberAchieveServiceApi;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.member.detail.ICuMemberDetailServiceApi;
import com.hzs.member.detail.ICuMemberServiceLogServiceApi;
import com.hzs.sale.deliver.param.DeliverSecondParam;
import com.hzs.sale.deliver.service.ISaDeliverItemsService;
import com.hzs.sale.deliver.vo.DeliverSecondVO;
import com.hzs.sale.order.dto.OrderQueryChargeDTO;
import com.hzs.sale.order.mapper.SaOrderMapper;
import com.hzs.sale.order.param.*;
import com.hzs.sale.order.service.*;
import com.hzs.sale.order.vo.*;
import com.hzs.sale.product.service.IBdProductExtendService;
import com.hzs.sale.product.service.IBdProductService;
import com.hzs.sale.wares.service.*;
import com.hzs.system.base.IAreaServiceApi;
import com.hzs.system.base.ICountryServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.ISystemConfigServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IAreaCurrencyServiceApi;
import com.hzs.system.config.IAwardsServiceApi;
import com.hzs.system.config.ICuMemberAgreementWhiteApi;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.AreaCurrencyDTO;
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 com.hzs.third.sms.ISmsServiceApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 订单的逻辑类
 */
@Service
@Slf4j
public class SaOrderServiceImpl extends ServiceImpl<SaOrderMapper, SaOrder> implements ISaOrderService {

    @DubboReference
    IMemberServiceApi iMemberServiceApi;
    @DubboReference
    IGradeServiceApi iGradeServiceApi;
    @DubboReference
    IAwardsServiceApi iAwardsServiceApi;
    @DubboReference
    IAreaServiceApi iAreaServiceApi;
    @DubboReference
    IMemberAccountServiceApi iMemberAccountServiceApi;
    @DubboReference
    IAreaCurrencyServiceApi iAreaCurrencyServiceApi;
    @DubboReference
    ICountryServiceApi iCountryServiceApi;
    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;
    @DubboReference
    IApprovalServiceApi iApprovalServiceApi;
    @DubboReference
    IMemberAchieveServiceApi iMemberAchieveServiceApi;
    @DubboReference
    ISystemConfigServiceApi iSystemConfigServiceApi;
    @DubboReference
    ICuMemberServiceLogServiceApi iCuMemberServiceLogServiceApi;
    @DubboReference
    IMemberTradeServiceApi iMemberTradeServiceApi;
    @DubboReference
    ICuMemberDetailServiceApi iCuMemberDetailServiceApi;
    @DubboReference
    ICuMemberAgreementWhiteApi cuMemberAgreementWhiteApi;
    @DubboReference
    ISmsServiceApi iSmsServiceApi;

    @Autowired
    private IBdWaresService iBdWaresService;
    @Autowired
    private IBdWaresExtendService iBdWaresExtendService;
    @Autowired
    private SaOrderHandle saOrderHandle;
    @Autowired
    private ISaOrderItemsService iSaOrderItemsService;
    @Autowired
    private IBdProductService iBdProductService;
    @Autowired
    private IBdProductExtendService iBdProductExtendService;
    @Autowired
    private IBdWaresSpecsRelationService iBdWaresSpecsRelationService;
    @Autowired
    private ISaDeliverItemsService iSaDeliverItemsService;
    @Autowired
    private IAcPickService iAcPickService;
    @Autowired
    private IOrderBusinessService iOrderBusinessService;
    @Autowired
    private ISaOrderChargeLogService iSaOrderChargeLogService;
    @Autowired
    private IBdWaresMemberLimitService iBdWaresMemberLimitService;
    @Autowired
    private ISaOrderSyncService iSaOrderSyncService;

    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public List<CuMemberExt> queryMemberExtByCondition(CuMember cuMember) {
        return iMemberServiceApi.getMemberInfo(cuMember).getData();
    }

    @Override
    public List<CuMemberExt> querySponsorOnUmbrella(Long placeParentId, String phone) {
        return iMemberServiceApi.querySponsorOnUmbrella(placeParentId, null, phone).getData();
    }

    @Override
    public List<CuMemberExt> selectPlaceSponsorUnderUmbrellaByCondition(Long memberId, List<CuMemberExt> cuMemberExtList) {
        return iMemberServiceApi.selectPlaceSponsorUnderUmbrellaByCondition(memberId, cuMemberExtList).getData();
    }

    @Override
    public List<CuMemberExt> queryPlaceSponsorUnderUmbrella(Long memberId, String placeParent) {
        return iMemberServiceApi.queryPlaceSponsorUnderUmbrella(memberId, placeParent).getData();
    }

    @Override
    public CuMemberExt queryPlaceSponsorLastLeft(Long memberId, Integer placeDept) {
        return iMemberServiceApi.queryPlaceSponsorLastLeft(memberId, placeDept).getData();
    }

    @Override
    public SaOrder querySaleOrderByOrderCode(SaOrder saOrder) {
        LambdaQueryWrapper<SaOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SaOrder::getOrderStatus, saOrder.getOrderStatus());
        queryWrapper.eq(SaOrder::getOrderCode, saOrder.getOrderCode());
        if (saOrder.getPkCountry() != null) {
            queryWrapper.eq(SaOrder::getPkCountry, saOrder.getPkCountry());
        }
        if (saOrder.getOrderType() != null) {
            queryWrapper.eq(SaOrder::getOrderType, saOrder.getOrderType());
        }
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public SaOrderExt querySaleOrderExtByOrderCode(SaOrder saOrder, List<Long> itemIdList) {
        SaOrder order = querySaleOrderByOrderCode(saOrder);
        if (order == null) {
            return null;
        }
        SaOrderExt saOrderExt = BeanUtil.copyProperties(order, SaOrderExt.class);
        LambdaQueryWrapper<SaOrderItems> orderItemsQueryWrapper = new LambdaQueryWrapper<>();
        orderItemsQueryWrapper.eq(SaOrderItems::getPkOrder, saOrderExt.getPkId());
        if (CollectionUtil.isNotEmpty(itemIdList)) {
            orderItemsQueryWrapper.in(SaOrderItems::getPkId, itemIdList);
        }
        saOrderExt.setOrderItemsList(iSaOrderItemsService.list(orderItemsQueryWrapper));
        return saOrderExt;
    }

    @Override
    public List<SaOrder> querySaleOrderByPkMember(Integer pkCountry, Long pkMember, List<Integer> orderTypeList, List<Integer> notOrderType) {
        LambdaQueryWrapper<SaOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SaOrder::getOrderStatus, EOrderStatus.PAY.getValue());
        queryWrapper.eq(SaOrder::getPkCountry, pkCountry);
        if (pkMember != null) {
            queryWrapper.eq(SaOrder::getPkMember, pkMember);
        }
        if (CollectionUtil.isNotEmpty(orderTypeList)) {
            queryWrapper.in(SaOrder::getOrderType, orderTypeList);
        }
        if (CollectionUtil.isNotEmpty(notOrderType)) {
            queryWrapper.notIn(SaOrder::getOrderType, notOrderType);
        }
        queryWrapper.orderByDesc(SaOrder::getPayTime);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public Integer querySaleOrderByPkMember(Integer pkCountry, Long pkMember, List<Integer> notTypeList) {
        LambdaQueryWrapper<SaOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SaOrder::getOrderStatus, EOrderStatus.PAY.getValue());
        queryWrapper.eq(SaOrder::getPkCountry, pkCountry);
        if (pkMember != null) {
            queryWrapper.eq(SaOrder::getPkMember, pkMember);
        }
        if (CollectionUtil.isNotEmpty(notTypeList)) {
            queryWrapper.notIn(SaOrder::getOrderType, notTypeList);
        }
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public Integer queryCuMemberByPkMember(Long pkReference) {
        return iMemberServiceApi.queryCuMemberByPkMember(pkReference).getData();
    }

    @Override
    public List<SaOrderVO> querySaleOrderByCondition(OrderQueryParam orderQueryParam) {
        if (orderQueryParam.getEndTime() != null) {
            orderQueryParam.setEndTime(DateUtils.afterDate(1, ChronoUnit.DAYS, orderQueryParam.getEndTime()));
        }
        List<SaOrderVO> saOrderVOList = baseMapper.querySaOrderByCondition(orderQueryParam);
        saOrderVOList.forEach(saOrder -> saOrderHandle.transformSaOrderToVO(saOrder));
        return saOrderVOList;
    }

    @Override
    public CuMember getCuMemberByKey(Long pkId) {
        return iMemberServiceApi.getMemberById(pkId).getData();
    }

    @Override
    public CuMember getCuMemberByCode(String code) {
        return iMemberServiceApi.getMemberByCode(code).getData();
    }

    @Override
    public Boolean lockKey(String key) {
        return redisService.lockKeyOnce(key);
    }

    @Override
    public CuMemberAccountExt queryOrderSpendDetails(CuMemberAccountExt cuMemberAccount, SaOrder saOrder, List<SaOrderItems> orderItemList) {
        BigDecimal payMoney = saOrder.getOrderAmount();

        // 订单创建人
        CuMember creator = getCuMemberByKey(saOrder.getPkCreator());
        cuMemberAccount.setMemberCode(creator.getMemberCode());

        // 查询专区所属币种
        List<AreaCurrencyDTO> areaCurrencyDTOListOld = iAreaCurrencyServiceApi.queryAreaCurrencyByCondition(saOrder.getOrderType(), cuMemberAccount.getPkCountry()).getData();
        List<AreaCurrencyDTO> areaCurrencyDTOList = areaCurrencyDTOListOld;
        if (cuMemberAccount.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
            //休止期的奖金账户(不在白名单内)不允许报单
            Integer expireStatus = creator.getExpireStatus();
            if (expireStatus.equals(EExpireStatus.REST.getValue())) {
                //查询配置是否休止期可以报单
                Integer num = cuMemberAgreementWhiteApi.selectAgreementWhiteByPkMember(creator.getPkId()).getData();
                if (num == null || num == 0) {
                    areaCurrencyDTOList = areaCurrencyDTOListOld.stream().filter(item -> !item.getFieldValue().equals(EAccount.BONUS.getValue())).collect(Collectors.toList());
                }
            }
        }

        if (!ComputeUtil.compareValue(payMoney)) {
            cuMemberAccount.setIsPayment(Boolean.TRUE);
        }

        // 个人政策币配置，政策币个人配置优先特殊配置
        UpPolicyCurrency upPolicyCurrency = null;
        if (EOrderType.REGISTER_ORDER.getValue() == saOrder.getOrderType()
                || EOrderType.UPGRADE_ORDER.getValue() == saOrder.getOrderType()) {
            upPolicyCurrency = iCuMemberServiceLogServiceApi.queryMaxCuMemberServiceLog(cuMemberAccount.getPkMember(), Collections.singletonList(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue())).getData();
        }

        // 验证商品是否存在特殊消费配置
        if (CollectionUtil.isNotEmpty(orderItemList)) {
            for (SaOrderItems saOrderItems : orderItemList) {
                if (saOrderItems.getPkSpecialCurrency() != null) {
                    BigDecimal orderItemPayMoney = ComputeUtil.computeMultiply(saOrderItems.getPrice(), saOrderItems.getQuantity());
                    payMoney = ComputeUtil.computeSubtract(payMoney, orderItemPayMoney);
                    List<AreaCurrencyDTO> areaCurrencyDtoList = iAreaCurrencyServiceApi.queryAreaCurrencyByCondition(saOrderItems.getPkSpecialCurrency()).getData();

                    if (!handleSaOrderAmount(upPolicyCurrency, cuMemberAccount, orderItemPayMoney, BigDecimal.ZERO, saOrder.getOrderTypeExtend(), areaCurrencyDtoList)) {
                        return null;
                    }
                }
            }
        }

        handleSaOrderAmount(upPolicyCurrency, cuMemberAccount, payMoney, saOrder.getPostage(), saOrder.getOrderTypeExtend(), areaCurrencyDTOList);

        if (null != cuMemberAccount.getPayAccount5() && cuMemberAccount.getPayAccount5().compareTo(BigDecimal.ZERO) > 0) {
            // 2024.09.24 重消专区可以使用其它币种，此处只记录重消币，其它币种需要单独计算统计
            saOrder.setConsumeAmount(cuMemberAccount.getPayAccount5());
        }

        return cuMemberAccount;
    }

    @Override
    public List<CuMemberAccountExt> queryMemberAccountByCondition(CuMemberAccount cuMemberAccount) {
        return iMemberAccountServiceApi.queryMemberAccountByCondition(cuMemberAccount).getData();
    }

    private Boolean handleSaOrderAmount(UpPolicyCurrency upPolicyCurrency, CuMemberAccountExt cuMemberAccount,
                                        BigDecimal payMoney, BigDecimal postage, Integer orderTypeExtend,
                                        List<AreaCurrencyDTO> areaCurrencyDTOList) {
        boolean flag = Boolean.TRUE;
        if (!ComputeUtil.compareValue(ComputeUtil.computeAdd(payMoney, postage))) {
            return Boolean.TRUE;
        }
        cuMemberAccount.setIsPayment(Boolean.FALSE);
        // 原始支付金额（订单金额 + 邮费）
        BigDecimal original = payMoney;

        for (AreaCurrencyDTO areaCurrencyDTO : areaCurrencyDTOList) {
            if (EAccount.POLICY.getValue() == areaCurrencyDTO.getFieldValue()
                    && null != orderTypeExtend
                    && EOrderTypeExtend.REG_REP.getValue() == orderTypeExtend) {
                // 2025.07.17 新需求，注册转复购订单不能使用政策币
                continue;
            }
            // 开始扣款
            // 待支付金额>0进行扣减
            if (ComputeUtil.compareValue(payMoney)) {
                // 获得特殊处理
                // 判断比例是否 > 0, 为强制扣除金额 ，强制扣除金额不满足，直接支付失败
                if (!ComputeUtil.compareValue(areaCurrencyDTO.getDeductRatio())) {
                    // 支付比例为0处理
                    // 最大支付金额
                    if (null != areaCurrencyDTO.getDeductMaxRatio()
                            && areaCurrencyDTO.getDeductMaxRatio().compareTo(BigDecimal.ZERO) > 0) {
                        // 并且有最大支付比例也不为0，则需要进行使用限制
                        areaCurrencyDTO.setDeductMaxRatioAmount(ComputeUtil.computeDivide(original.multiply(areaCurrencyDTO.getDeductMaxRatio()), BigDecimal.valueOf(100)));
                    }
                    payMoney = saOrderHandle.subtract(payMoney, cuMemberAccount, areaCurrencyDTO);
                } else {
                    // 政策币单独处理 政策币需要根据配置来进行处理
                    if (EAccount.POLICY.getValue() == areaCurrencyDTO.getFieldValue()) {
                        // 没有前置特殊政策币处理
                        if (null == areaCurrencyDTO.getSpecialFlag() || !areaCurrencyDTO.getSpecialFlag()) {
                            areaCurrencyDTO.setDeductRatio(BigDecimal.ZERO);
                        }

                        if (upPolicyCurrency != null) {
                            // 如果有政策币则进行处理
                            if (EYesNo.YES.getIntValue() == upPolicyCurrency.getEnableStatus()) {
                                // 启用则取值处理
                                areaCurrencyDTO.setDeductRatio(upPolicyCurrency.getDeductMoney() == null ? areaCurrencyDTO.getDeductRatio() : upPolicyCurrency.getDeductMoney());
                            } else {
                                // 禁用则不能使用
                                areaCurrencyDTO.setDeductRatio(BigDecimal.ZERO);
                            }
                        }
                    } else if (EAccount.CASH.getValue() == areaCurrencyDTO.getFieldValue()) {
                        if (upPolicyCurrency != null) {
                            // 有个人政策币，则不走特殊政策币配置的现金币比例
                            areaCurrencyDTO.setDeductRatio(areaCurrencyDTO.getOriginalDeductRatio());
                        }
                    }

                    // 最小支付金额
                    BigDecimal minPayMoney = ComputeUtil.computeDivide(original.multiply(areaCurrencyDTO.getDeductRatio()), BigDecimal.valueOf(100));
                    BigDecimal accountValue = saOrderHandle.getAccountByKey(cuMemberAccount, areaCurrencyDTO.getFieldValue());
                    if (EAccount.POLICY.getValue() != areaCurrencyDTO.getFieldValue()) {
                        // 不是政策币
                        if (minPayMoney.compareTo(accountValue) > 0) {
                            flag = false;
                            if (cuMemberAccount.getErrorMsg() == null) {
                                cuMemberAccount.setErrorMsg(areaCurrencyDTO.getAccountName() + TransactionUtils.getContent(MemberMsgConstants.MEMBER_ACCOUNT_BALANCE_NOT_ENOUGH));
                            } else {
                                cuMemberAccount.setErrorMsg(cuMemberAccount.getErrorMsg() + areaCurrencyDTO.getAccountName() + MemberMsgConstants.MEMBER_ACCOUNT_BALANCE_NOT_ENOUGH);
                            }
                        }
                    } else {
                        // 政策币
                        if (minPayMoney.compareTo(accountValue) > 0) {
                            minPayMoney = accountValue;
                        }
                    }
                    BigDecimal originalPayMoney = ReflectUtils.invokeGetter(cuMemberAccount, MemberFieldConstants.PAY_ACCOUNT + areaCurrencyDTO.getFieldValue());
                    if (originalPayMoney == null) {
                        originalPayMoney = BigDecimal.ZERO;
                    }
                    ReflectUtils.invokeSetter(cuMemberAccount, MemberFieldConstants.PAY_ACCOUNT + areaCurrencyDTO.getFieldValue(), ComputeUtil.computeAdd(originalPayMoney, minPayMoney));
                    payMoney = payMoney.subtract(minPayMoney);
                }
                // 奖金币单独处理 消费的时候不需要处理，等实际扣款的时候需要处理，先扣除可提现，在扣除可消费
            }
            // 对邮费进行单独处理 邮费>0 进行扣减
            if (areaCurrencyDTO.getIsPostage() != null && areaCurrencyDTO.getIsPostage() == EYesNo.YES.getIntValue() && postage.compareTo(BigDecimal.ZERO) > 0) {
                postage = saOrderHandle.subtract(postage, cuMemberAccount, areaCurrencyDTO);
            }
            // 每次扣除后判断是否扣除完毕，扣除完毕结束
            if (flag && payMoney.compareTo(BigDecimal.ZERO) == 0 && postage.compareTo(BigDecimal.ZERO) == 0) {
                cuMemberAccount.setIsPayment(Boolean.TRUE);
                break;
            }
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean confirmRegSaOrderByOrderParam(OrderParam orderParam) {
        boolean isToBePay = getIsToBePayByOrderType(orderParam.getPkSettleCountry(), orderParam.getSpecialArea());
        CuMember cuMember = saOrderHandle.packageSaveUser(orderParam, iMemberServiceApi.queryMember(orderParam.getCenterCodeId()).getData());

        if (!EOrderTypeExtend.REG_REP.getValue().equals(orderParam.getOrderTypeExtend())) {
            // 非0元需要获取会员编号、会员主键
            // 获取会员编号、会员主键
            if (isToBePay) {
                cuMember = iMemberServiceApi.createMemberIdAndCode(cuMember, Boolean.FALSE).getData();
            } else if (EOrderType.REGISTER_ORDER.getValue() == orderParam.getSpecialArea()
                    || EOrderType.SPECIAL_REGISTER_ORDER.getValue() == orderParam.getSpecialArea()) {
                // 2023.10.16按最新需求，注册订单需要在支付前需要显示会员编号
                cuMember = iMemberServiceApi.createRegisterMemberCode(cuMember).getData();
            }
        }

        SaOrderExt saOrderExt = packageWholeSaOrder(orderParam, cuMember);
        // 设置会员等级
        if (setLastCuMemberGrade(cuMember, saOrderExt)) {
            return false;
        }
        // cabbage 这个位置的订单只用于注册订单确认，支付单独有别的地方处理
        if (null != cuMember.getPkSettleGradeValue()
                && EGrade.HAI_FAN.getValue() == cuMember.getPkSettleGradeValue()) {
            // 最终等级是顾客，就是需要注册转复购订单
            saOrderExt.setOrderTypeExtend(EOrderTypeExtend.REG_REP.getValue());
        }

        // 保存 用户、订单、订单明细 分布式事务
        // 启用待支付，或者海粉订单
        if (isToBePay && !orderParam.getIsHaiFun()) {
            processOrder(saOrderExt);
            // 调用其他服务保存会员信息、会员注册信息
            R<Boolean> saveResult = iMemberServiceApi.saveMember(cuMember);
            if (saveResult.isSuccess()) {
                if (!saveResult.getData()) {
                    log.error("confirmRegSaOrderByOrderParam 保存会员失败.");
                    throw new RuntimeException("保存会员失败.");
                }
            } else {
                log.error("confirmRegSaOrderByOrderParam 保存会员失败. {}", saveResult.getMsg());
                throw new RuntimeException("保存会员失败.");
            }
        } else {
            redisService.setCacheObject(CacheConstants.TEMP_ORDER + orderParam.getCenterCodeId() + orderParam.getOrderCode(), saOrderExt, CacheConstants.MEMBER_REFRESH_TIME, TimeUnit.MINUTES);
            orderParam.setMemberCode(cuMember.getMemberCode());
            orderParam.setPkGrade(cuMember.getPkSettleGrade());
        }
        redisService.setCacheObject(CacheConstants.TEMP_PARAM + orderParam.getCenterCodeId() + orderParam.getOrderCode(), orderParam, CacheConstants.WARES_REFRESH_TIME, TimeUnit.DAYS);
        return true;
    }

    @Override
    public SaOrderExt packageSaOrder(OrderParam orderParam, CuMember cuMember) {
        SaOrderExt saOrderExt = packageWholeSaOrder(orderParam, cuMember);
        if (setLastCuMemberGrade(cuMember, saOrderExt)) {
            return null;
        }
        // cabbage 这个位置的订单只用于注册订单支付，支付这个处理和确认不是一个地方
        if (null != cuMember.getPkSettleGradeValue()
                && EGrade.HAI_FAN.getValue() == cuMember.getPkSettleGradeValue()) {
            // 最终等级是顾客，就是需要注册转复购订单
            saOrderExt.setOrderTypeExtend(EOrderTypeExtend.REG_REP.getValue());
        }
        return saOrderExt;
    }

    @Override
    public CuMember packageCuMember(OrderParam orderParam) {
        if (null != orderParam.getPkParent()) {
            orderParam.setParentId(orderParam.getPkParent());
        } else {
            if (StringUtils.isNotEmpty(orderParam.getParent())) {
                CuMember parentMember = getCuMemberByCode(orderParam.getParent());
                if (parentMember != null) {
                    orderParam.setParentId(parentMember.getPkId());
                }
            }
        }

        if (StringUtils.isNotEmpty(orderParam.getPlaceParent())) {
            CuMember placeMember = getCuMemberByCode(orderParam.getPlaceParent());
            if (placeMember != null) {
                orderParam.setPlaceParentId(placeMember.getPkId());
            }
        }
        CuMember cuMember = saOrderHandle.packageSaveUser(orderParam, iMemberServiceApi.queryMember(orderParam.getCenterCodeId()).getData());
        // 获取会员编号、会员主键
        cuMember = iMemberServiceApi.createMemberIdAndCode(cuMember, Boolean.FALSE).getData();
        return cuMember;
    }

    @Override
    public Boolean setLastCuMemberGrade(CuMember cuMember, SaOrder saOrderExt) {
        OrderReturn orderReturn = OrderReturn.builder().isEnough(false).build();
        GradeDTO gradeDTO = calculateGradeDTO(saOrderExt.getOrderType(), cuMember.getPkSettleCountry(), cuMember.getPkId(), saOrderExt, orderReturn);

        // 第二次封装用户 封装等级
        if (gradeDTO == null) {
            return true;
        }

        // 验证推荐等级，判断什么级别可以推荐什么级别
        if (EOrderType.REGISTER_ORDER.getValue() == saOrderExt.getOrderType()) {
            if (!EOrderTypeExtend.REG_REP.getValue().equals(saOrderExt.getOrderTypeExtend())) {
                // 判断推荐范围，验证该推荐人是否有推荐的权限
                CuMember parentCuMember = getCuMemberByKey(cuMember.getPkParent());

                if (parentCuMember.getPkSettleCountry() != null && cuMember.getPkSettleCountry() != null && Objects.equals(parentCuMember.getPkSettleCountry(), cuMember.getPkSettleCountry())) {
                    GradeDTO validateGradeDTO = queryGradeConfigByCondition(parentCuMember.getPkSettleCountry(), parentCuMember.getPkSettleGrade());
                    // 获取推荐人可以推荐的等级
                    if (validateGradeDTO == null || validateGradeDTO.getBdGradeScopeExtList() == null ||
                            validateGradeDTO.getBdGradeScopeExtList().stream().noneMatch(bdGradeScope -> gradeDTO.getPkId().equals(bdGradeScope.getPkScope()))) {
                        return true;
                    }
                }
            }
        }

        Integer pkAwards = cuMember.getPkAwards();
        cuMember.setPkRegisterGrade(gradeDTO.getPkId());
        cuMember.setPkSettleGrade(gradeDTO.getPkId());
        cuMember.setPkSettleGradeValue(gradeDTO.getGradeValue());

        if (EOrderType.REGISTER_ORDER.getValue() == saOrderExt.getOrderType()
                || EOrderType.UPGRADE_ORDER.getValue() == saOrderExt.getOrderType()) {
            // 2025.05.13 新添加需求，开网初期报单660给1980等级，报单1980给9900等级
            if (EGrade.YOU_KE.getValue() == gradeDTO.getGradeValue()) {
                GradeDTO newGradeDTO = iGradeServiceApi.getGradeByGradeValue(EGrade.MAKER.getValue(), saOrderExt.getPkCountry()).getData();
                if (null != newGradeDTO) {
                    cuMember.setPkSettleGrade(newGradeDTO.getPkId());
                    cuMember.setPkSettleGradeValue(newGradeDTO.getGradeValue());
                }
            } else if (EGrade.MAKER.getValue() == gradeDTO.getGradeValue()) {
                GradeDTO newGradeDTO = iGradeServiceApi.getGradeByGradeValue(EGrade.VIP.getValue(), saOrderExt.getPkCountry()).getData();
                if (null != newGradeDTO) {
                    cuMember.setPkSettleGrade(newGradeDTO.getPkId());
                    cuMember.setPkSettleGradeValue(newGradeDTO.getGradeValue());
                }
            }
        }

        // 判断奖衔，原会员有奖衔的话判断哪个大，使用大的
        if (pkAwards != null && gradeDTO.getGradeValue() != null) {
            BdAwards bdAwards = iAwardsServiceApi.getAwardsOne(pkAwards).getData();
            BdAwards newAwards = iAwardsServiceApi.getAwardsOne(gradeDTO.getPkAwards()).getData();
            if (bdAwards.getAwardsValue() < newAwards.getAwardsValue()) {
                cuMember.setPkAwards(gradeDTO.getPkAwards());
            }
        } else {
            cuMember.setPkAwards(gradeDTO.getPkAwards());
        }
        // 等级对应的结算值
        cuMember.setConsumeMoney(saOrderExt.getOrderAmount());
        if (EGrade.HAI_FAN.getValue() == gradeDTO.getGradeValue()) {
            // 顾客注册会员显示订单业绩
            cuMember.setConsumeAchieve(saOrderExt.getOrderAchieve());
        } else {
            cuMember.setConsumeAchieve(gradeDTO.getStartValue());
        }
        if (cuMember.getRegisterAuthority() == null || cuMember.getRegisterAuthority() < gradeDTO.getRegisterAuthority()) {
            cuMember.setRegisterAuthority(gradeDTO.getRegisterAuthority());
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void processOrder(SaOrderExt saOrderExt) {
        // 待支付直接保存订单、会员
        // 保存订单
        save(saOrderExt);
        saOrderExt.getOrderItemsList().forEach(saOrderItems -> {
            saOrderItems.setPkOrder(saOrderExt.getPkId());
        });
        // 保存订单明细
        iSaOrderItemsService.saveBatch(saOrderExt.getOrderItemsList());

//        // 更新销量
//        // 将订单表主键封装为明细表主键
//        List<WaresNumberParam> waresNumberParamList = new ArrayList<>();
//        saOrderExt.getOrderItemsList().forEach(saOrderItems -> {
//            saOrderItems.setPkOrder(saOrderExt.getPkId());
//            if (saOrderItems.getPkWares() != null && saOrderItems.getPkWares() != 0) {
//                // 换货或者二次发货等，商品为0，则不需要处理
//                waresNumberParamList.add(WaresNumberParam.builder().pkWares(saOrderItems.getPkWares()).number(saOrderItems.getWaresQuantity()).build());
//            }
//        });
//        // 过滤相同商品主键数据
//        List<WaresNumberParam> waresNumberList = waresNumberParamList.stream().filter(DeduplicationUtil.distinctByKey(WaresNumberParam::getPkWares)).collect(Collectors.toList());
//        waresSalesAccrual(waresNumberList);
    }

    @Override
    public boolean getIsToBePayByOrderType(Integer pkCountry, Integer specialArea) {
        String confirmPay;
        if (EOrderType.REGISTER_ORDER.getValue() == specialArea || EOrderType.SPECIAL_REGISTER_ORDER.getValue() == specialArea) {
            confirmPay = querySystemConfigByKey(pkCountry, ESystemConfig.REGISTER_ORDER_CONFIRM_PAY.getKey());
        } else if (EOrderType.UPGRADE_ORDER.getValue() == specialArea || EOrderType.SPECIAL_UPGRADE_ORDER.getValue() == specialArea) {
            confirmPay = querySystemConfigByKey(pkCountry, ESystemConfig.UPGRADE_ORDER_CONFIRM_PAY.getKey());
        } else if (EOrderType.REPURCHASE_ORDER.getValue() == specialArea || EOrderType.SPECIAL_REPURCHASE_ORDER.getValue() == specialArea
                || EOrderType.MALL_ORDER.getValue() == specialArea) {
            confirmPay = querySystemConfigByKey(pkCountry, ESystemConfig.REPURCHASE_ORDER_CONFIRM_PAY.getKey());
        } else if (EOrderType.PICK_ORDER.getValue() == specialArea) {
            // 提货没有待支付
            confirmPay = ESystemConfig.PICK_ORDER_CONFIRM_PAY.getValue();
        } else if (EOrderType.CONSUME_ORDER.getValue() == specialArea) {
            confirmPay = querySystemConfigByKey(pkCountry, ESystemConfig.CONSUME_ORDER_CONFIRM_PAY.getKey());
        } else {
            confirmPay = querySystemConfigByKey(pkCountry, ESystemConfig.REPURCHASE_ORDER_CONFIRM_PAY.getKey());
        }
        boolean isToBePay = false;
        // 启用待支付
        if (EYesNo.YES.getIntValue() == Integer.parseInt(confirmPay)) {
            log.info("增加待支付");
            isToBePay = true;
        }
        return isToBePay;
    }

    @Override
    public Long getIsToBePayTime(Integer pkCountry, Integer specialArea) {
        String timeType;
        long timeSecond = 0L;
        if (getIsToBePayByOrderType(pkCountry, specialArea)) {
            if (EOrderType.REGISTER_ORDER.getValue() == specialArea) {
                timeType = querySystemConfigByKey(pkCountry, ESystemConfig.REGISTER_ORDER_TIME.getKey());
            } else if (EOrderType.UPGRADE_ORDER.getValue() == specialArea) {
                timeType = querySystemConfigByKey(pkCountry, ESystemConfig.UPGRADE_ORDER_TIME.getKey());
            } else if (EOrderType.REPURCHASE_ORDER.getValue() == specialArea) {
                timeType = querySystemConfigByKey(pkCountry, ESystemConfig.REPURCHASE_ORDER_TIME.getKey());
            } else if (EOrderType.PICK_ORDER.getValue() == specialArea) {
                timeType = querySystemConfigByKey(pkCountry, ESystemConfig.PICK_ORDER_TIME.getKey());
            } else if (EOrderType.CONSUME_ORDER.getValue() == specialArea) {
                timeType = querySystemConfigByKey(pkCountry, ESystemConfig.CONSUME_ORDER_TIME.getKey());
            } else {
                timeType = querySystemConfigByKey(pkCountry, ESystemConfig.REGISTER_ORDER_TIME.getKey());
            }
            // 12小时
            timeSecond = 12 * MagicNumberConstants.HOUR_SECOND;
            if (ESpecialAreaTime.TWENTY_FOUR_HOUR.getValue().equals(timeType)) {
                timeSecond = timeSecond * 2;
            } else if (ESpecialAreaTime.FORTY_EIGHT_HOUR.getValue().equals(timeType)) {
                timeSecond = timeSecond * 4;
            }
        }
        return timeSecond;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean payRegSaOrder(SaOrderExt saOrderExt, CuMember newCuMember,
                                 CuMemberAccountExt cuMemberAccountExt, Boolean isHaiFun) {
        boolean isToBePay = getIsToBePayByOrderType(newCuMember.getPkSettleCountry(), saOrderExt.getOrderType());
        Date currentDateTime = DateUtils.currentDateTime();
        Long pkCreator = saOrderExt.getPkCreator();
        newCuMember.setPayStatus(EPayStatus.PAID.getValue());
        newCuMember.setPayTime(currentDateTime);
        saOrderExt.setPayTime(currentDateTime);
        saOrderExt.setOrderStatus(EOrderStatus.PAY.getValue());

        if (isToBePay && !isHaiFun) {
            // 根据业绩判断自动上树 -- 目前使用
            newCuMember.setPkModified(pkCreator);
            newCuMember.setModifiedTime(currentDateTime);
            saOrderExt.setPkModified(pkCreator);
            saOrderExt.setModifiedTime(currentDateTime);
            for (SaOrderItems saOrderItems : saOrderExt.getOrderItemsList()) {
                saOrderItems.setPkModified(pkCreator);
                saOrderItems.setModifiedTime(currentDateTime);
                saOrderItems.setOrderStatus(EOrderStatus.PAY.getValue());
            }

            // 更新订单信息
            updateSaOrder(saOrderExt);
        } else {
            newCuMember.setConsumeMoney(BigDecimal.ZERO);
            newCuMember.setConsumeAchieve(BigDecimal.ZERO);
            if (setLastCuMemberGrade(newCuMember, saOrderExt)) {
                return false;
            }
            if (isHaiFun) {
                if (null == newCuMember.getPkPlaceParent()
                        || null == newCuMember.getPlaceDept()) {
                    // 2024.01.13 当安置人和安置部门为空时，则进行重新上树
                    CuMember cuMember = repeatTry(newCuMember, Boolean.FALSE);
                    newCuMember.setPkPlaceParent(cuMember.getPkPlaceParent());
                    newCuMember.setPlaceDept(cuMember.getPlaceDept());
                }
                isToBePay = false;
            }
            newCuMember.setCreationTime(currentDateTime);
            saOrderExt.setCreationTime(currentDateTime);

            for (SaOrderItems saOrderItems : saOrderExt.getOrderItemsList()) {
                saOrderItems.setCreationTime(saOrderExt.getCreationTime());
                saOrderItems.setOrderStatus(EOrderStatus.PAY.getValue());
            }

            // 2025.07.15 顾客等级的注册订单类型，需要更新为复购订单
            GradeDTO gradeDTO = iGradeServiceApi.getGrade(newCuMember.getPkRegisterGrade()).getData();
            if (EGrade.HAI_FAN.getValue() == gradeDTO.getGradeValue()) {
                saOrderExt.setOrderType(EOrderType.REPURCHASE_ORDER.getValue());
                // 注册 转 复购 补一下特殊订单类型，后面好处理撤单使用
                saOrderExt.setOrderTypeExtend(EOrderTypeExtend.REG_REP.getValue());
            }

            // 保存订单信息
            processOrder(saOrderExt);
        }

        // 2024.05.29 会员续约需求，【有效期】为购买时间次年的上月最后一天
        newCuMember.setExpireDate(DateUtils.beforeMonthLastDate(DateUtils.addYears(currentDateTime, 1)));
        // 【休止期】普通会员6个月，奖衔会员12个月（先按6个月来，后续MQ会统一处理同姓名同手机号会员）
        newCuMember.setStopDate(DateUtils.addMonths(newCuMember.getExpireDate(), 6));

        // 调用其他服务保存会员信息、会员注册信息
        R<Boolean> saveResult = iMemberServiceApi.saveMember(newCuMember, saOrderExt, isToBePay, cuMemberAccountExt);
        if (saveResult.isSuccess()) {
            if (!saveResult.getData()) {
                log.error("payRegSaOrder 保存会员失败!.");
                throw new RuntimeException("保存会员失败!.");
            }
        } else {
            log.error("payRegSaOrder 保存会员失败!.，{}", saveResult.getMsg());
            throw new RuntimeException("保存会员失败!.");
        }

        try {
            // 同步全网产品库存
            this.allProductSync(saOrderExt);

            log.info("生产活动消息，activity.exchange：{}", JSONUtil.toJsonStr(saOrderExt));
            rabbitTemplate.convertAndSend(RabbitMqConstants.ACTIVITY_EXCHANGE, RabbitMqConstants.ACTIVITY_KEY, saOrderExt);
            // 推送秒结数据处理 -- 注册订单
            rabbitTemplate.convertAndSend(RabbitMqConstants.ORDER_SECOND_EXCHANGE, RabbitMqConstants.ORDER_SECOND_KEY, saOrderExt);

            // 发送会员注册成功短信
            iSmsServiceApi.sendMemberRegister(newCuMember.getPhone(), EAliSmsTemplate.MEMBER_REGISTER,
                    newCuMember.getMemberCode(), newCuMember.getLoginPassword(), newCuMember.getPayPassword());

//            if (EOrderType.REGISTER_ORDER.getValue() == saOrderExt.getOrderType()) {
//                // 推送会员续约处理MQ
//                rabbitTemplate.convertAndSend(RabbitMqConstants.MEMBER_CONTINUE_EXCHANGE, RabbitMqConstants.MEMBER_CONTINUE_KEY,
//                        MemberContinueDTO.builder()
//                                .pkMemberList(Collections.singletonList(saOrderExt.getPkMember()))
//                                .eMemberContinue(EMemberContinue.REGISTER_ORDER)
//                                .build());
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Boolean.TRUE;
    }

    private boolean payReyZeroOrder(SaOrderExt saOrderExt, CuMember newCuMember) {
        Date currentDateTime = DateUtils.currentDateTime();
        newCuMember.setPayStatus(EPayStatus.PAID.getValue());
        newCuMember.setPayTime(currentDateTime);
        newCuMember.setConsumeMoney(saOrderExt.getOrderAmount());
        newCuMember.setConsumeAchieve(saOrderExt.getOrderAchieve());
        // 会员续约需求，【有效期】为购买时间次年的上月最后一天
        newCuMember.setExpireDate(DateUtils.beforeMonthLastDate(DateUtils.addYears(currentDateTime, 1)));
        // 【休止期】普通会员6个月，奖衔会员12个月（先按6个月来，后续MQ会统一处理同姓名同手机号会员）
        newCuMember.setStopDate(DateUtils.addMonths(newCuMember.getExpireDate(), 6));

        if (null == newCuMember.getPkPlaceParent()
                || null == newCuMember.getPlaceDept()) {
            // 当安置人和安置部门为空时，进行上树
            CuMember cuMember = repeatTry(newCuMember, Boolean.FALSE);
            newCuMember.setPkPlaceParent(cuMember.getPkPlaceParent());
            newCuMember.setPlaceDept(cuMember.getPlaceDept());
        }

        saOrderExt.setOrderType(EOrderType.REPURCHASE_ORDER.getValue());
        saOrderExt.setOrderTypeExtend(EOrderTypeExtend.REG_REP.getValue());
        saOrderExt.setPkPlacement(newCuMember.getPkPlaceParent());
        saOrderExt.setOrderStatus(EOrderStatus.PAY.getValue());
        saOrderExt.setPayTime(currentDateTime);
        saOrderExt.setCreationTime(currentDateTime);
        for (SaOrderItems saOrderItems : saOrderExt.getOrderItemsList()) {
            saOrderItems.setCreationTime(saOrderExt.getCreationTime());
            saOrderItems.setOrderStatus(EOrderStatus.PAY.getValue());
            saOrderItems.setPkGrade(newCuMember.getPkSettleGrade());
        }
        // 保存订单信息
        processOrder(saOrderExt);

        // 调用其他服务保存会员信息、会员注册信息
        R<Boolean> handleResult = iMemberServiceApi.handleZeroMember(newCuMember, saOrderExt);
        if (handleResult.isSuccess()) {
            if (!handleResult.getData()) {
                log.error("payReyZeroOrder 保存会员失败!.");
                throw new RuntimeException("保存会员失败!.");
            }
        } else {
            log.error("payReyZeroOrder 保存会员失败!.，{}", handleResult.getMsg());
            throw new RuntimeException("保存会员失败!.");
        }

        try {
            // 同步全网产品库存
            this.allProductSync(saOrderExt);

            log.info("生产活动消息，activity.exchange：{}", JSONUtil.toJsonStr(saOrderExt));
            rabbitTemplate.convertAndSend(RabbitMqConstants.ACTIVITY_EXCHANGE, RabbitMqConstants.ACTIVITY_KEY, saOrderExt);
            // 推送秒结数据处理 -- 注册订单
            rabbitTemplate.convertAndSend(RabbitMqConstants.ORDER_SECOND_EXCHANGE, RabbitMqConstants.ORDER_SECOND_KEY, saOrderExt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Boolean.TRUE;
    }

    /**
     * 尝试重新换位置
     *
     * @param newCuMember 修改的会员
     */
    private synchronized CuMember repeatTry(CuMember newCuMember, Boolean isFirstAchieve) {
        CuMember cuMember = obtainLastResettleByRecommend(newCuMember, isFirstAchieve, null);
        if (!lockKey(CacheConstants.POSITION + cuMember.getPkPlaceParent() + cuMember.getPlaceDept())) {
            try {
                Thread.sleep(300);
                repeatTry(newCuMember, isFirstAchieve);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return cuMember;
    }

    private void insertSaOrder(SaOrderExt saOrderExt) {
        redisService.lockKeyMany(CacheConstants.MEMBER_ORDER + saOrderExt.getOrderCode());
        try {
            this.save(saOrderExt);
            for (SaOrderItems saOrderItems : saOrderExt.getOrderItemsList()) {
                saOrderItems.setPkOrder(saOrderExt.getPkId());
            }
            iSaOrderItemsService.saveBatch(saOrderExt.getOrderItemsList());
        } finally {
            redisService.unlock(CacheConstants.MEMBER_ORDER + saOrderExt.getOrderCode());
        }
    }

    private void updateSaOrder(SaOrderExt saOrderExt) {
        redisService.lockKeyMany(CacheConstants.MEMBER_ORDER + saOrderExt.getOrderCode());
        try {
            updateById(saOrderExt);
            iSaOrderItemsService.updateBatchById(saOrderExt.getOrderItemsList());
        } finally {
            redisService.unlock(CacheConstants.MEMBER_ORDER + saOrderExt.getOrderCode());
        }
    }

    /**
     * 销售订单更改状态为待支付
     *
     * @param saOrderExt 销售订单
     */
    public void encapsulationSaOrder(SaOrderExt saOrderExt) {
        saOrderExt.setPayTime(new Date());
        saOrderExt.setPkModified(saOrderExt.getPkCreator());
        saOrderExt.setModifiedTime(saOrderExt.getPayTime());
        saOrderExt.setOrderStatus(EOrderStatus.PAY.getValue());
        saOrderExt.getOrderItemsList().forEach(saOrderItems -> {
            saOrderItems.setPkModified(saOrderExt.getPkCreator());
            saOrderItems.setModifiedTime(saOrderExt.getPayTime());
            saOrderItems.setOrderStatus(EOrderStatus.PAY.getValue());
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean payUpgradeSaOrder(SaOrderExt saOrderExt, CuMemberAccountExt cuMemberAccountExt) {
        CuMember cuMember = getCuMemberByKey(saOrderExt.getPkMember());
        GradeDTO oldGradeDTO = iGradeServiceApi.getGrade(cuMember.getPkSettleGrade()).getData();
        // 封装等级,重新计算会员等级
        if (setLastCuMemberGrade(cuMember, saOrderExt)) {
            return false;
        }
        // 验证等级，原等级<新等级，才可以进行升级 或者 累计升级
        String upgradeWay = querySystemConfigByKey(saOrderExt.getPkCountry(), ESystemConfig.UPGRADE_WAY.getKey());
        boolean checkUpgrade = false;
        if (oldGradeDTO.getGradeValue() >= cuMember.getPkSettleGradeValue() && !Objects.equals(Integer.toString(EUpgradeWay.TOTAL.getValue()), upgradeWay)) {
            checkUpgrade = true;
            if (EGrade.VIP.getValue() == oldGradeDTO.getGradeValue()) {
                SaOrderExt gradeOrder = baseMapper.getLastOrderGrade(cuMember.getPkId());
                if (EGrade.MAKER.getValue() == gradeOrder.getGradeValue()) {
                    // 如果是1980赠送升级的9900，可以再买一个9900，但是等级不变
                    checkUpgrade = false;
                }
            }
        }
        if (checkUpgrade) {
            return false;
        }
        // 封装保存订单数据
        encapsulationSaOrder(saOrderExt);

        // 更新订单信息
        updateSaOrder(saOrderExt);
        // 处理会员信息，更新会员等级,扣款
        R<Boolean> saveResult = iMemberServiceApi.saveMember(cuMember, saOrderExt, cuMemberAccountExt);
        if (saveResult.isSuccess()) {
            if (!saveResult.getData()) {
                log.error("payUpgradeSaOrder 保存会员失败!!!");
                throw new RuntimeException("保存会员失败!!!");
            }
        } else {
            log.error("payUpgradeSaOrder 保存会员失败!!!{}", saveResult.getMsg());
            throw new RuntimeException("保存会员失败!!!");
        }
        try {
            // 同步全网产品库存
            this.allProductSync(saOrderExt);

            rabbitTemplate.convertAndSend(RabbitMqConstants.ACTIVITY_EXCHANGE, RabbitMqConstants.ACTIVITY_KEY, saOrderExt);
            // 推送秒结数据处理 -- 升级订单
            rabbitTemplate.convertAndSend(RabbitMqConstants.ORDER_SECOND_EXCHANGE, RabbitMqConstants.ORDER_SECOND_KEY, saOrderExt);

//            if (EOrderType.UPGRADE_ORDER.getValue() == saOrderExt.getOrderType()) {
//                // 推送会员续约处理MQ
//                rabbitTemplate.convertAndSend(RabbitMqConstants.MEMBER_CONTINUE_EXCHANGE, RabbitMqConstants.MEMBER_CONTINUE_KEY,
//                        MemberContinueDTO.builder()
//                                .pkMemberList(Collections.singletonList(saOrderExt.getPkMember()))
//                                .eMemberContinue(EMemberContinue.UPGRADE_ORDER)
//                                .build());
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean confirmRepurchaseSaOrder(OrderParam orderParam) {
        boolean isToBePay = getIsToBePayByOrderType(orderParam.getPkSettleCountry(), orderParam.getSpecialArea());
        CuMember cuMember;
        if (EOrderType.UPGRADE_ORDER.getValue() == orderParam.getSpecialArea()
                || EOrderType.REPURCHASE_ORDER.getValue() == orderParam.getSpecialArea()
                || EOrderType.MALL_ORDER.getValue() == orderParam.getSpecialArea()
                || EOrderType.SPECIAL_UPGRADE_ORDER.getValue() == orderParam.getSpecialArea()
                || EOrderType.SPECIAL_REPURCHASE_ORDER.getValue() == orderParam.getSpecialArea()) {
            cuMember = getCuMemberByCode(orderParam.getUpgradeMemberCode());
        } else {
            cuMember = getCuMemberByKey(orderParam.getCenterCodeId());
        }
        SaOrderExt saOrderExt = packageWholeSaOrder(orderParam, cuMember);
        if (saOrderExt.getOrderItemsList().size() == 0) {
            return false;
        }

        // 升级订单验证等级
        if (EOrderType.UPGRADE_ORDER.getValue() == orderParam.getSpecialArea() ||
                EOrderType.SPECIAL_UPGRADE_ORDER.getValue() == orderParam.getSpecialArea()) {
            if (setLastCuMemberGrade(cuMember, saOrderExt)) {
                return false;
            }
        } else if (EOrderType.MALL_ORDER.getValue() == orderParam.getSpecialArea()) {
            // 2025.08.01 秒杀专区，处理限购
            this.checkMallOrder(saOrderExt);
        }

        if (isToBePay) {
            processOrder(saOrderExt);
        } else {
            redisService.setCacheObject(CacheConstants.TEMP_ORDER + orderParam.getCenterCodeId() + orderParam.getOrderCode(), saOrderExt, CacheConstants.MEMBER_REFRESH_TIME, TimeUnit.MINUTES);
        }
        redisService.setCacheObject(CacheConstants.TEMP_PARAM + orderParam.getCenterCodeId() + orderParam.getOrderCode(), orderParam, CacheConstants.WARES_REFRESH_TIME, TimeUnit.DAYS);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean payRepurchaseSaOrder(SaOrderExt saOrderExt, CuMemberAccountExt cuMemberAccountExt) {
        // 保存订单
        encapsulationSaOrder(saOrderExt);

        if (EOrderType.PICK_ORDER.getValue() == saOrderExt.getOrderType()) {
            // 提货订单，没有待支付，直接保存
            insertSaOrder(saOrderExt);
        } else {
            // 更新订单信息
            updateSaOrder(saOrderExt);
            // 2025.08.01 添加秒杀限购处理
            this.handleMallOrder(saOrderExt);
        }

        // 处理会员信息，更新会员等级,扣款
        CuMember member = getCuMemberByKey(saOrderExt.getPkMember());
        CuMember cuMember = calculateHaFunMemberGrade(saOrderExt, member);

        if (EOrderType.RENEWAL_ORDER.getValue() == saOrderExt.getOrderType()) {
            // 续约订单，会员有效期加12个月
            cuMember = member;
            cuMember.setExpireDate(DateUtils.addMonths(member.getExpireDate(), 12));
            cuMember.setStopDate(DateUtils.addMonths(member.getStopDate(), 12));
        }

        R<Boolean> saveResult = iMemberServiceApi.saveMember(cuMember, saOrderExt, cuMemberAccountExt);
        if (saveResult.isSuccess()) {
            if (!saveResult.getData()) {
                log.error("payRepurchaseSaOrder 保存订单失败!");
                throw new RuntimeException("保存订单失败!");
            }
        } else {
            log.error("payRepurchaseSaOrder 保存订单失败! {}", saveResult.getMsg());
            throw new RuntimeException("保存订单失败!");
        }

        try {
            // 同步全网产品库存
            this.allProductSync(saOrderExt);

            // 推送秒结数据处理 -- 其它订单
            rabbitTemplate.convertAndSend(RabbitMqConstants.ORDER_SECOND_EXCHANGE, RabbitMqConstants.ORDER_SECOND_KEY, saOrderExt);
//            if (EOrderType.RENEWAL_ORDER.getValue() == saOrderExt.getOrderType()) {
//                // 续约专区推送MQ
//                rabbitTemplate.convertAndSend(RabbitMqConstants.MEMBER_CONTINUE_EXCHANGE, RabbitMqConstants.MEMBER_CONTINUE_KEY,
//                        MemberContinueDTO.builder()
//                                .pkMemberList(Collections.singletonList(saOrderExt.getPkMember()))
//                                .eMemberContinue(EMemberContinue.BUY_GIFT)
//                                .build());
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 封装整个订单
     *
     * @param orderParam 参数
     * @param cuMember   会员
     */
    private SaOrderExt packageWholeSaOrder(OrderParam orderParam, CuMember cuMember) {
        // 获取订单编号
        String orderCode = orderParam.getOrderCode();
        if (StringUtils.isEmpty(orderCode)) {
            orderCode = saOrderHandle.createOrderCode(EOrderPrefix.ORDER_CODE.getValue());
        }
        // 封装订单信息
        SaOrderExt saOrderExt = saOrderHandle.packageSaveSaOrder(orderParam, cuMember, orderCode);
        if (null != orderParam.getOrderTypeExtend() && EOrderTypeExtend.REG_REP.getValue().equals(orderParam.getOrderTypeExtend())) {
            saOrderExt.setOrderType(EOrderType.REPURCHASE_ORDER.getValue());
            saOrderExt.setOrderTypeExtend(orderParam.getOrderTypeExtend());
        }
        // 封装订单明细 -- 处理邮费、活动赠品
        saOrderHandle.packSaOrderItems(cuMember, saOrderExt, orderParam);

        // 第二次封装订单，根据明细表计算订单主表金额、业绩,处理明细仓库
        // key为产品id
        List<Integer> productIdList = new ArrayList<>();
        saOrderExt.getOrderItemsList().forEach(saOrderItems -> {
            saOrderExt.setPkRate(saOrderItems.getPkRate());
            if (EYesNo.YES.getIntValue() == saOrderItems.getIsGift()) {
                return;
            }
            // 总价
            saOrderExt.setOrderAmount(ComputeUtil.computeAddMultiply(saOrderExt.getOrderAmount(), saOrderItems.getPrice(), saOrderItems.getQuantity()));
            // 总业绩
            saOrderExt.setOrderAchieve(ComputeUtil.computeAddMultiply(saOrderExt.getOrderAchieve(), saOrderItems.getAchievement(), saOrderItems.getQuantity()));
            // 总考核业绩
            saOrderExt.setOrderAssAchieve(ComputeUtil.computeAddMultiply(saOrderExt.getOrderAssAchieve(), saOrderItems.getAssAchievement(), saOrderItems.getQuantity()));
            productIdList.add(saOrderItems.getPkProduct());
        });
        saOrderExt.setOrderAmount(saOrderExt.getOrderAmount().setScale(2, RoundingMode.HALF_UP));

        if (productIdList.size() > 0 && saOrderExt.getRecProvince() != null) {
            // 根据产品，先查看是否由仓库，有仓库的话修改仓库
            List<BdProductStorehouseExt> bdProductStorehouseList = iAreaServiceApi.queryBdProductStorehouseByCondition(productIdList, saOrderExt.getRecProvince()).getData();
            Map<Integer, BdProductStorehouseExt> bdProductStorehouseMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(bdProductStorehouseList)) {
                bdProductStorehouseList.forEach(bdProductStorehouse -> bdProductStorehouseMap.put(bdProductStorehouse.getPkProduct(), bdProductStorehouse));
                for (SaOrderItems saOrderItems : saOrderExt.getOrderItemsList()) {
                    if (bdProductStorehouseMap.containsKey(saOrderItems.getPkProduct())) {
                        BdProductStorehouseExt bdProductStorehouseExt = bdProductStorehouseMap.get(saOrderItems.getPkProduct());
                        saOrderItems.setPkStorehouse(bdProductStorehouseExt.getPkStorehouse().intValue());
                    }
                }
            }
        }
        saOrderExt.setUploadAchieve(saOrderExt.getOrderAchieve());
        orderParam.setOrderCode(orderCode);
        return saOrderExt;
    }


    @Override
    public void queryPostageByParam(OrderParam orderParam) {
        CuMember cuMember = getCuMemberByKey(orderParam.getCenterCodeId());
        saOrderHandle.queryPostage(cuMember, orderParam);
    }

    @Override
    public OrderReturn computeLevel(OrderParam orderParam) {
        // 新订单的
        SaOrder saOrder = saOrderHandle.computeSaOrderAchieve(orderParam);
        OrderReturn orderReturn = OrderReturn.builder().isEnough(false).build();

        // 计算下单后等级
        GradeDTO gradeDTO = calculateGradeDTO(orderParam.getSpecialArea(), orderParam.getPkSettleCountry(),
                orderParam.getCenterCodeId(), saOrder, orderReturn);
        if (null == gradeDTO) {
            orderReturn.setIsEnough(Boolean.FALSE);
            return orderReturn;
        }

        if (orderParam.getSpecialArea().equals(EOrderType.REGISTER_ORDER.getValue())
                || orderParam.getSpecialArea().equals(EOrderType.SPECIAL_REGISTER_ORDER.getValue())) {
            // 注册订单直接给足够升级
            orderReturn.setIsEnough(Boolean.TRUE);
        }

        if (orderParam.getIsEnough() != null && orderParam.getIsEnough()) {
            // 如果足够升级，查询出等级信息
            orderReturn.setIsEnough(Boolean.TRUE);
            CuMember member = getCuMemberByKey(orderParam.getCenterCodeId());
            GradeDTO grade = iGradeServiceApi.getGrade(member.getPkSettleGrade()).getData();
            orderReturn.setPkGradeVal(grade.getGradeName());
            return orderReturn;
        }

        // 验证等级是否满足条件
        if (!orderReturn.getIsEnough()) {
            CuMember member;
            if (null != orderParam.getUpgradeMemberCodeTmp()) {
                member = getCuMemberByCode(orderParam.getUpgradeMemberCodeTmp());
            } else {
                member = getCuMemberByKey(orderParam.getCenterCodeId());
            }
            GradeDTO grade = iGradeServiceApi.getGrade(member.getPkSettleGrade()).getData();
            if (grade.getGradeValue() < gradeDTO.getGradeValue()) {
                orderReturn.setIsEnough(Boolean.TRUE);
            } else {
                // 2025.07.17 为兼容注册送等级逻辑，此处需要查询一下会员的实际订单对应等级
                SaOrderExt gradeOrder = baseMapper.getLastOrderGrade(member.getPkId());
                if (null != gradeOrder) {
                    if (gradeOrder.getGradeValue() < gradeDTO.getGradeValue()
                            && gradeOrder.getGradeValue() < EGrade.VIP.getValue()) {
                        orderReturn.setIsEnough(Boolean.TRUE);
                    } else {
                        gradeDTO.setGradeName(null);
                    }
                }
            }
        }

        orderReturn.setPkGradeVal(gradeDTO.getGradeName());
        return orderReturn;
    }

    private GradeDTO calculateGradeDTO(Integer specialArea, Integer pkCountry, Long pkMember, SaOrder saOrder, OrderReturn orderReturn) {
        BigDecimal orderAmount = saOrder.getOrderAmount();
        BigDecimal orderAchieve = saOrder.getOrderAchieve();
        // 判断专区 升级方式不一样
        String upgradeWay = querySystemConfigByKey(pkCountry, ESystemConfig.UPGRADE_WAY.getKey());

        if (specialArea.equals(EOrderType.UPGRADE_ORDER.getValue())
//                || (cuMember != null && Objects.equals(cuMember.getPkSettleGrade(), MagicNumberConstants.CHINA_HA_FUN))
        ) {
            // 升级订单
//            if (Objects.equals(cuMember.getPkSettleGrade(), MagicNumberConstants.CHINA_HA_FUN)) {
//                upgradeWay = Integer.toString(EUpgradeWay.DIFFERENCE.getValue());
//            }
            if (EUpgradeWay.COVER.getValue() != Integer.parseInt(upgradeWay)) {
                // 获得历史订单pv
                QueryWrapper<SaOrder> queryWrapper = new QueryWrapper<>();
                queryWrapper.select(" pk_member,sum(order_amount) order_amount,sum(order_achieve) order_achieve ");
                queryWrapper.eq(SaOrderFieldConstants.ORDER_STATUS, EOrderStatus.PAY.getValue())
                        .eq(MemberFieldConstants.PK_MEMBER, pkMember)
                        .groupBy("pk_member");
                if (StringUtils.isNotEmpty(saOrder.getOrderCode())) {
                    queryWrapper.ne(SaOrderFieldConstants.ORDER_CODE, saOrder.getOrderCode());
                }
                SaOrder hisSaOrder = baseMapper.selectOne(queryWrapper);
                if (hisSaOrder != null) {
                    orderAmount = orderAmount.add(hisSaOrder.getOrderAmount());
                    orderAchieve = orderAchieve.add(hisSaOrder.getOrderAchieve());
                }
                // 累计升级无论是否升级都满足条件
                if (EUpgradeWay.TOTAL.getValue() == Integer.parseInt(upgradeWay)) {
                    orderReturn.setIsEnough(Boolean.TRUE);
                }
            }
        }

        return saOrderHandle.getMemberGradeAndAwardByCountry(orderAmount, orderAchieve, pkCountry, upgradeWay);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String registerEmptyOrder(OrderBlankRegParams orderBlankRegParams) {
        LoginUser loginUser = userTokenService.getLoginUser();
        Integer pkCountry = SecurityUtils.getPkCountry();
        Date date = new Date();

        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SPECIAL_UPDATE_CODE.getValue());
        orderBlankRegParams.setApprovalBusiness(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());


        //添加修改记录表数据
        CuMemberServiceLog memberLog = new CuMemberServiceLog();
//        memberLog.setPkMember(member.getData().getPkId().longValue());
        memberLog.setEditType(EApprovalBusiness.EMPTY_ORDER.getValue());
        memberLog.setEditTypePay(EApprovalBusiness.EMPTY_ORDER.getValue());

        memberLog.setNewValue(JSONObject.toJSONString(orderBlankRegParams));
        memberLog.setPkCreator(loginUser.getUserId());
        memberLog.setCreationTime(date);
        memberLog.setBusinessNo(code);
        memberLog.setPkCountry(pkCountry);
        memberLog.setProcessType(orderBlankRegParams.getProcessType());
        memberLog.setApproveNumber(orderBlankRegParams.getChangeNumber());

        //免签呈;免签呈免支付
        if (orderBlankRegParams.getProcessType() == EProcessType.AVOIDSIGNING.getValue()
                || orderBlankRegParams.getProcessType() == EProcessType.DOUBLEAVOID.getValue()) {
            //添加修改记录表数据
            memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
            iCuMemberServiceLogServiceApi.insert(memberLog);
            // 主要业务
            //创建用户
            CuMemberExt memberExt = createMember(orderBlankRegParams);

            R<CuMember> member = iMemberServiceApi.createEmptyOrderMember(memberExt);
            if (member.getData() == null) {
                throw new RuntimeException("保存会员失败");
            }
            if (orderBlankRegParams.getRegisterPv().compareTo(BigDecimal.ZERO) > 0) {
                // 生成订单 （订单pv 不为0 情况下）
                createRegisterEmptyOrder(orderBlankRegParams, member.getData(), loginUser);
            }
            return member.getData().getMemberCode();
        } else if (orderBlankRegParams.getProcessType() == EProcessType.AVOIDPAY.getValue()
                || orderBlankRegParams.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            // 免支付 需签呈+支付
            //生成签呈
            Set<Long> memberSet = new HashSet<>();
            memberSet.add(loginUser.getUserId());
            memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            iCuMemberServiceLogServiceApi.insert(memberLog);
            ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.EMPTY_ORDER)
                    .businessCode(code)
                    .signType(ESignType.getEnumByValue(orderBlankRegParams.getSignType()))
                    .remark(orderBlankRegParams.getRemark()).pkMemberList(memberSet).build();
            R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, loginUser);
            if (!submit.isSuccess()) {
                log.error("====" + submit.getData());
                throw new RuntimeException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_PETITION));
            }
        }
//        //扣钱
        if (orderBlankRegParams.getProcessType() == EProcessType.AVOIDSIGNING.getValue() || orderBlankRegParams.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            // 免签或者确认按钮扣费
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(pkCountry);
            businessCommissionDTO.setMemberAmountDTOList(orderBlankRegParams.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.EMPTY_ORDER.getValue());
            R<Boolean> b = iMemberTradeServiceApi.businessCommissionSubmit(businessCommissionDTO);
            if (!b.getData()) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY));
            }
        }
        return "";
    }

    /**
     * 空单生成订单
     *
     * @param orderBlankRegParams 参数
     */
    private SaOrder createRegisterEmptyOrder(OrderBlankRegParams orderBlankRegParams, CuMember member, LoginUser loginUser) {
        // 创建订单
        SaOrder saOrder = new SaOrder();
        String orderCode = saOrderHandle.createOrderCode(EOrderPrefix.ORDER_CODE.getValue());
        saOrder.setOrderCode(orderCode);
        // 虚拟订单
        saOrder.setOrderType(EOrderType.FICTITIOUS_ORDER.getValue());
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(orderBlankRegParams.getPkSettleCountry());
        saOrder.setPkRate(currency.getData().getPkId());
        saOrder.setOrderAmount(orderBlankRegParams.getRegisterPrice());
        saOrder.setOrderAchieve(orderBlankRegParams.getRegisterPv());
        saOrder.setDeliveryWay(orderBlankRegParams.getDeliveryWay());
        // 如果发货方式为空，或者为0，则重置为快递发货
        if (null == saOrder.getDeliveryWay() || saOrder.getDeliveryWay().equals(0)) {
            saOrder.setDeliveryWay(EDelivery.FAST_MAIL.getValue());
        }
        saOrder.setTranType(orderBlankRegParams.getTranType());
        saOrder.setRecName(orderBlankRegParams.getMemberName());
        saOrder.setRecPhone(orderBlankRegParams.getPhone());
        saOrder.setRecProvince(orderBlankRegParams.getProvince());
        saOrder.setRecCity(orderBlankRegParams.getCity());
        saOrder.setRecCounty(orderBlankRegParams.getCounty());
        saOrder.setRecAddress(orderBlankRegParams.getAddress());
        saOrder.setPayTime(new Date());
        saOrder.setOrderStatus(EOrderStatus.PAY.getValue());
        saOrder.setCreationTime(new Date());
        saOrder.setPkCountry(orderBlankRegParams.getPkSettleCountry());
        saOrder.setPkCreator(SecurityUtils.getUserId());
        saOrder.setPkMember(member.getPkId());
        saOrder.setRemark(orderBlankRegParams.getRemark());
        saOrder.setPkReference(member.getPkParent());
        saOrder.setPkPlacement(member.getPkPlaceParent());
        saOrder.setDeliveryWay(EDelivery.COMPANY_PICKED_UP.getValue());
        saOrder.setTranType(ETransportType.LAND.getValue());
        save(saOrder);
        // 创建订单项
        List<SaOrderItems> orderItems = orderBlankRegParams.getOrderItems();
        for (SaOrderItems orderItem : orderItems) {
            orderItem.setPkOrder(saOrder.getPkId());
            BdWares wares = iBdWaresService.getWares(orderItem.getPkWares());
            BdProductExtendExt productExtend = iBdProductExtendService.queryExtendAndProduct(orderItem.getPkProduct());
            orderItem.setPkWares(wares.getPkId());
            orderItem.setPrice(wares.getWaresPrice().multiply(new BigDecimal(orderItem.getQuantity())));
            orderItem.setPkRate(currency.getData().getPkId());
            orderItem.setAchievement(wares.getWaresAchieve().multiply(new BigDecimal(orderItem.getQuantity())));
            orderItem.setIsGift(productExtend.getIsGift());
            orderItem.setPkGrade(orderBlankRegParams.getUserLevel());
            orderItem.setPkAwards(orderBlankRegParams.getUserAwards());
            orderItem.setOrderStatus(EOrderStatus.PAY.getValue());
            orderItem.setCreationTime(DateUtils.currentDateTime());
            // 填充冗余产品规格
            List<BdWaresSpecsRelationExt> waresSpecsRelationList = iBdWaresSpecsRelationService.selectByWaresSpecsSku(orderItem.getPkWaresSpecsSku().intValue());
            // 规格名称
            List<String> specsNames = new ArrayList<>();
            // 规格id
            List<Integer> specsIds = new ArrayList<>();
            for (BdWaresSpecsRelationExt bdWaresSpecsRelationExt : waresSpecsRelationList) {
                specsNames.add(bdWaresSpecsRelationExt.getSpecsName());
                specsIds.add(bdWaresSpecsRelationExt.getPkSpecs());
            }
            orderItem.setSpecsName(StringUtils.join(specsNames, ","));
            orderItem.setSpecsNameId(StringUtils.join(specsIds, ","));
            orderItem.setPkCountry(orderBlankRegParams.getPkSettleCountry());
            orderItem.setPkCreator(SecurityUtils.getUserId());
            orderItem.setSkuCode(CommonUtil.createSkuCode(productExtend.getProductCode(), orderItem.getSpecsNameId()));
        }
        iSaOrderItemsService.saveBatch(orderItems);
        return saOrder;
    }

    /**
     * 空单生成用户
     *
     * @param orderBlankRegParams 参数
     */
    private CuMemberExt createMember(OrderBlankRegParams orderBlankRegParams) {
        CuMemberExt cuMember = new CuMemberExt();
        // 注册等级
        cuMember.setPkRegisterGrade(orderBlankRegParams.getUserLevel());
        // 结算等级
        cuMember.setPkSettleGrade(orderBlankRegParams.getUserLevel());
        cuMember.setPkSettleCountry(orderBlankRegParams.getPkSettleCountry());
        // 推荐人主键
        cuMember.setParent(orderBlankRegParams.getParent());
        // 安置人主键
        cuMember.setPlaceParent(orderBlankRegParams.getPlaceParent());
        // 回填金额
        cuMember.setLockAccount4(orderBlankRegParams.getBackfillPrice());

        cuMember.setPlaceDept(orderBlankRegParams.getPlaceDept());
        cuMember.setMemberName(orderBlankRegParams.getMemberName());
        cuMember.setPhone(orderBlankRegParams.getPhone());
        cuMember.setCustomerType(ECustomerType.EMPTY_ORDER.getValue());
        cuMember.setPkAwards(orderBlankRegParams.getUserAwards());
        cuMember.setIdCard(orderBlankRegParams.getIdCard());
        cuMember.setPkCenterCode(orderBlankRegParams.getCenterCodeId());
        cuMember.setPkCountry(orderBlankRegParams.getPkSettleCountry());
        cuMember.setPkSettleCountry(orderBlankRegParams.getPkSettleCountry());
        cuMember.setSource(EDataSource.PC.getValue());
        cuMember.setPkRegisterGrade(orderBlankRegParams.getUserLevel());
        cuMember.setPkSettleGrade(orderBlankRegParams.getUserLevel());
        if (orderBlankRegParams.getUserAwards() == null) {
            cuMember.setPkAwards(0);
        } else {
            cuMember.setPkAwards(orderBlankRegParams.getUserAwards());
        }
        cuMember.setConsumeMoney(orderBlankRegParams.getRegisterPrice());
        cuMember.setConsumeAchieve(orderBlankRegParams.getRegisterPv());
        cuMember.setPayTime(new Date());
        cuMember.setLoginPwd(SecureUtil.md5(SysConstants.LOGIN_PASSWORD));
        cuMember.setPayPwd(SecureUtil.md5(SysConstants.PAY_PASSWORD));
        cuMember.setLoginPassword(SysConstants.LOGIN_PASSWORD);
        cuMember.setPayPassword(SysConstants.PAY_PASSWORD);
        cuMember.setPkCreator(SecurityUtils.getUserId());
        cuMember.setCreationTime(new Date());
        cuMember.setOrderSource(EOrderSource.EMPTY.getValue());
        cuMember.setEmail(orderBlankRegParams.getEmail());
        return cuMember;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void revokeSaOrderByOrderCode(Long pkApprove, OrderCancelParam orderCancelParam, ValidateCancelOrderVO validateCancelOrderVO) {
        SaOrderExt saOrderExt = validateCancelOrderVO.getSaOrderExt();
        BusinessCommissionDTO businessCommissionDTO = null;
        if (orderCancelParam.getCancelRoad() == 1) {
            EApprovalBusiness approveBusiness = EApprovalBusiness.ORDER_CANCEL;
//            if (ECancelOrderType.OTHER_CANCEL_PART_ORDER.getValue() == orderCancelParam.getCancelType()) {
//                approveBusiness = EApprovalBusiness.ORDER_CANCEL_PRODUCT;
//            }
            Map<Long, OrderQueryChargeDTO> queryChargeMap = iOrderBusinessService.queryChargeLog(Collections.singletonList(validateCancelOrderVO.getSaOrderExt()),
                    approveBusiness, orderCancelParam.getPkCountry());
            if (queryChargeMap != null && queryChargeMap.containsKey(saOrderExt.getPkId())) {
                List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
                // 封装订单业务扣款
                if (queryChargeMap.get(saOrderExt.getPkId()).getCost().compareTo(BigDecimal.ZERO) > 0) {
                    // 当需要扣费大于0，则进行处理
                    memberAmountDTOList.add(MemberAmountDTO.builder()
                            .pkMember(saOrderExt.getPkCreator())
                            .tradeAmount(queryChargeMap.get(saOrderExt.getPkId()).getCost())
                            .build());
                }
                Integer currency = queryChargeMap.get(saOrderExt.getPkId()).getPkAccount();
                if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                    // 本批订单修改记录编号
                    String businessCode = CommonUtil.createSerialNumber(EOrderPrefix.REVOKE_ORDER_CODE);
                    businessCommissionDTO = BusinessCommissionDTO.builder()
                            .pkCountry(orderCancelParam.getPkCountry())
                            .pkCreator(pkApprove)
                            .pkAccount(currency)
                            .tradeType(approveBusiness.getValue())
                            .tradeCode(businessCode)
                            .memberAmountDTOList(memberAmountDTOList)
                            .build();
                }
            }
        }

//        if (ECancelOrderType.OTHER_CANCEL_PART_ORDER.getValue() == orderCancelParam.getCancelType()) {
//            List<OrderCancelDetailParam> orderCancelDetailParamList = orderCancelParam.getOrderCancelDetailParamList();
//            List<Long> pkOrderItemList = orderCancelDetailParamList.stream().map(OrderCancelDetailParam::getPkId).collect(Collectors.toList());
//            // 第二次封装订单，根据明细表计算订单主表金额、业绩
//            saOrderExt.setOrderAmount(BigDecimal.ZERO);
//            saOrderExt.setOrderAchieve(BigDecimal.ZERO);
//            saOrderExt.setOrderAssAchieve(BigDecimal.ZERO);
//            saOrderExt.setBackOrderAmount(BigDecimal.ZERO);
//            List<SaOrderItems> saOrderItemsList = new ArrayList<>();
//            saOrderExt.getOrderItemsList().forEach(saOrderItems -> {
//                if (pkOrderItemList.contains(saOrderItems.getPkId())) {
//                    saOrderExt.setBackOrderAmount(ComputeUtil.computeAddMultiply(saOrderExt.getBackOrderAmount(), saOrderItems.getPrice(), saOrderItems.getQuantity()));
//                    return;
//                }
//                // 总价;
//                saOrderExt.setOrderAmount(ComputeUtil.computeAddMultiply(saOrderExt.getOrderAmount(), saOrderItems.getPrice(), saOrderItems.getQuantity()));
//                // 总业绩
//                saOrderExt.setOrderAchieve(ComputeUtil.computeAddMultiply(saOrderExt.getOrderAchieve(), saOrderItems.getAchievement(), saOrderItems.getQuantity()));
//                // 总考核业绩
//                saOrderExt.setOrderAssAchieve(ComputeUtil.computeAddMultiply(saOrderExt.getOrderAssAchieve(), saOrderItems.getAssAchievement(), saOrderItems.getQuantity()));
//                saOrderItemsList.add(saOrderItems);
//            });
//            saOrderExt.setUploadAchieve(saOrderExt.getOrderAchieve());
//            if (saOrderItemsList.size() == 0) {
//                saOrderExt.setDelFlag(EDelFlag.DELETE.getValue());
//            } else {
//                saOrderExt.setOrderItemsList(saOrderItemsList);
//            }
//            // 修改订单
//            Date currentDateTime = DateUtils.currentDateTime();
//            // 删除发货单
//            iSaDeliverItemsService.deleteSaDeliverItems(saOrderExt.getPkId(), pkOrderItemList);
//            updateSaOrder(pkApprove, saOrderExt, currentDateTime);
//            // 删除订单明细
//            if (!iSaOrderItemsService.updateOrderItemsById(pkOrderItemList, pkApprove, currentDateTime)) {
//                throw new RuntimeException("更新订单失败");
//            }
//            if (!iMemberServiceApi.normalRevokeOrder(pkApprove, saOrderExt, null, pkOrderItemList, businessCommissionDTO).getData()) {
//                throw new RuntimeException("撤单失败");
//            }
//        } else {
        // 删除订单
        saOrderExt.setDelFlag(EDelFlag.DELETE.getValue());
        Date currentDate = DateUtils.currentDateTime();
        // 删除发货单
        iSaDeliverItemsService.deleteSaDeliverItems(saOrderExt.getPkId(), null);
        // 修改订单
        updateSaOrder(pkApprove, saOrderExt, currentDate);
        // 删除订单明细
        if (!iSaOrderItemsService.updateOrderItems(saOrderExt)) {
            throw new RuntimeException("更新订单失败");
        }
        // 撤销注册订单 单点撤单
        if (ECancelOrderType.SINGLE_CANCEL_ORDER.getValue() == orderCancelParam.getCancelType()) {
            // 单点撤单，变死点
            R<Boolean> tmpR = iMemberServiceApi.singleRevokeMemberByRegisterOrder(pkApprove, saOrderExt, businessCommissionDTO);
            if (!tmpR.isSuccess()) {
                throw new RuntimeException("撤单失败 " + tmpR.getMsg());
            }
        } else if (ECancelOrderType.MERGE_CANCEL_ORDER.getValue() == orderCancelParam.getCancelType()) {
            // 合并撤单，撤下面所有
            List<Long> memberList = validateCancelOrderVO.getMemberList().stream().map(OrderCancelRegisterMemberVO::getPkMember).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(memberList)) {
                // 撤销所有订单明细表
                iSaOrderItemsService.updateOrderItemsByMemberList(memberList, pkApprove, currentDate);
                // 撤销所有订单主表
                baseMapper.updateSaOrderByMember(memberList, pkApprove, currentDate);
            }

            R<Boolean> tmpR = iMemberServiceApi.mergeRevokeMemberByRegisterOrder(pkApprove, memberList, validateCancelOrderVO.getSaOrderMap(), businessCommissionDTO);
            if (!tmpR.isSuccess()) {
                throw new RuntimeException("撤单失败 " + tmpR.getMsg());
            }
        } else {
            // 其他撤单 撤销升级订单
            CuMember cuMember = getCuMemberByKey(saOrderExt.getPkMember());
            if (EOrderType.UPGRADE_ORDER.getValue() == saOrderExt.getOrderType()
                    || EOrderType.SPECIAL_UPGRADE_ORDER.getValue() == saOrderExt.getOrderType()
            ) {
                SaOrder updSaOrder = validateCancelOrderVO.getUpdSaOrder();
                // 计算等级
                // 获取升级订单
                // 空单注册，从cu_member_register中获取
                if (updSaOrder == null) {
                    CuMemberRegister cuMemberRegister = iMemberServiceApi.queryCuMemberRegister(saOrderExt.getPkMember()).getData();
                    cuMember.setPkRegisterGrade(cuMemberRegister.getPkRegisterGrade());
                    cuMember.setPkSettleGrade(cuMemberRegister.getPkRegisterGrade());
                    cuMember.setConsumeMoney(BigDecimal.ZERO);
                    cuMember.setConsumeAchieve(cuMemberRegister.getConsumeAchieve());

                    // 查询最新一条升级记录
                    CuMemberLevel cuMemberLevel = iCuMemberDetailServiceApi.queryLastManualUpgrade(cuMember.getPkId(),
                            Arrays.asList(EUpgradeType.AUTO_UPGRADE.getValue(), EUpgradeType.MANUAL_UPGRADE.getValue()),
                            saOrderExt.getPkId()).getData();
                    if (null != cuMemberLevel) {
                        // 存在手动升级
                        cuMember.setPkSettleGrade(cuMemberLevel.getNewLevel());
                    }
                } else {
                    OrderReturn orderReturn = OrderReturn.builder().isEnough(false).build();
                    GradeDTO gradeDTO = calculateGradeDTO(EOrderType.UPGRADE_ORDER.getValue(), cuMember.getPkSettleCountry(), cuMember.getPkId(),
                            validateCancelOrderVO.getUpdSaOrder(), orderReturn);
                    cuMember.setPkRegisterGrade(gradeDTO.getPkId());
                    cuMember.setPkSettleGrade(gradeDTO.getPkId());

                    // 查询最新一条升级记录
                    CuMemberLevel cuMemberLevel = iCuMemberDetailServiceApi.queryLastManualUpgrade(cuMember.getPkId(),
                            Arrays.asList(EUpgradeType.BUY_UPGRADE.getValue(), EUpgradeType.MANUAL_UPGRADE.getValue()),
                            saOrderExt.getPkId()).getData();
                    if (null != cuMemberLevel) {
                        // 存在手动升级
                        cuMember.setPkSettleGrade(cuMemberLevel.getNewLevel());
                    }

                    // 查询最新的手动开通注册权限的记录
                    CuMemberServiceLog cuMemberServiceLog = iCuMemberServiceLogServiceApi.selectTopData(cuMember.getPkId(), EApprovalBusiness.REGISTER_POWER_STATE.getValue(), EApproveStatus.FINISH.getValue()).getData();
                    if (null != cuMemberServiceLog && StringUtils.isNotEmpty(cuMemberServiceLog.getNewValue())) {
                        // 存在手动开通
                        if (Integer.parseInt(cuMemberServiceLog.getNewValue()) > gradeDTO.getRegisterAuthority()) {
                            // 手动开通注册权限 大于 降级之后的权限，则保留手动开通的权限
                            cuMember.setRegisterAuthority(Integer.parseInt(cuMemberServiceLog.getNewValue()));
                        } else {
                            cuMember.setRegisterAuthority(gradeDTO.getRegisterAuthority());
                        }
                    }

                    SaOrder saOrder = baseMapper.queryLastRegisterOrUpdate(cuMember.getPkId(), cuMember.getPkCountry());
                    if (null != saOrder) {
                        // 撤消升级单之后，获取注册或者最后的升级单，填充注册金额
                        cuMember.setConsumeMoney(saOrder.getOrderAmount());
                    } else {
                        // 没有注册或者升级单，则直接扣减升级单的订单金额
                        cuMember.setConsumeMoney(ComputeUtil.computeSubtract(cuMember.getConsumeMoney(), saOrderExt.getOrderAmount()));
                    }
                    cuMember.setConsumeAchieve(gradeDTO.getStartValue());
                }
            } else if (EOrderType.PICK_ORDER.getValue() == saOrderExt.getOrderType()) {
                // 提货订单
                if (!iAcPickService.cancelPickOrder(saOrderExt.getOrderCode(), pkApprove)) {
                    throw new RuntimeException("撤销订单退还提货失败");
                }
            } else if (EOrderType.MALL_ORDER.getValue() == saOrderExt.getOrderType()) {
                // 秒杀订单，处理限购
                this.handleMallOrderCancel(saOrderExt);
            }

            if (EOrderType.REPURCHASE_ORDER.getValue() == saOrderExt.getOrderType()
                    && EOrderTypeExtend.REG_REP.getValue() == saOrderExt.getOrderTypeExtend()) {
                // 注册转复购订单，走的是注册订单的撤单流程
                R<Boolean> tmpR = iMemberServiceApi.singleRevokeMemberByRegisterOrder(pkApprove, saOrderExt, businessCommissionDTO);
                if (!tmpR.isSuccess()) {
                    throw new RuntimeException("撤单失败 " + tmpR.getMsg());
                }
            } else {
                if (!iMemberServiceApi.normalRevokeOrder(pkApprove, saOrderExt, cuMember, null, businessCommissionDTO).getData()) {
                    throw new RuntimeException("撤单处理会员失败");
                }
            }
        }
//        }

        try {
            // 推送MQ的列表
            List<SaOrderExt> mqList = new ArrayList<>();
            mqList.add(saOrderExt);
            if (ECancelOrderType.MERGE_CANCEL_ORDER.getValue() == orderCancelParam.getCancelType()) {
                // 合并撤单需要将所有订单全部推过去，有部分活动要按订单来处理
                Map<Long, SaOrderExt> saOrderMap = validateCancelOrderVO.getSaOrderMap();
                for (Long key : saOrderMap.keySet()) {
                    // 撤单主单默认放在第一位置，合并撤单列表添加的时候不需要处理撤单主单
                    if (!saOrderExt.getOrderCode().equals(saOrderMap.get(key).getOrderCode())) {
                        mqList.add(saOrderMap.get(key));
                    }
                }
            }
            // 推送MQ，处理活动回退
            rabbitTemplate.convertAndSend(RabbitMqConstants.ORDER_CANCEL_EXCHANGE, RabbitMqConstants.ORDER_CANCEL_KEY, mqList);

//            if (EOrderType.UPGRADE_ORDER.getValue() == mqList.get(0).getOrderType()) {
//                // 升级订单撤单，只能一次撤一单，推送会员续约处理MQ
//                rabbitTemplate.convertAndSend(RabbitMqConstants.MEMBER_CONTINUE_EXCHANGE, RabbitMqConstants.MEMBER_CONTINUE_KEY,
//                        MemberContinueDTO.builder()
//                                .pkMemberList(Collections.singletonList(mqList.get(0).getPkMember()))
//                                .eMemberContinue(EMemberContinue.UPGRADE_CANCEL)
//                                .build());
//            } else if (EOrderType.REGISTER_ORDER.getValue() == mqList.get(0).getOrderType()) {
//                // 注册订单撤单，推送会员续约处理MQ
//                List<Long> pkMemberList = mqList.stream().map(SaOrderExt::getPkMember).collect(Collectors.toList());
//                rabbitTemplate.convertAndSend(RabbitMqConstants.MEMBER_CONTINUE_EXCHANGE, RabbitMqConstants.MEMBER_CONTINUE_KEY,
//                        MemberContinueDTO.builder()
//                                .pkMemberList(pkMemberList)
//                                .eMemberContinue(EMemberContinue.REGISTER_CANCEL)
//                                .build());
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateSaOrder(Long pkApprove, SaOrderExt saOrderExt, Date currentDateTime) {
        LambdaUpdateWrapper<SaOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SaOrder::getPkModified, pkApprove);
        updateWrapper.set(SaOrder::getModifiedTime, currentDateTime);
        updateWrapper.set(SaOrder::getDelFlag, saOrderExt.getDelFlag());
        updateWrapper.set(SaOrder::getOrderAmount, saOrderExt.getOrderAmount());
        updateWrapper.set(SaOrder::getOrderAchieve, saOrderExt.getOrderAchieve());
        updateWrapper.set(SaOrder::getUploadAchieve, saOrderExt.getUploadAchieve());
        updateWrapper.set(SaOrder::getOrderAssAchieve, saOrderExt.getOrderAssAchieve());
        updateWrapper.eq(SaOrder::getPkId, saOrderExt.getPkId());
        saOrderExt.setPkModified(pkApprove);
        saOrderExt.setModifiedTime(currentDateTime);
        if (!update(updateWrapper)) {
            throw new RuntimeException("更新订单失败");
        }
    }

    @Override
    public GradeDTO queryGradeConfigByCondition(Integer pkCountry, Integer pkGrade) {
        return saOrderHandle.queryGradeConfigByCondition(pkCountry, pkGrade);
    }

    @Override
    public CuMember obtainLastResettleByRecommend(CuMember cuMember, Boolean isFirstAchieve, Boolean isFirst) {
        // 验证是否首单
        if (isFirst == null) {
            isFirst = validateFirstOrder(cuMember.getPkParent(), cuMember.getPkSettleCountry());
        }
        cuMember = iMemberAchieveServiceApi.queryCuMemberAchieveByPkMember(cuMember, isFirst, isFirstAchieve).getData();
        // 验证是否推荐过人，没有推荐只能放入极左极下
        return cuMember;
    }

    @Override
    public boolean validateFirstOrder(Long pkParent, Integer pkCountry) {
        String validateFirstOrder = querySystemConfigByKey(pkCountry, ESystemConfig.FIRST_ORDER.getKey());
        if (EYesNo.YES.getIntValue() == Integer.parseInt(validateFirstOrder)) {
            return queryCuMemberByPkMember(pkParent) == 0;
        }
        return false;
    }

    @Override
    public boolean validateLeftExistMember(Long pkPlaceParent, Integer pkCountry) {
        String validateParent = querySystemConfigByKey(pkCountry, ESystemConfig.PARENT_VALIDATE.getKey());
        if (EYesNo.YES.getIntValue() == Integer.parseInt(validateParent)) {
            // 因为使用Member作为入参，此处 category 传入 10，代表 0=正常，1=待激活
            List<CuMemberExt> cuMemberExtList = queryMemberExtByCondition(CuMember.builder().pkPlaceParent(pkPlaceParent).placeDept(EPlaceDept.LEFT_DEPT.getValue()).category(10).build());
            return cuMemberExtList.size() == 0;
        }
        return false;
    }

    @Override
    public List<SaOrderExt> queryRepeatSaOrderByDay(Date startDate, Date endDate) {
        return baseMapper.queryRepeatSaOrderByDay(startDate, endDate);
    }

    @Override
    public String querySystemConfigByKey(Integer pkCountry, String key) {
        return iSystemConfigServiceApi.getBonusSystemConfig(pkCountry, key).getData();
    }

    @Override
    public BigDecimal selectSum() {
        return baseMapper.selectSum();
    }

    @Override
    public SaOrderExt queryOrderByPkId(Long pkId, Integer pkCountry) {
        return baseMapper.queryOrderByPkId(pkId, pkCountry);
    }

    @Override
    public SaOrderExt queryOrderByCode(String orderCode, Integer pkCountry) {
        return baseMapper.queryOrderByCode(orderCode, pkCountry);
    }

    @Override
    public List<SaOrderExt> queryOrderListByCodeList(List<String> orderCodeList, Integer pkCountry) {
        return baseMapper.queryOrderListByCodeList(orderCodeList, pkCountry);
    }

    @Override
    public List<SaOrderExt> queryOrderListByIdList(List<Long> orderIdList, Integer pkCountry) {
        return baseMapper.queryOrderListByIdList(orderIdList, pkCountry);
    }

    @Override
    public List<SaOrderExt> myOrderList(MyOrderParam param, Long memberId, Integer pkCountry) {
        return baseMapper.myOrderList(param, memberId, pkCountry);
    }

    @Override
    public List<TOnlineRefundExt> queryRefundList() {
        return baseMapper.queryRefundList(SecurityUtils.getUserId());
    }

    @Override
    public List<SaOrderExt> selfRevokeOrderList(MyOrderParam param, Long memberId, Integer pkCountry) {
        return baseMapper.selfRevokeOrderList(param, memberId, pkCountry);
    }

    @Override
    public List<SaOrderExt> selfOrderList(MyOrderParam param, Long memberId, Integer pkCountry) {
        return baseMapper.selfOrderList(param, memberId, pkCountry);
    }

    @Override
    public String lastOrderList(Long memberId, Integer pkCountry) {
        return baseMapper.lastOrderList(memberId, pkCountry);
    }

    @Override
    public List<SaOrderExt> selfAddressOrderList(MyOrderParam param, Long memberId, Integer pkCountry) {
        return baseMapper.selfAddressOrderList(param, memberId, pkCountry);
    }

    @Override
    public int myOrderNum(List<Integer> statusList, Long memberId, Integer pkCountry) {
        return baseMapper.myOrderNum(statusList, memberId, pkCountry);
    }

    @Override
    public boolean myOrderConfirm(Long pkOrder, Long memberId) {
        // 更新订单明细为已收货
        LambdaUpdateWrapper<SaOrderItems> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SaOrderItems::getPkOrder, pkOrder);
        updateWrapper.set(SaOrderItems::getOrderStatus, EOrderStatus.RECEIVED.getValue());
        updateWrapper.set(SaOrderItems::getPkModified, memberId);
        updateWrapper.set(SaOrderItems::getModifiedTime, new Date());
        return iSaOrderItemsService.update(updateWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String myOrderCancel(SaOrder saOrder, Long memberId) {
        Date nowDate = new Date();

        // 如果是注册订单，需要校验下面是否有会员
        if (EOrderType.REGISTER_ORDER.getValue() == saOrder.getOrderType()
                || EOrderType.SPECIAL_REGISTER_ORDER.getValue() == saOrder.getOrderType()
        ) {
            // 注册类订单，需要校验是否推荐过人或者安置过人，如果有则不允许进行取消
            if (iMemberServiceApi.checkLowerMember(saOrder.getPkMember()).getData()) {
                // 订单所属会员下存在用户不能取消
                return TransactionUtils.getContent(MemberMsgConstants.EXIST_MEMBER_NOT_CANCEL);
            }
        }

        log.info("会员取消订单参数，memberId: {}, orderId: {}", memberId, saOrder.getPkId());

        // 删除订单明细
        LambdaUpdateWrapper<SaOrderItems> updateItemsWrapper = new LambdaUpdateWrapper<>();
        updateItemsWrapper.eq(SaOrderItems::getPkOrder, saOrder.getPkId());
        updateItemsWrapper.set(SaOrderItems::getDelFlag, EDelFlag.DELETE.getValue());
        updateItemsWrapper.set(SaOrderItems::getPkModified, memberId);
        updateItemsWrapper.set(SaOrderItems::getModifiedTime, nowDate);
        iSaOrderItemsService.update(updateItemsWrapper);

        // 删除订单
        LambdaUpdateWrapper<SaOrder> updateOrderWrapper = new LambdaUpdateWrapper<>();
        updateOrderWrapper.eq(SaOrder::getPkId, saOrder.getPkId());
        updateOrderWrapper.set(SaOrder::getDelFlag, EDelFlag.DELETE.getValue());
        updateOrderWrapper.set(SaOrder::getPkModified, memberId);
        updateOrderWrapper.set(SaOrder::getModifiedTime, nowDate);
        this.update(updateOrderWrapper);

        // 如果是注册订单，需要取消点位
        if (EOrderType.REGISTER_ORDER.getValue() == saOrder.getOrderType()
                || EOrderType.SPECIAL_REGISTER_ORDER.getValue() == saOrder.getOrderType()
        ) {
            if (!iMemberServiceApi.cancelMember(saOrder.getPkMember()).getData()) {
                throw new RuntimeException("取消订单失败");
            }
        }
        return null;
    }

    @Override
    public List<OrderBusinessVO> queryOrderBusinessList(OrderBusinessParam param, Integer pkCountry) {
        return baseMapper.queryOrderBusinessList(param, pkCountry);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteOrderAndItems(List<Long> orderIdList, Long userId, Integer pkCountry) {
        Date nowDate = new Date();

        // 删除订单
        LambdaUpdateWrapper<SaOrder> orderUpdateWrapper = new LambdaUpdateWrapper<>();
        orderUpdateWrapper.in(SaOrder::getPkId, orderIdList);
        if (null != pkCountry) {
            orderUpdateWrapper.eq(SaOrder::getPkCountry, pkCountry);
        }
        orderUpdateWrapper.set(SaOrder::getDelFlag, EDelFlag.DELETE.getValue());
        orderUpdateWrapper.set(SaOrder::getPkModified, userId);
        orderUpdateWrapper.set(SaOrder::getModifiedTime, nowDate);
        this.update(orderUpdateWrapper);

        // 删除订单明细
        LambdaUpdateWrapper<SaOrderItems> orderItemsUpdateWrapper = new LambdaUpdateWrapper<>();
        orderItemsUpdateWrapper.in(SaOrderItems::getPkOrder, orderIdList);
        if (null != pkCountry) {
            orderItemsUpdateWrapper.eq(SaOrderItems::getPkCountry, pkCountry);
        }
        orderItemsUpdateWrapper.set(SaOrderItems::getDelFlag, EDelFlag.DELETE.getValue());
        orderItemsUpdateWrapper.set(SaOrderItems::getPkModified, userId);
        orderItemsUpdateWrapper.set(SaOrderItems::getModifiedTime, nowDate);
        iSaOrderItemsService.update(orderItemsUpdateWrapper);
    }

    @Override
    public List<WaresOrderVo> selectByOrderInfoList(WaresOrderParam waresOrderParam) {
        return baseMapper.selectByOrderInfoList(waresOrderParam);
    }

    @Override
    public List<OrderInvoicingVO> listOrderInvoicing(OrderInvoicingParam param) {
        return baseMapper.listOrderInvoicing(param);
    }

    @Override
    public List<SaOrderExt> queryOrderMemberInfo(List<Integer> orderTypeList, List<Long> pkMemberList, Integer pkCountry) {
        return baseMapper.queryOrderMemberInfo(orderTypeList, pkMemberList, null, pkCountry);
    }

    @Override
    public List<SaOrderItemsExt> queryOrderSelect(OrderSelectParam param, Integer pkCountry) {
        return baseMapper.queryOrderSelect(param, pkCountry);
    }

    /**
     * 封装会员分享会员
     *
     * @param orderParam    参数
     * @param cuMemberShare 会员分享
     */
    private CuMember packageCuMemberShare(OrderParam orderParam, CuMemberShare cuMemberShare) {
        orderParam.setMemberCode(cuMemberShare.getMemberCode());
        orderParam.setMemberName(cuMemberShare.getMemberName());
        orderParam.setPhone(cuMemberShare.getPhone());
        orderParam.setParentId(cuMemberShare.getPkParent());
        orderParam.setCenterCodeId(cuMemberShare.getPkParent());
        CuMember parentMember = iMemberServiceApi.queryMember(cuMemberShare.getPkParent()).getData();
        if (parentMember == null) {
            return null;
        }
        orderParam.setPkCountry(cuMemberShare.getPkCountry());
        orderParam.setPkSettleCountry(parentMember.getPkSettleCountry());
        CuMember newCuMember = saOrderHandle.packageSaveUser(orderParam, parentMember);
        newCuMember.setPkId(cuMemberShare.getPkId());
        newCuMember.setPkCreator(cuMemberShare.getPkId());
        return newCuMember;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean onlinePaymentCallBack(Long pkMember, String orderCode) {
        if (StringUtils.isEmpty(orderCode)) {
            return Boolean.FALSE;
        }
        log.info("在线支付回调接受的参数, pkMember:{}, orderCode:{}!", pkMember, orderCode);
        SaOrder querySaOrder = SaOrder.builder().orderStatus(EOrderStatus.WAIT_PAY.getValue()).orderCode(orderCode).build();

        SaOrderExt saOrderExt = querySaleOrderExtByOrderCode(querySaOrder, null);
        if (saOrderExt == null) {
            saOrderExt = redisService.getCacheObject(CacheConstants.TEMP_ORDER + pkMember + orderCode);
            if (saOrderExt == null) {
                // 订单已经不存在
                log.warn("在线支付回调,订单已经不存在");
                return Boolean.FALSE;
            }
        }
        log.info("在线支付回调接受的参数, order : {}", saOrderExt);
        saOrderExt.setPayType(EOrderPayType.ONLINE.getValue());

        CuMember newCuMember = null;
        if (saOrderExt.getPkMember() != null) {
            newCuMember = getCuMemberByKey(saOrderExt.getPkMember());
        }
        if (EOrderType.REGISTER_ORDER.getValue() == saOrderExt.getOrderType()
                || EOrderType.SPECIAL_REGISTER_ORDER.getValue() == saOrderExt.getOrderType()) {
            // 注册订单
            boolean isToBePay = getIsToBePayByOrderType(saOrderExt.getPkCountry(), saOrderExt.getOrderType());
            OrderParam orderParam = redisService.getCacheObject(CacheConstants.TEMP_PARAM + pkMember + orderCode);
            if (newCuMember == null && !isToBePay) {
                newCuMember = packageCuMember(orderParam);
                saOrderExt = packageSaOrder(orderParam, newCuMember);
                saOrderExt.setPayType(EOrderPayType.ONLINE.getValue());
            }
            if (newCuMember == null) {
                throw new RuntimeException("生成会员失败");
            }
            payRegSaOrder(saOrderExt, newCuMember, null, Boolean.FALSE);
        } else if (EOrderType.UPGRADE_ORDER.getValue() == saOrderExt.getOrderType()
                || EOrderType.SPECIAL_UPGRADE_ORDER.getValue() == saOrderExt.getOrderType()) {
            // 升级订单
            payUpgradeSaOrder(saOrderExt, null);
        } else {
            // 其他订单
            if (EOrderType.REPURCHASE_ORDER.getValue() == saOrderExt.getOrderType()
                    && EOrderTypeExtend.REG_REP.getValue().equals(saOrderExt.getOrderTypeExtend())) {
                log.info("==========注册转复购==========");
                if (null != newCuMember) {
                    // 先注册0元会员，再购买注册订单，复购订单 扩展类型为 注册转复购
                    OrderParam orderParam = redisService.getCacheObject(CacheConstants.TEMP_PARAM + pkMember + orderCode);
                    orderParam.setIsHaiFun(Boolean.TRUE);
                    orderParam.setOrderTypeExtend(saOrderExt.getOrderTypeExtend());

                    // 会员等级使用缓存中已经计算好的
                    newCuMember.setPkRegisterGrade(orderParam.getPkGrade());
                    newCuMember.setPkSettleGrade(orderParam.getPkGrade());

                    saOrderExt = packageWholeSaOrder(orderParam, newCuMember);
                    saOrderExt.setPayType(EOrderPayType.ONLINE.getValue());
                    if (!payReyZeroOrder(saOrderExt, newCuMember)) {
                        throw new ServiceException("会员或订单处理失败");
                    }
                } else {
                    // 188分享订单，复购订单 扩展类型为 注册转复购
                    OrderParam orderParam = redisService.getCacheObject(CacheConstants.TEMP_PARAM + pkMember + orderCode);
                    orderParam.setIsHaiFun(Boolean.TRUE);
                    orderParam.setOrderTypeExtend(saOrderExt.getOrderTypeExtend());

                    newCuMember = packageCuMember(orderParam);
                    // 会员ID已经提前生成，此处直接使用
                    if (null != orderParam.getPkMemberId()) {
                        newCuMember.setPkId(orderParam.getPkMemberId());
                        newCuMember.setPkCenterCode(null);
                    }

                    saOrderExt = packageSaOrder(orderParam, newCuMember);
                    saOrderExt.setPayType(EOrderPayType.ONLINE.getValue());
                    // 会员ID已经提前生成，此处直接使用
                    if (null != orderParam.getPkMemberId()) {
                        saOrderExt.setPkCreator(orderParam.getPkMemberId());
                        saOrderExt.setOrderCode(orderParam.getOrderCode());
                    }

                    if (newCuMember == null) {
                        throw new RuntimeException("生成会员失败");
                    }
                    payRegSaOrder(saOrderExt, newCuMember, null, Boolean.TRUE);
                }
            } else {
                payRepurchaseSaOrder(saOrderExt, null);
            }
        }
        log.info("在线支付回调成功，返回 {}", Boolean.TRUE);
        return Boolean.TRUE;
    }

    @Override
    public CuMemberShare queryCuMemberShare(Long pkMember) {
        return iMemberServiceApi.queryCuMemberShare(pkMember).getData();
    }

    private CuMember calculateHaFunMemberGrade(SaOrderExt saOrderExt, CuMember newCuMember) {
        CuMember cuMember = null;
//        if (newCuMember != null
//                && Objects.equals(MagicNumberConstants.CHINA_HA_FUN, newCuMember.getPkSettleGrade())
//                && Objects.equals(CountryConstants.CHINA_COUNTRY, newCuMember.getPkSettleCountry())) {
//            int oldLevel = newCuMember.getPkSettleGrade();
//            // 封装等级,重新计算会员等级
//            setLastCuMemberGrade(newCuMember, saOrderExt);
//            // 验证等级，原等级<新等级，才可以进行升级 或者事累计升级
//            if (oldLevel < newCuMember.getPkSettleGrade()) {
//                cuMember = newCuMember;
//            }
//        }
        return cuMember;
    }

    @Override
    public Boolean regEmptyOrderApproved(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        R<CuMemberServiceLog> cuMemberServiceLogR = iCuMemberServiceLogServiceApi.selectByBusinessNo(approvalBusinessResultDTO.getBusinessCode());
        OrderBlankRegParams orderBlankRegParams = JSONUtil.toBean(cuMemberServiceLogR.getData().getNewValue(), OrderBlankRegParams.class);
        // 调用空单注册方法
        this.registerEmptyOrder(orderBlankRegParams);
        return true;
    }

    @Override
    public Boolean regEmptyOrderReject(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        R<CuMemberServiceLog> cuMemberServiceLogR = iCuMemberServiceLogServiceApi.selectByBusinessNo(approvalBusinessResultDTO.getBusinessCode());
        OrderBlankRegParams orderBlankRegParams = JSONUtil.toBean(cuMemberServiceLogR.getData().getNewValue(), OrderBlankRegParams.class);
        CuMemberServiceLog memberLog = new CuMemberServiceLog();
        memberLog.setBusinessNo(approvalBusinessResultDTO.getBusinessCode());
        memberLog.setPkModified(approvalBusinessResultDTO.getLoginUser().getUserId());
        memberLog.setModifiedTime(DateUtils.currentDateTime());
        memberLog.setApproveStatus(EApproveStatus.REJECTED.getValue());
        iCuMemberServiceLogServiceApi.updateByBusinessNo(memberLog);
        List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
        MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
        memberAmountDTO.setPkMember(approvalBusinessResultDTO.getLoginUser().getUserId());
        if (StringUtils.isNotNull(orderBlankRegParams.getCost())) {
            memberAmountDTO.setTradeAmount(orderBlankRegParams.getCost());
        } else {
            memberAmountDTO.setTradeAmount(new BigDecimal(0));
        }
        memberAmountDTOList.add(memberAmountDTO);
        //退款
        BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
        businessCommissionDTO.setPkCountry(orderBlankRegParams.getPkCountry());
        businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
        businessCommissionDTO.setTradeType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
        R<Boolean> b = iMemberTradeServiceApi.businessCommissionSubmit(businessCommissionDTO);
        if (!b.getData()) {
            throw new ServiceException(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY);
        }
        return true;
    }

    @Override
    public void closeOrder() {
        R<Map<String, String>> configMap = iSystemConfigServiceApi.getSystemConfig();
        Map<String, String> configDate = configMap.getData();
        R<Map<Integer, BdCountry>> all = iCountryServiceApi.getAllCountryMap();
        Set<Map.Entry<Integer, BdCountry>> entries = all.getData().entrySet();

        for (Map.Entry<Integer, BdCountry> entry : entries) {
            BdCountry country = entry.getValue();
            for (int i = 0; i < ESystemConfig.getPayMentTimeList().size(); i++) {
                try {
                    String date = configDate.get(country.getPkId() + ESystemConfig.getPayMentTimeList().get(i).getKey());
                    // 查询可取消订单
                    if (StringUtils.isNotBlank(date)) {
                        Integer orderType = null;
                        if (ESystemConfig.getPayMentTimeList().get(i).getKey().equals(ESystemConfig.REGISTER_ORDER_TIME.getKey())) {
                            // 注册专区
                            orderType = EOrderType.REGISTER_ORDER.getValue();
                        } else if (ESystemConfig.getPayMentTimeList().get(i).getKey().equals(ESystemConfig.UPGRADE_ORDER_TIME.getKey())) {
                            // 升级专区
                            orderType = EOrderType.UPGRADE_ORDER.getValue();
                        } else if (ESystemConfig.getPayMentTimeList().get(i).getKey().equals(ESystemConfig.REPURCHASE_ORDER_TIME.getKey())) {
                            // 复购专区时间
                            orderType = EOrderType.REPURCHASE_ORDER.getValue();
                        } else if (ESystemConfig.getPayMentTimeList().get(i).getKey().equals(ESystemConfig.PICK_ORDER_TIME.getKey())) {
                            // 提货专区
                            orderType = EOrderType.PICK_ORDER.getValue();
                        }
                        ESpecialAreaTime specialAreaTime = ESpecialAreaTime.getSpecialAreaTime(date);
                        if (orderType != null && specialAreaTime != null) {
                            if (baseMapper.closeOrder(country.getPkId(), specialAreaTime.getAttributeValue(), orderType) > 0) {
                                iSaOrderItemsService.closeOrder(country.getPkId(), specialAreaTime.getAttributeValue(), orderType);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("自动关闭订单失败", e);
                }
            }
        }
    }

    @Override
    public List<SaOrder> querySaOrderByOrderType(String payTime) {
        return baseMapper.querySaOrderByOrderType(payTime);
    }

    @Override
    public List<Integer> queryOrderType(Long memberId, Integer pkCountry) {
        return baseMapper.queryOrderType(memberId, pkCountry);
    }

    @Override
    public void waresSalesAccrual(List<WaresNumberParam> waresNumberParamList) {
        try {
            if (waresNumberParamList.size() > 0) {
                iBdWaresExtendService.updateWaresSalesAccrual(waresNumberParamList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<DeliverSecondVO> secondList(DeliverSecondParam param, Integer pkCountry) {
        return baseMapper.secondList(param, pkCountry);
    }

    @Override
    public SaOrder queryOrderTotalAchieveByTime(Date startDate, Date endDate) {
        List<Integer> orderTypeList = new ArrayList<>();
        orderTypeList.add(EOrderType.REGISTER_ORDER.getValue());
        orderTypeList.add(EOrderType.UPGRADE_ORDER.getValue());
        QueryWrapper<SaOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("sum(order_amount) orderAmount,sum(order_achieve) orderAchieve")
                .eq(SaOrderFieldConstants.ORDER_STATUS, EOrderStatus.PAY.getValue())
                .in(SaOrderFieldConstants.ORDER_TYPE, orderTypeList)
                .ge(SaOrderFieldConstants.PAY_TIME, startDate)
                .lt(SaOrderFieldConstants.PAY_TIME, endDate);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List<Long> querySeqList(Integer param) {
        return baseMapper.querySeqList(param);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertBach(List<SaOrder> orderList, List<SaOrderItems> orderItemsList) {
        int i = baseMapper.insertBach(orderList);
        if (i > 0 && CollectionUtil.isNotEmpty(orderItemsList)) {
            iSaOrderItemsService.insertBach(orderItemsList);
        }
        return i;
    }

    @Override
    public List<MemberFirstOrderVo> checkMemberIsFirstOrder(List<String> memberCodeList) {
        return baseMapper.checkMemberIsFirstOrder(memberCodeList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void selfRevokeOrder(Long pkApprove, MyOrderVO myOrderVO) {
        SaOrderExt saOrderExt = myOrderVO.getSaOrderExt();
        BusinessCommissionDTO businessCommissionDTO = null;
        if (ObjectUtil.isNotEmpty(saOrderExt)) {
            // 删除订单
            saOrderExt.setDelFlag(EDelFlag.DELETE.getValue());
            Date currentDate = DateUtils.currentDateTime();
            // 删除发货单
            iSaDeliverItemsService.deleteSaDeliverItems(saOrderExt.getPkId(), null);
            // 修改订单
            updateSaOrder(pkApprove, saOrderExt, currentDate);
            // 删除订单明细
            if (!iSaOrderItemsService.updateOrderItems(saOrderExt)) {
                throw new RuntimeException("更新订单失败");
            }

            // 添加订单日志表
            // 本批订单修改记录编号
            String businessCode = CommonUtil.createSerialNumber(EOrderPrefix.DEFAULT);
            SaOrderChargeLog saOrderChargeLog = this.packageSaOrderChargeLog(currentDate, pkApprove,
                    EApprovalBusiness.ORDER_CANCEL.getValue(), businessCode, myOrderVO, EAgentApprovalStatus.APPROVED.getValue());
            MyOrderVO mo = new MyOrderVO();
            mo.setPkId(myOrderVO.getPkId());
            mo.setOrderCode(mo.getOrderCode());
            mo.setPkCreator(pkApprove);
            saOrderChargeLog.setAfterData(JSONUtil.toJsonStr(mo));
            saOrderChargeLog.setSource(ESignSource.MEMBER.getValue());
            iSaOrderChargeLogService.save(saOrderChargeLog);

            // 撤销注册订单(注册订单,海粉订单,特殊注册订单)
            if (myOrderVO.getOrderType() == EOrderType.REGISTER_ORDER.getValue()
                    || myOrderVO.getOrderType() == EOrderType.SPECIAL_REGISTER_ORDER.getValue()
                    || (myOrderVO.getOrderType() == EOrderType.REPURCHASE_ORDER.getValue() && EOrderTypeExtend.REG_REP.getValue() == saOrderExt.getOrderTypeExtend())
            ) {
                // 逻辑删除会员
                if (!iMemberServiceApi.singleRevokeMemberBySelfRevokeOrder(pkApprove, saOrderExt, businessCommissionDTO).getData()) {
                    throw new RuntimeException("撤单失败");
                }
            } else {
                // 其他撤单 撤销升级订单
                CuMember cuMember = getCuMemberByKey(saOrderExt.getPkMember());
                if (EOrderType.UPGRADE_ORDER.getValue() == saOrderExt.getOrderType()
                        || EOrderType.SPECIAL_UPGRADE_ORDER.getValue() == saOrderExt.getOrderType()
                ) {
                    SaOrder updSaOrder = myOrderVO.getUpdSaOrder();
                    // 计算等级
                    // 获取升级订单
                    // 空单注册，从cu_member_register中获取
                    if (updSaOrder == null) {
                        CuMemberRegister cuMemberRegister = iMemberServiceApi.queryCuMemberRegister(saOrderExt.getPkMember()).getData();
                        cuMember.setPkRegisterGrade(cuMemberRegister.getPkRegisterGrade());
                        cuMember.setPkSettleGrade(cuMemberRegister.getPkRegisterGrade());
                        cuMember.setConsumeMoney(BigDecimal.ZERO);
                        cuMember.setConsumeAchieve(cuMemberRegister.getConsumeAchieve());

                        // 查询最新一条升级记录
                        CuMemberLevel cuMemberLevel = iCuMemberDetailServiceApi.queryLastManualUpgrade(cuMember.getPkId(),
                                Arrays.asList(EUpgradeType.AUTO_UPGRADE.getValue(), EUpgradeType.MANUAL_UPGRADE.getValue()),
                                saOrderExt.getPkId()).getData();
                        if (null != cuMemberLevel) {
                            // 存在手动升级
                            cuMember.setPkSettleGrade(cuMemberLevel.getNewLevel());
                        }
                    } else {
                        OrderReturn orderReturn = OrderReturn.builder().isEnough(false).build();
                        GradeDTO gradeDTO = calculateGradeDTO(EOrderType.UPGRADE_ORDER.getValue(), cuMember.getPkSettleCountry(), cuMember.getPkId(),
                                myOrderVO.getUpdSaOrder(), orderReturn);
                        cuMember.setPkRegisterGrade(gradeDTO.getPkId());
                        cuMember.setPkSettleGrade(gradeDTO.getPkId());

                        // 查询最新一条升级记录
                        CuMemberLevel cuMemberLevel = iCuMemberDetailServiceApi.queryLastManualUpgrade(cuMember.getPkId(),
                                Arrays.asList(EUpgradeType.BUY_UPGRADE.getValue(), EUpgradeType.MANUAL_UPGRADE.getValue()),
                                saOrderExt.getPkId()).getData();
                        if (null != cuMemberLevel) {
                            // 存在手动升级
                            cuMember.setPkSettleGrade(cuMemberLevel.getNewLevel());
                        }

                        // 记录原奖衔与新奖衔
                        BdAwards tmpAwards;
                        // 判断奖衔，原奖衔>新奖衔 不进行变奖衔
                        BdAwards oldAwards = iAwardsServiceApi.getAwardsOne(cuMember.getPkAwards()).getData();
                        BdAwards newAwards = iAwardsServiceApi.getAwardsOne(gradeDTO.getPkAwards()).getData();
                        if (oldAwards.getAwardsValue() > newAwards.getAwardsValue()) {
                            cuMember.setPkAwards(gradeDTO.getPkAwards());
                            tmpAwards = newAwards;
                        } else {
                            tmpAwards = oldAwards;
                        }
                        // 查询最新一条手动开通奖衔记录
                        CuMemberAwardsExt cuMemberAwardsExt = iCuMemberDetailServiceApi.queryLastManualAwards(cuMember.getPkId()).getData();
                        if (null != cuMemberAwardsExt) {
                            // 存在手动开奖衔
                            if (cuMemberAwardsExt.getAwardsValue() > tmpAwards.getAwardsValue()) {
                                cuMember.setPkAwards(cuMemberAwardsExt.getNewLevel());
                            }
                        }

                        // 查询最新的手动开通注册权限的记录
                        CuMemberServiceLog cuMemberServiceLog = iCuMemberServiceLogServiceApi.selectTopData(cuMember.getPkId(), EApprovalBusiness.REGISTER_POWER_STATE.getValue(), EApproveStatus.FINISH.getValue()).getData();
                        if (null != cuMemberServiceLog && StringUtils.isNotEmpty(cuMemberServiceLog.getNewValue())) {
                            // 存在手动开通
                            if (Integer.parseInt(cuMemberServiceLog.getNewValue()) > gradeDTO.getRegisterAuthority()) {
                                // 手动开通注册权限 大于 降级之后的权限，则保留手动开通的权限
                                cuMember.setRegisterAuthority(Integer.parseInt(cuMemberServiceLog.getNewValue()));
                            } else {
                                cuMember.setRegisterAuthority(gradeDTO.getRegisterAuthority());
                            }
                        }

                        SaOrder saOrder = baseMapper.queryLastRegisterOrUpdate(cuMember.getPkId(), cuMember.getPkCountry());
                        if (null != saOrder) {
                            // 撤消升级单之后，获取注册或者最后的升级单，填充注册金额
                            cuMember.setConsumeMoney(saOrder.getOrderAmount());
                        } else {
                            // 没有注册或者升级单，则直接扣减升级单的订单金额
                            cuMember.setConsumeMoney(ComputeUtil.computeSubtract(cuMember.getConsumeMoney(), saOrderExt.getOrderAmount()));
                        }

                        cuMember.setConsumeAchieve(gradeDTO.getStartValue());
                    }
                } else if (myOrderVO.getOrderType() == EOrderType.PICK_ORDER.getValue()) {
                    //提货订单退还提货数量
                    if (!iAcPickService.cancelPickOrder(saOrderExt.getOrderCode(), pkApprove)) {
                        throw new RuntimeException("撤单失败");
                    }
                } else if (EOrderType.MALL_ORDER.getValue() == saOrderExt.getOrderType()) {
                    // 秒杀订单，处理限购
                    this.handleMallOrderCancel(saOrderExt);
                }

                if (!iMemberServiceApi.normalRevokeOrder(pkApprove, saOrderExt, cuMember, null, businessCommissionDTO).getData()) {
                    throw new RuntimeException("撤单失败");
                }
            }
            try {
                // 推送MQ，处理活动回退
                rabbitTemplate.convertAndSend(RabbitMqConstants.ORDER_CANCEL_EXCHANGE, RabbitMqConstants.ORDER_CANCEL_KEY, Collections.singletonList(saOrderExt));

//                if (EOrderType.UPGRADE_ORDER.getValue() == saOrderExt.getOrderType()) {
//                    // 升级订单撤单，推送会员续约处理MQ
//                    rabbitTemplate.convertAndSend(RabbitMqConstants.MEMBER_CONTINUE_EXCHANGE, RabbitMqConstants.MEMBER_CONTINUE_KEY,
//                            MemberContinueDTO.builder()
//                                    .pkMemberList(Collections.singletonList(saOrderExt.getPkMember()))
//                                    .eMemberContinue(EMemberContinue.UPGRADE_CANCEL)
//                                    .build());
//                } else if (EOrderType.REGISTER_ORDER.getValue() == saOrderExt.getOrderType()) {
//                    // 注册订单撤单，推送会员续约处理MQ
//                    rabbitTemplate.convertAndSend(RabbitMqConstants.MEMBER_CONTINUE_EXCHANGE, RabbitMqConstants.MEMBER_CONTINUE_KEY,
//                            MemberContinueDTO.builder()
//                                    .pkMemberList(Collections.singletonList(saOrderExt.getPkMember()))
//                                    .eMemberContinue(EMemberContinue.REGISTER_CANCEL)
//                                    .build());
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private SaOrderChargeLog packageSaOrderChargeLog(Date nowDate, Long userId, Integer chargeType, String businessCode,
                                                     MyOrderVO saOrder, Integer approvalStatus) {
        SaOrderChargeLog saOrderChargeLog = new SaOrderChargeLog();
        saOrderChargeLog.setPkOrder(saOrder.getPkId());
        saOrderChargeLog.setChargeType(chargeType);
        saOrderChargeLog.setPkCreator(userId);
        saOrderChargeLog.setCreationTime(nowDate);
        saOrderChargeLog.setPkModified(saOrderChargeLog.getPkCreator());
        saOrderChargeLog.setModifiedTime(saOrderChargeLog.getCreationTime());
        saOrderChargeLog.setPkCountry(saOrder.getPkCountry());
        saOrderChargeLog.setApprovalStatus(approvalStatus);
        saOrderChargeLog.setBusinessCode(businessCode);
        return saOrderChargeLog;
    }

    @Override
    public SaOrderExt queryByPkIdOrCode(Long pkOrder, String orderCode, Integer pkCountry) {
        return baseMapper.queryByPkIdOrCode(pkOrder, orderCode, pkCountry);
    }

    @Override
    public List<SingleItemStatVo> singleItemStat(SingleItemStatParam singleItemStatParam) {
        return baseMapper.singleItemStat(singleItemStatParam);
    }

    /**
     * 处理秒杀限购
     *
     * @param saOrderExt
     */
    private void handleMallOrder(SaOrderExt saOrderExt) {
        if (EOrderType.MALL_ORDER.getValue() == saOrderExt.getOrderType()) {
            // 秒杀订单，需要更新限购信息
            // key:商品ID，value:商品购买数量
            Map<Integer, Integer> limitMap = new HashMap<>();
            for (SaOrderItems saOrderItems : saOrderExt.getOrderItemsList()) {
                if (EYesNo.NO.getIntValue() == saOrderItems.getIsGift()) {
                    // 非赠品计算商品数量
                    limitMap.put(saOrderItems.getPkWares(), saOrderItems.getWaresQuantity());
                }
            }
            // 会员限购列表
            List<BdWaresMemberLimit> limitList = new ArrayList<>();
            for (Integer key : limitMap.keySet()) {
                for (ELimitType limitType : ELimitType.getLiveLimitType()) {
                    limitList.add(BdWaresMemberLimit.builder()
                            .pkMember(saOrderExt.getPkMember())
                            .pkWares(key)
                            .limitType(limitType.getValue())
                            .quantity(limitMap.get(key))
                            .limitDate(ELimitType.TOTAL.getValue() == limitType.getValue() ? ELimitType.TOTAL.getFormat() : DateUtils.parseDateToFormat(limitType.getFormat(), saOrderExt.getPayTime()))
                            .build());
                }
            }
            if (CollectionUtil.isNotEmpty(limitList)) {
                // 更新会员限购数据
                iBdWaresMemberLimitService.updateWaresMemberLimitBatch(limitList);
                // 更新商品限购库存
                iBdWaresExtendService.batchUpdateInventoryUse(limitList);
            }
        }
    }

    @Override
    public void checkMallOrder(SaOrderExt saOrderExt) {
        // key:商品ID，value:商品购买数量
        Map<Integer, Integer> limitMap = new HashMap<>();
        // key:商品ID,value:商品限购属性
        Map<Integer, BdWaresExtend> waresLimitMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(saOrderExt.getOrderItemsList())) {
            // 新创建订单
            for (SaOrderItems saOrderItems : saOrderExt.getOrderItemsList()) {
                if (EYesNo.NO.getIntValue() == saOrderItems.getIsGift()) {
                    // 非赠品
                    limitMap.put(saOrderItems.getPkWares(), saOrderItems.getWaresQuantity());
                }
            }
        } else {
            // 待支付订单
            for (SaOrderItems saOrderItems : saOrderExt.getOrderItemsExtList()) {
                if (EYesNo.NO.getIntValue() == saOrderItems.getIsGift()) {
                    // 非赠品
                    limitMap.put(saOrderItems.getPkWares(), saOrderItems.getWaresQuantity());
                }
            }
        }

        if (limitMap.size() > 0) {
            // 商品限购数据
            List<BdWaresExtend> waresExtendList = iBdWaresExtendService.listByPkWaresList(limitMap.keySet());
            for (BdWaresExtend bdWaresExtend : waresExtendList) {
                // 购买数量
                Integer waresQuantity = limitMap.get(bdWaresExtend.getPkWares());
                if (waresQuantity + bdWaresExtend.getInventoryUse() > bdWaresExtend.getInventory()) {
                    // 购买数量 + 已用库存  > 库存数量，不能购买
                    throw new ServiceException("购买商品库存已不足，无法下单");
                }
                if (waresQuantity > bdWaresExtend.getMemberLimit()
                        || waresQuantity > bdWaresExtend.getMemberMonthLimit()) {
                    // 购买数量 > 总限购 或 月限购，不能购买
                    throw new ServiceException("购买商品已经超过限购数量，无法下单");
                }
                waresLimitMap.put(bdWaresExtend.getPkWares(), bdWaresExtend);
            }
            // 会员购买数据
            List<BdWaresMemberLimit> memberLimitList = iBdWaresMemberLimitService.listMemberWaresLimit(saOrderExt.getPkMember(), limitMap.keySet());
            if (CollectionUtil.isNotEmpty(memberLimitList)) {
                // key: 商品+限购类型，value：数量
                Map<String, Integer> checkLimitMap = new HashMap<>();
                for (BdWaresMemberLimit bdWaresMemberLimit : memberLimitList) {
                    checkLimitMap.put(bdWaresMemberLimit.getPkWares() + "-" + bdWaresMemberLimit.getLimitDate(), bdWaresMemberLimit.getQuantity());
                }
                for (Integer tmpWares : waresLimitMap.keySet()) {
                    // 遍历商品进行判断是否超出限购
                    // 总限购
                    Integer totalLimit = checkLimitMap.get(tmpWares + "-" + ELimitType.TOTAL.getFormat());
                    if (null != totalLimit) {
                        // 总限购 + 本次购买数量
                        totalLimit = totalLimit + limitMap.get(tmpWares);
                        if (totalLimit > waresLimitMap.get(tmpWares).getMemberLimit()) {
                            // 购买数量 > 总限购，不能购买
                            throw new ServiceException("购买商品已经超过限购数量，无法下单");
                        }
                    }
                    // 月限购
//                    Integer monthLimit = checkLimitMap.get(tmpWares + "-" + DateUtils.parseDateToFormat(ELimitType.MONTH.getFormat(), saOrderExt.getPayTime()));
                    Integer monthLimit = checkLimitMap.get(tmpWares + "-" + DateUtils.parseDateToFormat(ELimitType.MONTH.getFormat(), new Date()));
                    if (null != monthLimit) {
                        // 月限购 + 本次购买数量
                        monthLimit = monthLimit + limitMap.get(tmpWares);
                        if (monthLimit > waresLimitMap.get(tmpWares).getMemberMonthLimit()) {
                            // 购买数量 > 月限购，不能购买
                            throw new ServiceException("购买商品已经超过限购数量，无法下单");
                        }
                    }
                }
            }
        }
    }

    /**
     * 秒杀订单回退限购
     *
     * @param saOrderExt
     */
    private void handleMallOrderCancel(SaOrderExt saOrderExt) {
        List<BdWaresMemberLimit> limitList = new ArrayList<>();
        for (SaOrderItems saOrderItems : saOrderExt.getOrderItemsExtList()) {
            if (EYesNo.NO.getIntValue() == saOrderItems.getIsGift()) {
                // 会员限购列表
                for (ELimitType limitType : ELimitType.getLiveLimitType()) {
                    limitList.add(BdWaresMemberLimit.builder()
                            .pkMember(saOrderExt.getPkMember())
                            .pkWares(saOrderItems.getPkWares())
                            .limitType(limitType.getValue())
                            .quantity(saOrderItems.getWaresQuantity() * -1)
                            .limitDate(ELimitType.TOTAL.getValue() == limitType.getValue() ? ELimitType.TOTAL.getFormat() : DateUtils.parseDateToFormat(limitType.getFormat(), saOrderExt.getPayTime()))
                            .build());
                }
            }
        }
        if (CollectionUtil.isNotEmpty(limitList)) {
            // 更新会员限购数据
            iBdWaresMemberLimitService.updateWaresMemberLimitBatch(limitList);
            // 更新商品限购库存
            iBdWaresExtendService.batchUpdateInventoryUse(limitList);
        }
    }

    /**
     * 同步全网产品库存
     *
     * @param saOrderExt
     */
    private void allProductSync(SaOrderExt saOrderExt) {
        if (EYesNo.NO.getIntValue() == BdConfig.getProductSync()) {
            return;
        }
        Map<Integer, BdProduct> productMap = iBdProductService.queryProductMap(saOrderExt.getOrderItemsList().stream().map(SaOrderItems::getPkProduct).collect(Collectors.toSet()), null);
        // 开启线程调用全网产品库存
        // 请求参数
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("source", BdConfig.getSysName());
        bodyMap.put("orderCode", saOrderExt.getOrderCode());
        List<Map<String, Object>> bodyDetailList = new ArrayList<>();
        for (SaOrderItems saOrderItems : saOrderExt.getOrderItemsList()) {
            Map<String, Object> detailMap = new HashMap<>();
            detailMap.put("wmsCode", productMap.get(saOrderItems.getPkProduct()).getWmsCode());
            detailMap.put("changeNum", saOrderItems.getQuantity());
            bodyDetailList.add(detailMap);
        }
        bodyMap.put("detailList", bodyDetailList);
        // 请求头
        String header = Base64Encoder.encode(BdConfig.getSysName() + "!" + saOrderExt.getOrderCode());
        ThreadUtils.threadPoolExecutor.submit(() -> {
            log.info("同步产品,header: {}", header);
            log.info("同步产品,bodyMap: {}", bodyMap);
            HttpRequest httpRequest = HttpUtil.createPost(BdConfig.getProductSyncUrl());
            httpRequest.header("authorization", header);
            httpRequest.body(JSONUtil.toJsonStr(bodyMap));
            httpRequest.setReadTimeout(5000);
            try {
                // 同步产品接口返回
                String resultStr = httpRequest.execute().body();
                AjaxResult ajaxResult = JSONUtil.toBean(resultStr, AjaxResult.class);
                log.info("同步产品,resultStr: {}", resultStr);
                if (!ajaxResult.isSuccess()) {
                    // 同步产品失败，250毫秒后重试
                    Thread.sleep(250);
                    resultStr = httpRequest.execute().body();
                    log.info("同步产品失败重试,resultStr: {}", resultStr);
                }
            } catch (Exception e) {
                log.error("同步产品库存异常", e);
                // 保存订单产品同步记录
                iSaOrderSyncService.save(SaOrderSync.builder()
                        .orderCode(saOrderExt.getOrderCode())
                        .bodyDetail(JSONUtil.toJsonStr(bodyDetailList))
                        .build());
            }
        });
    }


}
