package com.hzs.retail.sale.controller.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.RepeatSubmit;
import com.hzs.common.core.config.BdConfig;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EGrade;
import com.hzs.common.core.enums.ESpecialArea;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.ext.CuMemberAccountExt;
import com.hzs.common.domain.retail.member.ext.CuMemberRetailRegionExt;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.system.config.BdGrade;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.retail.sale.controller.service.IRetailOrderService;
import com.hzs.retail.sale.param.*;
import com.hzs.retail.sale.vo.*;
import com.hzs.sale.order.param.*;
import com.hzs.sale.order.service.ISaOrderService;
import com.hzs.sale.shopping.service.IShoppingCartService;
import com.hzs.sale.shopping.vo.ProductGroup;
import com.hzs.sale.shopping.vo.ShoppingCartRedis;
import com.hzs.sale.shopping.vo.ShoppingCartVO;
import com.hzs.system.base.IAreaServiceApi;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 新零售订单控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/retail-order")
public class ApiRetailOrderController {

    @Autowired
    private IRetailOrderService iRetailOrderService;
    @Autowired
    private ISaOrderService iSaOrderService;
    @Autowired
    private IShoppingCartService shoppingCartService;
    @Autowired
    private RedisService redisService;

    @DubboReference
    IMemberServiceApi iMemberServiceApi;
    @DubboReference
    IGradeServiceApi iGradeServiceApi;
    @DubboReference
    IAreaServiceApi iAreaServiceApi;

    /**
     * 校验会员等级
     *
     * @param levelParam 入参
     * @return
     */
    @PostMapping("/valid-mem-level")
    public AjaxResult validMemLevel(@Valid @RequestBody RetailOrderLevelParam levelParam) {
        // 返回VO
        RetailerOrderLevelVO orderLevelVO = RetailerOrderLevelVO.builder()
                .isEnough(false)
                .build();

        if (ESpecialArea.RETAIL_UPGRADE.getValue() == levelParam.getSpecialArea()) {
            // 升级校验
            if (StringUtils.isEmpty(levelParam.getUpgradeMemberCode())) {
                return AjaxResult.error("升级编号不能为空");
            }

            CuMember updateGradeMember = iMemberServiceApi.getRetailMember(null, levelParam.getUpgradeMemberCode()).getData();
            if (null == updateGradeMember) {
                throw new ServiceException("升级编号不存在，请重试");
            }
            levelParam.setUpgradeMember(updateGradeMember);
        }

        try {
            // 购物车中获取商品信息，获取等级
            BdGrade bdGrade = iSaOrderService.calculateGrade(levelParam.getSpecialArea(), convertShoppingCarToSku(SecurityUtils.getUserId(), levelParam.getShopList()),
                    null, levelParam.getUpgradeMember(), SecurityUtils.getSystemType(), EYesNo.NO.getIntValue());
            if (null != bdGrade) {
                orderLevelVO.setIsEnough(true);
                orderLevelVO.setPkGradeVal(bdGrade.getGradeName());
                orderLevelVO.setGradeValue(bdGrade.getGradeValue());
            } else {
                orderLevelVO.setMsg("会员不满足升级条件");
            }
        } catch (ServiceException e) {
            log.error("校验会员等级服务异常", e);
            orderLevelVO.setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("会员等级判断异常", e);
            orderLevelVO.setMsg("会员等级判断异常");
        }
        return AjaxResult.success(orderLevelVO);
    }

    /**
     * 校验推荐人
     *
     * @param parentParam 入参
     * @return
     */
    @PostMapping("/valid-p-code")
    public AjaxResult validPCode(@Valid @RequestBody RetailOrderParentParam parentParam) {
        // 推荐人是不是在会员伞下
        R<CuMember> parentMemberResult = this.checkParent(parentParam.getParent(), SecurityUtils.getUserId());
        if (!parentMemberResult.isSuccess()) {
            return AjaxResult.error(parentMemberResult.getMsg());
        }

        CuMember parentMember = parentMemberResult.getData();
        return AjaxResult.success(RetailOrderParentVO.builder()
                .parent(parentMember.getMemberCode())
                .parentName(parentMember.getMemberName())
                .build());
    }

    /**
     * 校验会员是否跨团队
     *
     * @param relationParam 校验入参
     * @return
     */
    @PostMapping("/valid-relation")
    public AjaxResult validRelation(@Valid @RequestBody RetailOrderRelationParam relationParam) {
        // new 手机号可以重复，不需要进行是否重复校验 -- 已经跳过，此处可以不需要当前判断
//        String relationStr = iMemberServiceApi.checkRegisterRelation(relationParam.getPhone(), relationParam.getParentCode()).getData();
//        if (relationStr != null) {
//            return AjaxResult.error(relationStr);
//        }
        return AjaxResult.success();
    }

    /**
     * 查询邮费
     *
     * @param postageParam 邮费入参
     * @return
     */
    @PostMapping("/query-order-postage")
    public AjaxResult queryOrderPostage(@Valid @RequestBody RetailOrderPostageParam postageParam) {
        // 当前会员ID
        postageParam.setPkCreator(SecurityUtils.getUserId());

        if (ESpecialArea.RETAIL_REGISTER.getValue() == postageParam.getSpecialArea()
                || ESpecialArea.RETAIL_UPGRADE.getValue() == postageParam.getSpecialArea()) {
            // 注册、升级包邮
            return AjaxResult.success(RetailOrderPostageVO.builder()
                    .postage(BigDecimal.ZERO)
                    .build());
        } else {
            CuMember buyMember;
            if (StringUtils.isNotEmpty(postageParam.getBuyMemberCode())) {
                // 购买人不为空，则需要查询重新赋一下
                buyMember = iMemberServiceApi.getRetailMember(null, postageParam.getBuyMemberCode()).getData();
                if (null == buyMember) {
                    return AjaxResult.error("会员编号不存在");
                }
            } else {
                buyMember = iMemberServiceApi.getRetailMember(postageParam.getPkCreator(), null).getData();
            }

            // 查询邮费
            RetailOrderParam orderParam = BeanUtil.copyProperties(postageParam, RetailOrderParam.class);
            // 购物车中获取商品信息
            orderParam.setOrderItemsParams(convertShoppingCarToSku(postageParam.getPkCreator(), postageParam.getShopList()));

            iRetailOrderService.createSaOrderItems(orderParam, null, buyMember, null, null);

            return AjaxResult.success(RetailOrderPostageVO.builder()
                    .postage(orderParam.getPostage())
                    .build());
        }
    }

    /**
     * 确认注册订单
     *
     * @param registerParam 订单入参
     * @param source        数据来源
     * @return
     */
    @RepeatSubmit
    @PostMapping("/confirm-reg-order")
    public AjaxResult confirmRegisterOrder(@Valid @RequestBody RetailOrderRegisterParam registerParam,
                                           @RequestHeader("Source") Integer source) {
        // 设置数据来源
        registerParam.setSource(source);
        // 会员ID
        registerParam.setPkCreator(SecurityUtils.getUserId());
        // 新零售注册专区
        registerParam.setSpecialArea(ESpecialArea.RETAIL_REGISTER.getValue());
        // 系统类型
        registerParam.setSystemType(SecurityUtils.getSystemType());

        // 获取等级列表
        List<BdGrade> gradeList = iGradeServiceApi.getRetailGradeList().getData();
        // 校验注册权限等
        String checkStr = this.checkRegistrationPermission(registerParam, gradeList);
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 校验会员选择区域是否已经被占用
        checkStr = this.checkRegionNum(registerParam);
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 手机号可以重复，不需要进行是否重复校验 -- 已经跳过，此处可以不需要当前判断
//        // 校验注册关系（是否跨团队） -- 2024.12.24 修改为校验手机号必须唯一
//        String relationStr = iMemberServiceApi.checkRegisterRelation(registerParam.getPhone(), registerParam.getParentCode()).getData();
//        if (relationStr != null) {
//            return AjaxResult.error(relationStr);
//        }

        // 购物车中获取商品信息
        registerParam.setOrderItemsParams(convertShoppingCarToSku(registerParam.getPkCreator(), registerParam.getShopList()));

        // 确认订单
        String str = iRetailOrderService.confirmRegOrder(registerParam, gradeList);
        return confirmOrderReturn(str, registerParam.getPkCreator(), registerParam.getShopList(), registerParam.getOrderCode());
    }

    /**
     * 支付注册订单
     *
     * @param payParam 支付订单入参
     * @return
     */
    @RepeatSubmit
    @PostMapping("/pay-reg-order")
    public AjaxResult payRegisterOrder(@Valid @RequestBody RetailOrderPayParam payParam) {
        // 当前会员ID
        Long pkMember = SecurityUtils.getUserId();

        // 获取缓存参数
        RetailOrderRegisterParam registerParam = redisService.getCacheObject(CacheConstants.RETAIL_TEMP_REG_PARAM + pkMember + payParam.getOrderCode());
        if (null == registerParam) {
            return AjaxResult.error("订单长时间没有支付，已经失效，请重新下单");
        }
        if (null == registerParam.getSystemType()) {
            registerParam.setSystemType(SecurityUtils.getSystemType());
        }

        // 等级列表
        List<BdGrade> gradeList = iGradeServiceApi.getRetailGradeList().getData();
        // 校验注册权限等
        String checkStr = this.checkRegistrationPermission(registerParam, gradeList);
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 校验会员选择区域是否已经被占用
        checkStr = this.checkRegionNum(registerParam);
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 手机号可以重复，不需要进行是否重复校验 -- 已经跳过，此处可以不需要当前判断
//        // 校验注册关系（是否跨团队） -- 2024.12.24 修改为校验手机号必须唯一
//        String relationStr = iMemberServiceApi.checkRegisterRelation(registerParam.getPhone(), registerParam.getParentCode()).getData();
//        if (relationStr != null) {
//            return AjaxResult.error(relationStr);
//        }

        // 支付入参
        registerParam.setIsPay(EYesNo.YES.getIntValue());

        // 封装会员信息
        CuMember newMember = iRetailOrderService.packageCuMember(registerParam);
        // 封装订单信息
        SaOrderExt saOrderExt = iRetailOrderService.createSaOrder(registerParam, gradeList, newMember);

        // 校验会员账户状态等
        R<CuMemberAccountExt> accountResult = iRetailOrderService.validMemberAccount(pkMember, payParam.getPayPwd());
        if (!accountResult.isSuccess()) {
            return AjaxResult.error(accountResult.getMsg());
        }
        CuMemberAccountExt memberAccountExt = accountResult.getData();

        // 校验余额是否足够
        iSaOrderService.queryRetailOrderSpendDetails(memberAccountExt, saOrderExt, saOrderExt.getOrderItemsList());
        if (memberAccountExt.getIsPayment()) {
            // 进行支付
            saOrderExt.setSpecialArea(registerParam.getSpecialArea());
            saOrderExt.setRegionProvince(registerParam.getRegionProvince());
            saOrderExt.setRegionCity(registerParam.getRegionCity());
            saOrderExt.setRegionCounty(registerParam.getRegionCounty());
            String payStr = iRetailOrderService.payRegOrder(saOrderExt, newMember, memberAccountExt);
            if (null != payStr) {
                return AjaxResult.error(payStr);
            }
        } else {
            if (StringUtils.isEmpty(memberAccountExt.getErrorMsg())) {
                return AjaxResult.error("余额不足，请及时充值");
            } else {
                return AjaxResult.error(memberAccountExt.getErrorMsg());
            }
        }

        // 注册成功返回信息
        return AjaxResult.success(RetailOrderVO.builder()
                .memberCode(newMember.getMemberCode())
                .memberName(newMember.getMemberName())
                .phone(newMember.getPhone())
                .loginPassword(newMember.getLoginPassword())
                .payPassword(newMember.getPayPassword())
                .urlAddress(BdConfig.getPc())
                .build());
    }

    /**
     * 确认升级订单
     *
     * @param upgradeParam 订单入参
     * @param source       数据来源
     * @return
     */
    @RepeatSubmit
    @PostMapping("/confirm-upg-order")
    public AjaxResult confirmUpgradeOrder(@Valid @RequestBody RetailOrderUpgradeParam upgradeParam,
                                          @RequestHeader("Source") Integer source) {
        // 设置数据来源
        upgradeParam.setSource(source);
        // 会员ID
        upgradeParam.setPkCreator(SecurityUtils.getUserId());
        // 新零售注册专区
        upgradeParam.setSpecialArea(ESpecialArea.RETAIL_UPGRADE.getValue());
        // 系统类型
        upgradeParam.setSystemType(SecurityUtils.getSystemType());

        // 升级会员
        CuMember updateGradeMember = iMemberServiceApi.getRetailMember(null, upgradeParam.getUpgradeMemberCode()).getData();
        if (null == updateGradeMember) {
            throw new ServiceException("升级编号不存在，请重试");
        }
        String otherCheckStr = this.otherOrderCheck(updateGradeMember, upgradeParam.getSpecialArea());
        if (null != otherCheckStr) {
            return AjaxResult.error(otherCheckStr);
        }
        upgradeParam.setUpgradeMember(updateGradeMember);

        // 校验会员选择区域是否已经被占用
        otherCheckStr = this.checkRegionNum(upgradeParam);
        if (null != otherCheckStr) {
            return AjaxResult.error(otherCheckStr);
        }

        // 购物车中获取商品信息
        upgradeParam.setOrderItemsParams(convertShoppingCarToSku(upgradeParam.getPkCreator(), upgradeParam.getShopList()));

        // 确认订单
        String str = iRetailOrderService.confirmUpgOrder(upgradeParam);
        return confirmOrderReturn(str, upgradeParam.getPkCreator(), upgradeParam.getShopList(), upgradeParam.getOrderCode());
    }

    /**
     * 支付升级订单
     *
     * @param payParam 支付订单入参
     * @return
     */
    @RepeatSubmit
    @PostMapping("/pay-upg-order")
    public AjaxResult payUpgradeOrder(@Valid @RequestBody RetailOrderPayParam payParam) {
        // 当前会员ID
        Long pkMember = SecurityUtils.getUserId();

        // 获取缓存参数
        RetailOrderUpgradeParam upgradeParam = redisService.getCacheObject(CacheConstants.RETAIL_TEMP_UPG_PARAM + pkMember + payParam.getOrderCode());
        if (null == upgradeParam) {
            return AjaxResult.error("订单长时间没有支付，已经失效，请重新下单");
        }

        // 升级会员
        CuMember updateGradeMember = iMemberServiceApi.getRetailMember(null, upgradeParam.getUpgradeMemberCode()).getData();
        if (null == updateGradeMember) {
            throw new ServiceException("升级编号不存在，请重试");
        }
        String otherCheckStr = this.otherOrderCheck(updateGradeMember, payParam.getSpecialArea());
        if (null != otherCheckStr) {
            return AjaxResult.error(otherCheckStr);
        }

        // 校验会员选择区域是否已经被占用
        otherCheckStr = this.checkRegionNum(upgradeParam);
        if (null != otherCheckStr) {
            return AjaxResult.error(otherCheckStr);
        }

        // 支付入参
        upgradeParam.setIsPay(EYesNo.YES.getIntValue());

        // 封装订单信息
        SaOrderExt saOrderExt = iRetailOrderService.createSaOrder(upgradeParam, null, updateGradeMember);

        // 校验会员账户状态等
        R<CuMemberAccountExt> accountResult = iRetailOrderService.validMemberAccount(pkMember, payParam.getPayPwd());
        if (!accountResult.isSuccess()) {
            return AjaxResult.error(accountResult.getMsg());
        }
        CuMemberAccountExt memberAccountExt = accountResult.getData();

        // 校验余额是否足够
        iSaOrderService.queryRetailOrderSpendDetails(memberAccountExt, saOrderExt, saOrderExt.getOrderItemsList());
        if (memberAccountExt.getIsPayment()) {
            // 进行支付
            saOrderExt.setSpecialArea(upgradeParam.getSpecialArea());
            saOrderExt.setRegionProvince(upgradeParam.getRegionProvince());
            saOrderExt.setRegionCity(upgradeParam.getRegionCity());
            saOrderExt.setRegionCounty(upgradeParam.getRegionCounty());
            String payStr = iRetailOrderService.payUpgOrder(saOrderExt, updateGradeMember, memberAccountExt);
            if (null != payStr) {
                return AjaxResult.error(payStr);
            }
        } else {
            if (StringUtils.isEmpty(memberAccountExt.getErrorMsg())) {
                return AjaxResult.error("余额不足，请及时充值");
            } else {
                return AjaxResult.error(memberAccountExt.getErrorMsg());
            }
        }

        return AjaxResult.success("支付成功");
    }

    /**
     * 确认订单（注册、升级之外的订单）
     *
     * @param orderParam 订单入参
     * @param source     数据来源
     * @return
     */
    @RepeatSubmit
    @PostMapping("/confirm-other-order")
    public AjaxResult confirmOtherOrder(@Valid @RequestBody RetailOrderOtherParam orderParam,
                                        @RequestHeader("Source") Integer source) {
        // 设置数据来源
        orderParam.setSource(source);
        // 会员ID
        orderParam.setPkCreator(SecurityUtils.getUserId());
        // 系统类型
        orderParam.setSystemType(SecurityUtils.getSystemType());

        // 购买会员
        CuMember buyMember = iMemberServiceApi.getRetailMember(null, orderParam.getBuyMemberCode()).getData();
        String otherCheckStr = this.otherOrderCheck(buyMember, orderParam.getSpecialArea());
        if (null != otherCheckStr) {
            return AjaxResult.error(otherCheckStr);
        }
        orderParam.setBuyMember(buyMember);

        // 购物车中获取商品信息
        orderParam.setOrderItemsParams(convertShoppingCarToSku(orderParam.getPkCreator(), orderParam.getShopList()));

        // 确认订单
        String str = iRetailOrderService.confirmOtherOrder(orderParam);
        return confirmOrderReturn(str, orderParam.getPkCreator(), orderParam.getShopList(), orderParam.getOrderCode());
    }

    /**
     * 支付订单（注册、升级之外的订单）
     *
     * @param payParam 支付订单入参
     * @return
     */
    @RepeatSubmit
    @PostMapping("/pay-other-order")
    public AjaxResult payOtherOrder(@Valid @RequestBody RetailOrderPayParam payParam) {
        // 当前会员ID
        Long pkMember = SecurityUtils.getUserId();

        // 获取缓存参数
        RetailOrderOtherParam otherParam = redisService.getCacheObject(CacheConstants.RETAIL_TEMP_OTHER_PARAM + pkMember + payParam.getOrderCode());
        if (null == otherParam) {
            return AjaxResult.error("订单长时间没有支付，已经失效，请重新下单");
        }

        // 购买会员
        CuMember buyMember = iMemberServiceApi.getRetailMember(null, otherParam.getBuyMemberCode()).getData();
        String otherCheckStr = this.otherOrderCheck(buyMember, payParam.getSpecialArea());
        if (null != otherCheckStr) {
            return AjaxResult.error(otherCheckStr);
        }

        // 封装订单信息
        SaOrderExt saOrderExt = iRetailOrderService.createSaOrder(otherParam, null, buyMember);

        // 校验会员账户状态等
        R<CuMemberAccountExt> accountResult = iRetailOrderService.validMemberAccount(pkMember, payParam.getPayPwd());
        if (!accountResult.isSuccess()) {
            return AjaxResult.error(accountResult.getMsg());
        }
        CuMemberAccountExt memberAccountExt = accountResult.getData();

        // 校验余额是否足够
        iSaOrderService.queryRetailOrderSpendDetails(memberAccountExt, saOrderExt, saOrderExt.getOrderItemsList());
        if (memberAccountExt.getIsPayment()) {
            // 进行支付
            saOrderExt.setSpecialArea(otherParam.getSpecialArea());
            String payStr = iRetailOrderService.payOtherOrder(saOrderExt, buyMember, memberAccountExt);
            if (null != payStr) {
                return AjaxResult.error(payStr);
            }
        } else {
            if (StringUtils.isEmpty(memberAccountExt.getErrorMsg())) {
                return AjaxResult.error("余额不足，请及时充值");
            } else {
                return AjaxResult.error(memberAccountExt.getErrorMsg());
            }
        }

        return AjaxResult.success("支付成功");
    }

    /**
     * 查询订单信息
     *
     * @param queryOrderParam 查询入参
     * @return
     */
    @PostMapping("/query-order")
    public AjaxResult queryOrder(@Valid @RequestBody RetailQueryOrderParam queryOrderParam) {
        // 获取缓存订单
        SaOrderExt saOrderExt = redisService.getCacheObject(CacheConstants.RETAIL_TEMP_ORDER + SecurityUtils.getUserId() + queryOrderParam.getOrderCode());
        if (null == saOrderExt) {
            return AjaxResult.error("订单已超时，请重新下单");
        }
        // 推荐人
        CuMember parentMember = null;
        // 获取等级值
        GradeDTO gradeDTO = null;
        if (ESpecialArea.RETAIL_REGISTER.getValue() == queryOrderParam.getSpecialArea()
                || ESpecialArea.RETAIL_UPGRADE.getValue() == queryOrderParam.getSpecialArea()) {
            parentMember = iMemberServiceApi.getRetailMember(saOrderExt.getPkReference(), null).getData();
            gradeDTO = iGradeServiceApi.getGrade(saOrderExt.getPkGrade()).getData();
        }

        // 省市区地址
        Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(saOrderExt.getPkCountry()).getData();

        return AjaxResult.success(RetailQueryOrderVO.builder()
                // 支付金额 = 订单金额 + 邮费
                .orderAmount(saOrderExt.getOrderAmount().add(saOrderExt.getPostage()))
                // 订单过期时间 30 分钟
                .payTime(CacheConstants.RETAIL_ORDER_EXPIRE_TIME * 60)
                .pkGradeVal(null != gradeDTO ? gradeDTO.getGradeName() : null)
                .memberCode(saOrderExt.getMemberCode())
                .memberName(saOrderExt.getMemberName())
                .phone(saOrderExt.getMemberPhone())
                .parent(null != parentMember ? parentMember.getMemberCode() : null)
                .parentName(null != parentMember ? parentMember.getMemberName() : null)
                .deliveryWay(saOrderExt.getDeliveryWay())
                .transType(saOrderExt.getTranType())
                .recName(saOrderExt.getRecName())
                .recPhone(saOrderExt.getRecPhone())
                .recProvince(areaMap.get(saOrderExt.getRecProvince()))
                .recCity(areaMap.get(saOrderExt.getRecCity()))
                .recCounty(areaMap.get(saOrderExt.getRecCounty()))
                .recAddress(saOrderExt.getRecAddress())
                .build());
    }

    /**
     * 查询订单支付信息
     *
     * @param queryOrderParam 查询入参
     * @return
     */
    @PostMapping("/query-spend-details")
    public AjaxResult querySpendDetails(@Valid @RequestBody RetailQueryOrderParam queryOrderParam) {
        // 缓存中获取订单
        SaOrderExt saOrder = redisService.getCacheObject(CacheConstants.RETAIL_TEMP_ORDER + SecurityUtils.getUserId() + queryOrderParam.getOrderCode());
        if (null == saOrder) {
            return AjaxResult.error("订单长时间没有支付，已经失效，请重新下单");
        }

        CuMemberAccountExt cuMemberAccountExt = iRetailOrderService.getMemberAccount(SecurityUtils.getUserId());
        if (null == cuMemberAccountExt) {
            return AjaxResult.error("会员账户异常，请联系客服处理");
        }
        // 验证会员账户余额是否足够支付
        iSaOrderService.queryRetailOrderSpendDetails(cuMemberAccountExt, saOrder, saOrder.getOrderItemsList());
        CuMemberAccountParam cuMemberAccountParam = BeanUtil.copyProperties(cuMemberAccountExt, CuMemberAccountParam.class);
        return AjaxResult.success(cuMemberAccountParam);
    }

    /**
     * 根据购物车ID获取商品信息
     *
     * @param pkCreator 下单人
     * @param shopList  购物车列表
     */
    private List<OrderItemsParam> convertShoppingCarToSku(Long pkCreator, List<ShoppingCartRedis> shopList) {
        List<ShoppingCartRedis> shoppingCartRedisList = shoppingCartService.queryShopping(pkCreator, ShoppingCartVO.builder()
                .deleteList(shopList)
                .build());
        // 订单商品明细
        List<OrderItemsParam> orderItemsParamList = new ArrayList<>();
        shoppingCartRedisList.forEach(shoppingCartRedis -> {
            OrderItemsParam orderItemsParam = OrderItemsParam.builder()
                    .pkId(shoppingCartRedis.getPkId())
                    .channel(shoppingCartRedis.getSource())
                    .waresCode(shoppingCartRedis.getWaresCode())
                    .quantity(shoppingCartRedis.getNumber())
                    .pkMakerSpace(shoppingCartRedis.getPkMakerSpace())
                    .build();
            List<WaresItemsParam> waresItemsParamList = new ArrayList<>(shoppingCartRedis.getProductGroup().size());
            for (ProductGroup productGroup : shoppingCartRedis.getProductGroup()) {
                WaresItemsParam waresItemsParam = WaresItemsParam.builder()
                        .pkProduct(productGroup.getPkProduct())
                        .pkWaresSpecsSku(productGroup.getPkSkuId())
                        .quantity(productGroup.getQuantity())
                        .build();
                waresItemsParamList.add(waresItemsParam);
            }
            orderItemsParam.setWaresItemsParamList(waresItemsParamList);
            orderItemsParamList.add(orderItemsParam);
        });
        if (CollectionUtil.isEmpty(orderItemsParamList)) {
            throw new ServiceException("购物车中商品信息已不存在，请重新选择商品");
        }
        return orderItemsParamList;
    }

    /**
     * 校验推荐人是否在会员伞下
     *
     * @param parentCode 推荐编号
     * @param pkMember   会员ID
     * @return
     */
    private R<CuMember> checkParent(String parentCode, Long pkMember) {
        // 查询推荐人
        CuMember parentMember = iMemberServiceApi.getRetailMember(null, parentCode).getData();
        if (null == parentMember) {
            return R.fail("会员编号不存在");
        }
        if (!parentMember.getPkCreator().equals(parentMember.getPkId())) {
            CuMember topMember = iMemberServiceApi.getRetailTopMember(parentMember.getPkId(), null, pkMember, null).getData();
            if (null == topMember) {
                return R.fail("会员编号不在当前会员推荐伞下，请重新输入");
            }
        }
        return R.ok(parentMember);
    }

    /**
     * 校验注册权限
     *
     * @param orderParam 订单入参
     * @param gradeList  等级列表
     * @return
     */
    private String checkRegistrationPermission(RetailOrderRegisterParam orderParam, List<BdGrade> gradeList) {
        if (CollectionUtil.isEmpty(gradeList)) {
            gradeList = iGradeServiceApi.getRetailGradeList().getData();
        }

        // 校验会员等级是否大于V0，不然不能进行注册会员
        CuMember creatorMember = iMemberServiceApi.getRetailMember(orderParam.getPkCreator(), null).getData();
        if (null == creatorMember) {
            return "当前会员不存在";
        }
        // 校验推荐人等级是否为V0，如果是V0不能进行注册
        BdGrade memberGrade = gradeList.stream().filter(tmpGrade -> tmpGrade.getPkId().equals(creatorMember.getPkSettleGrade())).findFirst().get();
        if (EGrade.START_UP.getValue() == memberGrade.getGradeValue()) {
            return "当前会员不能注册新会员";
        }
        orderParam.setCreatorMember(creatorMember);
        orderParam.setPkParent(orderParam.getPkCreator());

        if (!creatorMember.getMemberCode().equals(orderParam.getParentCode())) {

            CuMember parentMember = iMemberServiceApi.getRetailMember(null, orderParam.getParentCode()).getData();
            if (null == parentMember) {
                return "推荐编号不存在";
            }
//            // 校验推荐人是否大于V0，不然不能当推荐人
//            BdGrade parentGrade = gradeList.stream().filter(tmpGrade -> tmpGrade.getPkId().equals(parentMember.getPkSettleGrade())).findFirst().get();
//            if (EGrade.START_UP.getValue() == parentGrade.getGradeValue()) {
//                return orderParam.getParentCode() + " 不能做为推荐人";
//            }

            // 校验推荐人是否在当前会员伞下
            CuMember topMember = iMemberServiceApi.getRetailTopMember(parentMember.getPkId(), null, orderParam.getPkCreator(), null).getData();
            if (null == topMember) {
                return "推荐人不在会员推荐伞下，请重新输入";
            }
            orderParam.setPkParent(parentMember.getPkId());
        }

        return null;
    }

    /**
     * 确认订单返回
     *
     * @param str       提示信息（null 为成功）
     * @param pkCreator 订单创建人
     * @param shopList  购物车ID
     * @param orderCode 订单编号
     * @return
     */
    private AjaxResult confirmOrderReturn(String str, Long pkCreator, List<ShoppingCartRedis> shopList, String orderCode) {
        if (null == str) {
            // 删除购物车商品数据
            if (CollectionUtil.isNotEmpty(shopList)) {
                shoppingCartService.batchDelShopping(pkCreator, ShoppingCartVO.builder()
                        .deleteList(shopList)
                        .build());
            }
            return AjaxResult.success(RetailOrderVO.builder()
                    .orderCode(orderCode)
                    .build());
        }
        return AjaxResult.error(str);
    }

    /**
     * 其它订单下单校验
     *
     * @param buyMember   购买会员
     * @param specialArea 所属专区
     * @return
     */
    private String otherOrderCheck(CuMember buyMember, Integer specialArea) {
        if (null == buyMember) {
            return "购买会员编号不存在，请重试";
        }
        if (ESpecialArea.RETAIL_UPGRADE.getValue() != specialArea
                && ESpecialArea.RETAIL_REPURCHASE.getValue() != specialArea) {
            // 判断购买会员是否是V0，V0不允许下升级、复购以外订单
            GradeDTO gradeDTO = iGradeServiceApi.getGrade(buyMember.getPkSettleGrade()).getData();
            if (gradeDTO.getGradeValue() == EGrade.START_UP.getValue()) {
                return "当前购买会员编号不允许下单";
            }
        }
        return null;
    }

    /**
     * 校验会员选择区域是否已经被占用
     *
     * @param orderParam
     * @return
     */
    private String checkRegionNum(RetailOrderParam orderParam) {
        if (null != orderParam.getRegionProvince()
                && null != orderParam.getRegionCity()) {
            // 区域省、市不为空，则进行判断
            CuMemberRetailRegionExt cuMemberRetailRegion = iSaOrderService.getRegionBindNum(orderParam.getRegionProvince(), orderParam.getRegionCity(), orderParam.getRegionCounty());
            if (null != cuMemberRetailRegion) {
                if (cuMemberRetailRegion.getRegionNum() >= cuMemberRetailRegion.getBindNum()) {
                    return "当前区域已经达到绑定上限，请重新选择";
                }
            }
        }
        return null;
    }

}
