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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.activity.pick.service.IAcRetailPickService;
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.utils.*;
import com.hzs.common.core.utils.reflect.ReflectUtils;
import com.hzs.common.domain.member.account.CuMemberAccount;
import com.hzs.common.domain.member.base.CuMember;
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.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.wares.BdWares;
import com.hzs.common.domain.system.base.BdCountry;
import com.hzs.common.domain.system.config.BdGrade;
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.IMemberBankServiceApi;
import com.hzs.member.account.IMemberTradeServiceApi;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.account.dto.CuMemberBankParam;
import com.hzs.member.account.dto.MemberAmountDTO;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.member.detail.ICuMemberServiceLogServiceApi;
import com.hzs.sale.deliver.service.ISaDeliverItemsService;
import com.hzs.sale.index.vo.CuMemberMyMarketDetailVO;
import com.hzs.sale.index.vo.CuMemberMyMarketVO;
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.wares.service.*;
import com.hzs.system.base.ICountryServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.ISystemConfigServiceApi;
import com.hzs.system.base.dto.CountryDTO;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IAreaCurrencyServiceApi;
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 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.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

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

    @DubboReference
    IMemberServiceApi iMemberServiceApi;
    @DubboReference
    IMemberBankServiceApi iMemberBankServiceApi;
    @DubboReference
    IMemberAccountServiceApi iMemberAccountServiceApi;
    @DubboReference
    IAreaCurrencyServiceApi iAreaCurrencyServiceApi;
    @DubboReference
    ICountryServiceApi iCountryServiceApi;
    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;
    @DubboReference
    IApprovalServiceApi iApprovalServiceApi;
    @DubboReference
    ISystemConfigServiceApi iSystemConfigServiceApi;
    @DubboReference
    ICuMemberServiceLogServiceApi iCuMemberServiceLogServiceApi;
    @DubboReference
    IMemberTradeServiceApi iMemberTradeServiceApi;
    @DubboReference
    IGradeServiceApi iGradeServiceApi;

    @Autowired
    private IBdWaresService iBdWaresService;
    @Autowired
    private SaOrderHandle saOrderHandle;
    @Autowired
    private ISaOrderItemsService saOrderItemsService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private IBdProductExtendService iBdProductExtendService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IBdWaresSpecsRelationService waresSpecsRelationService;
    @Autowired
    private ISaDeliverItemsService saDeliverItemsService;
    @Autowired
    private IAcRetailPickService iAcRetailPickService;

    @Autowired
    private IOrderBusinessService orderBusinessService;
    @Autowired
    private ISaOrderChargeLogService saOrderChargeLogService;

    @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(saOrderItemsService.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) {
        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);
        }
        return baseMapper.selectCount(queryWrapper);
    }

    @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 List<CuMemberAccountExt> queryMemberAccountByCondition(CuMemberAccount cuMemberAccount) {
        return iMemberAccountServiceApi.queryMemberAccountByCondition(cuMemberAccount).getData();
    }

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

        CuMember cuMember = getCuMemberByKey(saOrder.getPkMember());
        if (null != cuMember) {
            cuMemberAccount.setAccount1(BigDecimal.ZERO);
            cuMemberAccount.setAccount3(BigDecimal.ZERO);
            cuMemberAccount.setAccount4(BigDecimal.ZERO);
            cuMemberAccount.setAccount5(BigDecimal.ZERO);
            cuMemberAccount.setAccount6(BigDecimal.ZERO);
            cuMemberAccount.setAccount7(BigDecimal.ZERO);
            cuMemberAccount.setAccount8(BigDecimal.ZERO);
            cuMemberAccount.setAccount9(BigDecimal.ZERO);
            cuMemberAccount.setAccount10(BigDecimal.ZERO);
        }

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

        // 查询专区所属币种
        List<AreaCurrencyDTO> areaCurrencyDTOList = iAreaCurrencyServiceApi.queryAreaCurrencyByCondition(saOrder.getOrderType(), cuMemberAccount.getPkCountry()).getData();

        // 验证是否是跨国保单，登录结算国！=结算国，跨国报单修改支付金额
        if (!Objects.equals(cuMemberAccount.getPkCountry(), saOrder.getPkCountry())) {
            // 结算国当地币 转美金  美金登录当地币
            CurrencyDTO loginCountryCurrency = iCurrencyServiceApi.getCurrency(cuMemberAccount.getPkCountry()).getData();
            CurrencyDTO settleCountryCurrency = iCurrencyServiceApi.getCurrency(saOrder.getPkCountry()).getData();
            if (settleCountryCurrency.getInExchangeRate().compareTo(loginCountryCurrency.getInExchangeRate()) != 0) {
                // 订单结算国与登录结算国汇率不相同才进行处理
                payMoney = ComputeUtil.computeMultiply(ComputeUtil.computeDivide(payMoney, settleCountryCurrency.getInExchangeRate()), loginCountryCurrency.getInExchangeRate());
            }
        }
        BigDecimal postage = saOrder.getPostage();

        // 验证商品是否存在特殊消费配置
        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(saOrder, orderItemList, cuMemberAccount, orderItemPayMoney, BigDecimal.ZERO, areaCurrencyDtoList)) {
                        return null;
                    }
                }
            }
        }

        handleSaOrderAmount(saOrder, orderItemList, cuMemberAccount, payMoney, postage, areaCurrencyDTOList);

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

        return cuMemberAccount;
    }

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

        // 默认情况下，注册、升级专区才能使用政策币，其它专区都是走特殊业务处理
        // 个人政策币配置
        UpPolicyCurrency upPolicyCurrency = null;
        if (EOrderType.REGISTER_ORDER.getValue() == saOrder.getOrderType()) {
            if (cuMemberAccount.getPayAccount3Flag()) {
                // 验证是否有政策币权限
                List<CuMemberServiceLog> cuMemberServiceLogs = iCuMemberServiceLogServiceApi.queryMaxCuMemberServiceLog(cuMemberAccount.getPkMember(), Collections.singletonList(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue()));
                if (CollectionUtil.isNotEmpty(cuMemberServiceLogs)) {
                    Map<Integer, CuMemberServiceLog> cuMemberServiceLogMap = new HashMap<>(ComputeUtil.mapInitCapacity(cuMemberServiceLogs.size()));
                    cuMemberServiceLogs.forEach(serviceLog -> cuMemberServiceLogMap.put(serviceLog.getEditType(), serviceLog));

                    try {
                        upPolicyCurrency = JSONUtil.toBean(cuMemberServiceLogMap.get(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue()).getNewValue(), UpPolicyCurrency.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        for (AreaCurrencyDTO areaCurrencyDTO : areaCurrencyDTOList) {
            // 开始扣款
            // 待支付金额>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() + TransactionUtils.getContent(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
    public boolean getIsToBePayByOrderType(Integer pkCountry, Integer specialArea) {
        String confirmPay;
        if (EOrderType.REGISTER_ORDER.getValue() == specialArea) {
            confirmPay = querySystemConfigByKey(pkCountry, ESystemConfig.REGISTER_ORDER_CONFIRM_PAY.getKey());
        } else if (EOrderType.REPURCHASE_ORDER.getValue() == specialArea) {
            confirmPay = querySystemConfigByKey(pkCountry, ESystemConfig.REPURCHASE_ORDER_CONFIRM_PAY.getKey());
        } else if (EOrderType.CONSUME_ORDER.getValue() == specialArea) {
            confirmPay = querySystemConfigByKey(pkCountry, ESystemConfig.CONSUME_ORDER_CONFIRM_PAY.getKey());
        } else if (EOrderType.MALL_ORDER.getValue() == specialArea) {
            confirmPay = querySystemConfigByKey(pkCountry, ESystemConfig.REPURCHASE_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.REPURCHASE_ORDER.getValue() == specialArea) {
                timeType = querySystemConfigByKey(pkCountry, ESystemConfig.REPURCHASE_ORDER_TIME.getKey());
            } else if (EOrderType.CONSUME_ORDER.getValue() == specialArea) {
                timeType = querySystemConfigByKey(pkCountry, ESystemConfig.CONSUME_ORDER_TIME.getKey());
            } else if (EOrderType.MALL_ORDER.getValue() == specialArea) {
                timeType = querySystemConfigByKey(pkCountry, ESystemConfig.REGISTER_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;
    }

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

    /**
     * 生成空单注册
     *
     * @param orderBlankRegParams 参数
     */
    @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 ServiceException("保存会员失败");
            }
            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 ServiceException(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 = waresSpecsRelationService.selectByWaresSpecsSku(orderItem.getPkWaresSpecsSku());
            // 规格名称
            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()));
        }
        saOrderItemsService.saveBatch(orderItems);
        // 设置用户银行卡信息 国内页面隐藏
        if (loginUser.getDataCountry() != 1) {
            CuMemberBankParam memberBank = new CuMemberBankParam();
            memberBank.setPkMember(member.getPkId());
            memberBank.setPkCountry(orderBlankRegParams.getPkSettleCountry());
            memberBank.setBankName(orderBlankRegParams.getBankName());
            memberBank.setSubBankName(orderBlankRegParams.getOpeningBranch());
            memberBank.setCardNumber(orderBlankRegParams.getBankCard());
            memberBank.setAccountName(orderBlankRegParams.getOpeningName());
            memberBank.setPhone(orderBlankRegParams.getReservedPhone());
            memberBank.setIdCard(orderBlankRegParams.getIdCard());
            memberBank.setPkMember(member.getPkId());
            iMemberBankServiceApi.addBankInfo(memberBank);
        }
        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();
        CuMemberExt memberExt = iMemberServiceApi.getMemberById(saOrderExt.getPkMember()).getData();
        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 = orderBusinessService.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();
            // 删除发货单
            saDeliverItemsService.deleteSaDeliverItems(saOrderExt.getPkId(), pkOrderItemList);
            updateSaOrder(pkApprove, saOrderExt, currentDateTime);
            // 删除订单明细
            if (!saOrderItemsService.updateOrderItemsById(pkOrderItemList, pkApprove, currentDateTime)) {
                throw new ServiceException("更新订单失败");
            }
            if (!iMemberServiceApi.normalRevokeOrder(pkApprove, saOrderExt, null, businessCommissionDTO).getData()) {
                throw new ServiceException("撤单失败");
            }
        } else {
            // 删除订单
            saOrderExt.setDelFlag(EDelFlag.DELETE.getValue());
            Date currentDate = DateUtils.currentDateTime();
            // 删除发货单
            saDeliverItemsService.deleteSaDeliverItems(saOrderExt.getPkId(), null);
            // 修改订单
            updateSaOrder(pkApprove, saOrderExt, currentDate);
            // 删除订单明细
            if (!saOrderItemsService.updateOrderItems(saOrderExt)) {
                throw new ServiceException("更新订单失败");
            }

            // 撤销注册订单 单点撤单
            if (ECancelOrderType.SINGLE_CANCEL_ORDER.getValue() == orderCancelParam.getCancelType()
                    || (ObjectUtil.isNotEmpty(memberExt) && ECancelOrderType.OTHER_CANCEL_ORDER.getValue() == orderCancelParam.getCancelType() && saOrderExt.getPayTime().equals(memberExt.getPayTime()))
            ) {
                // 单点撤单，变死点
                R<Boolean> tmpR = iMemberServiceApi.singleRevokeMemberByRegisterOrder(pkApprove, saOrderExt, businessCommissionDTO);
                if (!tmpR.isSuccess()) {
                    throw new ServiceException("撤单失败 " + 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)) {
                    // 撤销所有订单明细表
                    saOrderItemsService.updateOrderItemsByMemberList(memberList, pkApprove, currentDate);
                    // 撤销所有订单主表
                    baseMapper.updateSaOrderByMember(memberList, pkApprove, currentDate);
                }

                R<Boolean> tmpR = iMemberServiceApi.mergeRevokeMemberByRegisterOrder(pkApprove, memberList, validateCancelOrderVO.getSaOrderMap(), businessCommissionDTO);
                if (!tmpR.isSuccess()) {
                    throw new ServiceException("撤单失败 " + tmpR.getMsg());
                }
            } else {
                // 其他撤单
                this.handleCancelUpgradeOrder(saOrderExt, validateCancelOrderVO.getUpdSaOrder(), pkApprove, businessCommissionDTO);
            }
        }

        try {
            // 撤单秒结处理
            this.pushCancelOrderMq(saOrderExt);
            // 推送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);
        } 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 ServiceException("更新订单失败");
        }
    }

    @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 saOrderItemsService.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()) {
            // 注册类订单，需要校验是否推荐过人或者安置过人，如果有则不允许进行取消
            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);
        saOrderItemsService.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()) {
            if (!iMemberServiceApi.cancelMember(saOrder.getPkMember()).getData()) {
                throw new ServiceException("取消订单失败");
            }
        }

        return null;
    }

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

    @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);
        saOrderItemsService.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);
    }

    @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.REPURCHASE_ORDER_TIME.getKey())) {
                            // 复购专区时间
                            orderType = EOrderType.REPURCHASE_ORDER.getValue();
                        }
                        ESpecialAreaTime specialAreaTime = ESpecialAreaTime.getSpecialAreaTime(date);
                        if (orderType != null && specialAreaTime != null) {
                            if (baseMapper.closeOrder(country.getPkId(), specialAreaTime.getAttributeValue(), orderType) > 0) {
                                saOrderItemsService.closeOrder(country.getPkId(), specialAreaTime.getAttributeValue(), orderType);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("自动关闭订单失败", e);
                }
            }
        }
    }

    @Override
    public BigDecimal selectBySumPv(Date startPayDate, Date endPayDate, Long memberId) {
        return baseMapper.selectBySumPv(startPayDate, endPayDate, memberId);
    }

    @Override
    public BigDecimal selectBySumAmount(Date startPayDate, Date endPayDate, Long memberId) {
        return baseMapper.selectBySumAmount(startPayDate, endPayDate, memberId);
    }

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

    @Override
    public CuMemberMyMarketVO selectMyMarket(Long pkMember, Integer pkCountry) {
        //查询全国市场
        CuMemberMyMarketVO cuMemberMyMarketVO = baseMapper.selectMyMarket(null, pkCountry);
        CountryDTO country = iCountryServiceApi.getCountry(pkCountry).getData();
        //查询市场分布
        List<CuMemberMyMarketDetailVO> cuMemberMyMarketDetailVOList = baseMapper.selectMyMarketDetail(pkMember, pkCountry);
        cuMemberMyMarketVO.setMyMarketDetailVOList(cuMemberMyMarketDetailVOList);
        //查询我的市场
        if (CollectionUtil.isNotEmpty(cuMemberMyMarketDetailVOList)) {
            List<Integer> countryNmus = cuMemberMyMarketDetailVOList.stream().map(CuMemberMyMarketDetailVO::getPkCountry).distinct().collect(Collectors.toList());
            cuMemberMyMarketVO.setMyCountryNum(countryNmus.size());
            cuMemberMyMarketVO.setMyRegionNum(cuMemberMyMarketDetailVOList.size());
        } else {
            cuMemberMyMarketVO.setMyCountryNum(1);
            cuMemberMyMarketVO.setMyRegionNum(0);
        }
        //海外暂时点亮国家
        if (!pkCountry.equals(CountryConstants.CHINA_COUNTRY)) {
            cuMemberMyMarketVO.setMyMarketDetailVOList(Collections.singletonList(CuMemberMyMarketDetailVO.builder().lightName(country.getLightName()).build()));
        }
        return cuMemberMyMarketVO;
    }

    @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)) {
            saOrderItemsService.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();
        if (saOrderExt != null) {
            // 删除订单
            saOrderExt.setDelFlag(EDelFlag.DELETE.getValue());
            Date currentDate = DateUtils.currentDateTime();
            // 删除发货单
            saDeliverItemsService.deleteSaDeliverItems(saOrderExt.getPkId(), null);
            // 修改订单
            updateSaOrder(pkApprove, saOrderExt, currentDate);
            // 删除订单明细
            if (!saOrderItemsService.updateOrderItems(saOrderExt)) {
                throw new ServiceException("更新订单失败");
            }

            // 本批订单修改记录编号
            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());
            saOrderChargeLogService.save(saOrderChargeLog);

            // 撤销注册订单
            CuMember member = iMemberServiceApi.getMember(SecurityUtils.getUserId()).getData();
            if (myOrderVO.getOrderType() == EOrderType.RETAIL_REGISTER.getValue()
                    || (myOrderVO.getOrderType() == EOrderType.RETAIL_REPURCHASE.getValue()
                    && myOrderVO.getPayTime().equals(member.getPayTime())
                    && member.getCreationTime().equals(member.getPayTime()))
            ) {
                // 逻辑删除会员
                if (!iMemberServiceApi.singleRevokeMemberBySelfRevokeOrder(pkApprove, saOrderExt, null).getData()) {
                    throw new ServiceException("撤单失败");
                }
            } else {
                // 其他撤单
                this.handleCancelUpgradeOrder(saOrderExt, myOrderVO.getUpdSaOrder(), pkApprove, null);
            }

            try {
                // 撤单秒结处理
                this.pushCancelOrderMq(saOrderExt);
                // 推送MQ，处理活动回退
                rabbitTemplate.convertAndSend(RabbitMqConstants.ORDER_CANCEL_EXCHANGE, RabbitMqConstants.ORDER_CANCEL_KEY, Collections.singletonList(saOrderExt));
            } 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);
    }

    @Override
    public CuMemberAccountExt queryRetailOrderSpendDetails(CuMemberAccountExt cuMemberAccount, SaOrder saOrder, List<SaOrderItems> orderItemList) {
        // 订单金额
        BigDecimal payMoney = saOrder.getOrderAmount();
        // 订单邮费
        BigDecimal postage = saOrder.getPostage();

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

        // 查询专区所属币种
        List<AreaCurrencyDTO> areaCurrencyDTOList = iAreaCurrencyServiceApi.queryAreaCurrencyByCondition(ESpecialArea.getRetailSpecialAreaValue(saOrder.getOrderType()), cuMemberAccount.getPkCountry()).getData();

        // 验证会员是否存在特殊消费配置
        List<AreaCurrencyDTO> memberCurrencyDTOList = iAreaCurrencyServiceApi.queryMemberCurrency(ESpecialArea.getRetailSpecialAreaValue(saOrder.getOrderType()), cuMemberAccount.getPkMember()).getData();
        if (CollectionUtil.isNotEmpty(memberCurrencyDTOList)) {
            areaCurrencyDTOList = memberCurrencyDTOList;
        } else {
            // 验证商品是否存在特殊消费配置
            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 (!handleRetailSaOrderAmount(saOrder, cuMemberAccount, orderItemPayMoney, BigDecimal.ZERO, areaCurrencyDtoList)) {
                            return null;
                        }
                    }
                }
            }
        }

        handleRetailSaOrderAmount(saOrder, cuMemberAccount, payMoney, postage, areaCurrencyDTOList);

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

    /**
     * 新零售订单付款处理
     *
     * @param saOrder
     * @param cuMemberAccount
     * @param payMoney
     * @param postage
     * @param areaCurrencyDTOList
     * @return
     */
    private Boolean handleRetailSaOrderAmount(SaOrder saOrder, CuMemberAccountExt cuMemberAccount,
                                              BigDecimal payMoney, BigDecimal postage,
                                              List<AreaCurrencyDTO> areaCurrencyDTOList) {
        boolean flag = Boolean.TRUE;
        if (!ComputeUtil.compareValue(ComputeUtil.computeAdd(payMoney, postage))) {
            return Boolean.TRUE;
        }
        cuMemberAccount.setIsPayment(Boolean.FALSE);
        // 原始支付金额（订单金额 + 邮费）
        BigDecimal original = payMoney;

        // 2024.05.30 与业务确认，政策币个人配置优先特殊配置
        // 默认情况下，注册、升级专区才能使用政策币，其它专区都是走特殊业务处理
        // 个人政策币配置
        UpPolicyCurrency upPolicyCurrency = null;
        if (EOrderType.RETAIL_REGISTER.getValue() == saOrder.getOrderType()) {
            if (cuMemberAccount.getPayAccount3Flag()) {
                // 验证是否有政策币权限
                List<CuMemberServiceLog> cuMemberServiceLogs = iCuMemberServiceLogServiceApi.queryMaxCuMemberServiceLog(cuMemberAccount.getPkMember(), Collections.singletonList(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue()));
                if (CollectionUtil.isNotEmpty(cuMemberServiceLogs)) {
                    Map<Integer, CuMemberServiceLog> cuMemberServiceLogMap = new HashMap<>(ComputeUtil.mapInitCapacity(cuMemberServiceLogs.size()));
                    cuMemberServiceLogs.forEach(serviceLog -> cuMemberServiceLogMap.put(serviceLog.getEditType(), serviceLog));

                    try {
                        upPolicyCurrency = JSONUtil.toBean(cuMemberServiceLogMap.get(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue()).getNewValue(), UpPolicyCurrency.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        for (AreaCurrencyDTO areaCurrencyDTO : areaCurrencyDTOList) {
            // 开始扣款
            // 待支付金额>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() + TransactionUtils.getContent(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;
    }

    /**
     * 处理撤销升级订单
     *
     * @param saOrderExt            订单信息
     * @param updSaOrder            升级订单
     * @param pkApprove             操作人
     * @param businessCommissionDTO 业务处理DTO
     */
    private void handleCancelUpgradeOrder(SaOrderExt saOrderExt, SaOrder updSaOrder, Long pkApprove, BusinessCommissionDTO businessCommissionDTO) {
        // 其他撤单 撤销升级订单
        CuMember cuMember = getCuMemberByKey(saOrderExt.getPkMember());
        if (EOrderType.RETAIL_UPGRADE.getValue() == saOrderExt.getOrderType()) {
            // 处理等级
            // 获取最新的升级记录，如果没有则查询会员的注册信息
            // 查询会员升级记录表最终数据
            CuMemberLevel cuMemberLevel = iMemberServiceApi.getLastUpgrade(cuMember.getPkId(), saOrderExt.getPkId()).getData();
            if (null != cuMemberLevel) {
                // 存在升级记录
                cuMember.setPkSettleGrade(cuMemberLevel.getNewLevel());
            } else {
                // 没有升级记录，重置成会员
                cuMember.setPkSettleGrade(iGradeServiceApi.getGradeByGradeValue(EGrade.MEMBER.getValue(), saOrderExt.getPkCountry()).getData().getPkId());
                cuMember.setConsumeMoney(BigDecimal.ZERO);
                cuMember.setConsumeAchieve(BigDecimal.ZERO);
            }
            saOrderExt.setUpdateFlag(EYesNo.YES.getIntValue());
        } else if (EOrderType.RETAIL_PICK.getValue() == saOrderExt.getOrderType()) {
            // 新提货订单
            if (!iAcRetailPickService.cancelRetailPickOrder(saOrderExt.getPkId(), pkApprove)) {
                throw new ServiceException("撤销订单退还提货失败");
            }
        }

        if (EOrderType.RETAIL_REGISTER.getValue() == saOrderExt.getOrderType()
                || EOrderType.RETAIL_UPGRADE.getValue() == saOrderExt.getOrderType()
                || EOrderType.RETAIL_REPURCHASE.getValue() == saOrderExt.getOrderType()) {
            // 判断处理支付状态和时间
            Date firstPayTime = baseMapper.getFirstPayTime(saOrderExt.getPkMember());
            if (null == firstPayTime) {
                cuMember.setPayTime(null);
                cuMember.setPayStatus(EPayStatus.UNPAID.getValue());
            } else {
                if (firstPayTime.compareTo(cuMember.getPayTime()) < 0) {
                    cuMember.setPayTime(firstPayTime);
                }
            }
        }

        if (!iMemberServiceApi.normalRevokeOrder(pkApprove, saOrderExt, cuMember, businessCommissionDTO).getData()) {
            throw new ServiceException("撤单处理会员失败");
        }
    }

    /**
     * 订单推送MQ处理
     *
     * @param saOrderExt 会员订单
     */
    private void pushCancelOrderMq(SaOrderExt saOrderExt) {
        try {
            if (EOrderType.RETAIL_REGISTER.getValue() == saOrderExt.getOrderType()
                    || EOrderType.RETAIL_REPURCHASE.getValue() == saOrderExt.getOrderType()
                    || EOrderType.RETAIL_CONSUME.getValue() == saOrderExt.getOrderType()) {
                // 撤单标记为 true
                saOrderExt.setCancelBool(Boolean.TRUE);
                // 计算奖金，通过mq分发消息，异步处理
                log.info("{} 秒结消息，order.second.exchange：{}", SysConstants.RETAIL_PREFIX, saOrderExt.getOrderCode());
                rabbitTemplate.convertAndSend(RabbitMqConstants.ORDER_SECOND_EXCHANGE, RabbitMqConstants.ORDER_SECOND_KEY, saOrderExt);
            }
        } catch (Exception e) {
            log.error("{} pushOrderMq 推送MQ失败. order: {}", SysConstants.RETAIL_PREFIX, saOrderExt, e);
        }
    }


    @Override
    public BdGrade calculateGrade() {
        GradeDTO gradeDTO = iGradeServiceApi.getGradeByGradeValue(EGrade.MEMBER.getValue(), CountryConstants.CHINA_COUNTRY).getData();
        // 返回等级
        return BeanUtil.copyProperties(gradeDTO, BdGrade.class);
    }

    @Override
    public boolean showDiscountArea() {
        if (ObjectUtil.isEmpty(SecurityUtils.getUserId())) {
            return false;
        }
        LambdaQueryWrapper<SaOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SaOrder::getPkMember, SecurityUtils.getUserId());
        wrapper.eq(SaOrder::getDelFlag, EDelFlag.UN_DELETE.getValue());
        wrapper.eq(SaOrder::getOrderStatus, EOrderStatus.PAY.getValue());
        wrapper.in(SaOrder::getOrderType, Arrays.asList(EOrderType.RETAIL_REGISTER.getValue(), EOrderType.RETAIL_UPGRADE.getValue()));
        return baseMapper.selectCount(wrapper) > 0;
    }


}
