package com.hzs.sale.order.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.HttpStatus;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
import com.hzs.common.core.constant.msg.SaOrderMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.reflect.ReflectUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.account.CuMemberAccount;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.ext.CuMemberAccountExt;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.sale.order.param.OrderItemsParam;
import com.hzs.sale.order.param.OrderParam;
import com.hzs.sale.order.param.OrderReturn;
import com.hzs.sale.order.param.WaresItemsParam;
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.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
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.RequestBody;

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

@Slf4j
public abstract class ParentOrderController extends BaseController {

    @DubboReference
    IAreaServiceApi iAreaServiceApi;
    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;
    @DubboReference
    IMemberServiceApi iMemberServiceApi;

    @Autowired
    protected IShoppingCartService iShoppingCartService;
    @Autowired
    protected RedisService redisService;

    private ISaOrderService iSaOrderService;
    @Autowired
    public void setOrderService(ISaOrderService orderService) {
        this.iSaOrderService = orderService;
    }

    public ISaOrderService getOrderService() {
        return iSaOrderService;
    }


    /**
     * 根据code、编码获取值
     *
     * @param code 查询的code
     */
    protected CuMember getCuMemberByCode(String code) {
        return iSaOrderService.getCuMemberByCode(code);
    }

    /**
     * 验证字段是否必输
     *
     * @param fieldList 需要验证的字段
     */
    protected boolean validateFieldNotNull(OrderParam orderParam, List<String> fieldList) {
        return fieldList.stream().anyMatch(field -> {
            Object obj = ReflectUtils.invokeGetter(orderParam, field);
            return obj == null || "".equals(obj);
        });
    }

    /**
     * 验证手机号+姓名
     *
     * @param orderParam 手机号、姓名、安置人必输
     */
    protected AjaxResult validatePhone(OrderParam orderParam) {
        if (StringUtils.isEmpty(orderParam.getPhone()) || StringUtils.isEmpty(orderParam.getMemberName())) {
            return AjaxResult.error(MemberMsgConstants.REQUIRED_NOT_EMPTY);
        }

        // 手机号
        String phone = orderParam.getPhone();
        // 会员姓名
        String memberName = orderParam.getMemberName();
        // 验证手机号注册次数
        List<CuMemberExt> cuMemberExtList = iSaOrderService.queryMemberExtByCondition(CuMember.builder().phone(phone).payStatus(EPayStatus.PAID.getValue()).pkSettleGrade(EGrade.VIP.getValue()).pkSettleCountry(orderParam.getPkSettleCountry()).build());
        // 系统中存在该手机号走的验证
        if (CollectionUtil.isNotEmpty(cuMemberExtList)) {
            // 手机号注册次数
            if (!validatePhoneCount(cuMemberExtList)) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.SYSTEM_REGISTER_COUNT));
            }
            // 一个手机号只能有一个姓名
            boolean flag = cuMemberExtList.stream().allMatch(cuMemberExt -> memberName.equals(cuMemberExt.getMemberName()));
            if (!flag) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PHONE_ALREADY_REGISTER));
            }
        }
        if (!orderParam.getIsHaiFun()) {
            if (StringUtils.isEmpty(orderParam.getPlaceParent())) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PLACE_PARENT_NOT_EMPTY));
            }
            // 安置人
            // 1.只能在同一个团队内 验证安置人及安置人伞上是否存在该手机号+姓名
            // 很多情况安置人跟伞下是一样的，从redis获取安置人，验证安置人手机号跟姓名是否一致
            CuMember placeParentCuMember = getCuMemberByCode(orderParam.getPlaceParent());
            if (!placeParentCuMember.getMemberName().equals(memberName) ||
                    !placeParentCuMember.getPhone().equals(phone)) {
                // 寻找安置人伞上,验证安置伞上是否存在该手机姓名,如果伞上没有找到手机号，其他地方找到了，说明不在一个团队
                List<CuMemberExt> sponsorOnUmbrella = iSaOrderService.querySponsorOnUmbrella(placeParentCuMember.getPkId(), phone);
                CuMemberExt searchCuMember = null;
                for (CuMemberExt sponsor : sponsorOnUmbrella) {
                    if (sponsor.getPhone().equals(phone) && sponsor.getMemberName().equals(memberName)) {
                        searchCuMember = sponsor;
                        break;
                    }
                }
                if (CollectionUtil.isNotEmpty(cuMemberExtList)) {
                    if (searchCuMember == null) {
                        return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REGISTER_EXIST_OTHER_TEAM));
                    } else {
                        // 验证cuMemberExtList是否在searchCuMember的伞下，不在伞下说明游离了
                        List<CuMemberExt> validateSponsorOnUmbrella = iSaOrderService.selectPlaceSponsorUnderUmbrellaByCondition(searchCuMember.getPkId(), cuMemberExtList);
                        if (CollectionUtil.isEmpty(validateSponsorOnUmbrella) || validateSponsorOnUmbrella.size() != cuMemberExtList.size()) {
                            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REGISTER_EXIST_OTHER_TEAM));
                        }
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 验证推荐编号，成功后返回姓名，如果首单返回安置人、安置部门
     *
     * @param orderParam 必须推荐人
     */
    protected AjaxResult validateReferenceRelation(OrderParam orderParam) {
        if (StringUtils.isEmpty(orderParam.getParent())) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PARENT_NOT_EMPTY));
        }
        CuMember cuMember = getCuMemberByCode(orderParam.getParent());
        if (cuMember == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PARENT_NOT_EXISTS));
        }
        // 验证会员支付状态，只有支付状态才能进行推荐人
        if (cuMember.getPayStatus() != EPayStatus.PAID.getValue()) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PARENT_NOT_PAY));
        }
//        // 验证推荐等级，判断什么级别可以推荐什么级别
//        GradeDTO gradeDTO = getOrderService().queryGradeConfigByCondition(orderParam.getPkSettleCountry(), cuMember.getPkSettleGrade());
//        // 获取推荐人可以推荐的等级
//        if (gradeDTO.getBdGradeScopeExtList().stream().noneMatch(bdGradeScope -> cuMember.getPkSettleGrade().equals(bdGradeScope.getPkScope()))) {
//            return AjaxResult.error(MemberMsgConstants.PARENT_REFERENCE_NOT_AUTHORITY);
//        }
        // 验证推荐人跟报单人关系， 报单人一定在最上，然后是推荐人
        // 推荐人=报单人，不用在验证报单人在推荐人上面
        if (!cuMember.getPkId().equals(orderParam.getCenterCodeId())) {
            // 查找报单人安置伞下是否存在推荐人
            List<CuMemberExt> cuMemberExtList = iSaOrderService.queryPlaceSponsorUnderUmbrella(orderParam.getCenterCodeId(), cuMember.getMemberCode());
            if (CollectionUtil.isEmpty(cuMemberExtList)) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PARENT_NOT_TEAM));
            }
//            List<CuMemberExt> cuMemberExtList = iSaOrderService.queryBloodKinshipOnUmbrella(cuMember.getPkId());
//            boolean flag = cuMemberExtList.stream().noneMatch(bloodKinship ->
//                    bloodKinship.getPkId().equals(orderParam.getCenterCodeId()));
//            if (flag) {
//                return AjaxResult.error(MemberMsgConstants.PARENT_NOT_TEAM);
//            }
        }
        // 存在首单，只返回推荐人姓名
        orderParam.setParentId(cuMember.getPkId());
        if (SecurityUtils.getUserId().equals(cuMember.getPkId())) {
            orderParam.setParentName(cuMember.getMemberName());
        } else {
            orderParam.setParentName(CommonUtil.getMemberName(cuMember.getPkVertex(), cuMember.getMemberName(), cuMember.getNickName()));
        }

        String firstOrder = iSaOrderService.querySystemConfigByKey(orderParam.getPkSettleCountry(), ESystemConfig.FIRST_ORDER.getKey());
        if (EYesNo.YES.getIntValue() == Integer.parseInt(firstOrder)) {
            // 判断是否为首单,根据订单关系，按照订单关系，是首单的话，直接带出极左极下，放在第一部门，不能修改
//            Integer count = iSaOrderService.querySaleOrderByPkMember(cuMember.getPkSettleCountry(), null, cuMember.getPkId());
            Integer count = iSaOrderService.queryCuMemberByPkMember(cuMember.getPkId());
            if (count == 0) {
                // 验证网体
                orderParam.setIsFirst(true);
                // 不存在首单，返回推荐人姓名、安置人编号、安置人姓名、安置人部门
                // 查找推荐人极左极下
                CuMemberExt cuMemberExt = iSaOrderService.queryPlaceSponsorLastLeft(cuMember.getPkId(), EPlaceDept.LEFT_DEPT.getValue());
                if (cuMemberExt == null) {
                    orderParam.setPlaceParentId(cuMember.getPkId());
                    orderParam.setPlaceParent(CommonUtil.getMemberCode(cuMember.getMemberCode(), cuMember.getServiceCode()));
                    if (SecurityUtils.getUserId().equals(cuMember.getPkId())) {
                        orderParam.setPlaceParentName(cuMember.getMemberName());
                    } else {
                        orderParam.setPlaceParentName(CommonUtil.getMemberName(cuMember.getPkVertex(), cuMember.getMemberName(), cuMember.getNickName()));
                    }
                } else {
                    orderParam.setPlaceParentId(cuMemberExt.getPkId());
                    orderParam.setPlaceParent(CommonUtil.getMemberCode(cuMemberExt.getMemberCode(), cuMemberExt.getServiceCode()));
                    if (SecurityUtils.getUserId().equals(cuMember.getPkId())) {
                        orderParam.setPlaceParentName(cuMemberExt.getMemberName());
                    } else {
                        orderParam.setPlaceParentName(CommonUtil.getMemberName(cuMemberExt.getPkVertex(), cuMemberExt.getMemberName(), cuMemberExt.getNickName()));
                    }
                }
                String placePosition = iSaOrderService.querySystemConfigByKey(orderParam.getPkSettleCountry(), ESystemConfig.PLACE_POSITION.getKey());
                if (Objects.equals("3", placePosition)) {
                    orderParam.setPlaceDept(EPlaceDept.RIGHT_DEPT.getValue());
                } else {
                    orderParam.setPlaceDept(EPlaceDept.LEFT_DEPT.getValue());
                }
            }
        }
        return AjaxResult.success(orderParam);
    }

    /**
     * 验证安置编号、安置部门，成功后返回姓名
     *
     * @param orderParam 必须安置人
     */
    protected AjaxResult validatePlaceParentMemberCode(OrderParam orderParam) {
        if (StringUtils.isEmpty(orderParam.getParent())) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PARENT_NOT_EMPTY));
        }
        if (StringUtils.isEmpty(orderParam.getPlaceParent())) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PLACE_PARENT_NOT_EMPTY));
        }

        // 验证推荐编号、安置编号是否存在,不验证大小写，去空格。
        CuMember parentMember = getCuMemberByCode(orderParam.getParent());
        if (parentMember == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PARENT_NOT_EXISTS));
        }
        orderParam.setParent(CommonUtil.getMemberCode(parentMember.getMemberCode(), parentMember.getServiceCode()));
        if (SecurityUtils.getUserId().equals(parentMember.getPkId())) {
            orderParam.setParentName(parentMember.getMemberName());
        } else {
            orderParam.setParentName(CommonUtil.getMemberName(parentMember.getPkVertex(), parentMember.getMemberName(), parentMember.getNickName()));
        }

        CuMember placeMember = getCuMemberByCode(orderParam.getPlaceParent());
        if (placeMember == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PLACE_PARENT_NOT_EXISTS));
        }
        orderParam.setPlaceParentId(placeMember.getPkId());
        orderParam.setPlaceParent(CommonUtil.getMemberCode(placeMember.getMemberCode(), placeMember.getServiceCode()));

        if (SecurityUtils.getUserId().equals(placeMember.getPkId())) {
            orderParam.setPlaceParentName(placeMember.getMemberName());
        } else {
            orderParam.setPlaceParentName(CommonUtil.getMemberName(placeMember.getPkVertex(), placeMember.getMemberName(), placeMember.getNickName()));
        }
        // 当安置人跟安置位置都有值是需要验证 需要验证安置位置
        if (orderParam.getPlaceDept() != null && orderParam.getPlaceDept() > 0) {
            // 安置人在推荐人伞下，含自己。 推荐人在报单中心伞下，含自己，在推荐那边验证
            if (!orderParam.getPlaceParent().equals(orderParam.getParent())) {
                // 查找推荐人安置伞下
                List<CuMemberExt> cuMemberExtList = iSaOrderService.queryPlaceSponsorUnderUmbrella(parentMember.getPkId(), orderParam.getPlaceParent());
                // 查找是否在伞下
                boolean flag = cuMemberExtList.stream().noneMatch(placeSponsor ->
                        orderParam.getPlaceParent().equals(placeSponsor.getMemberCode()) || orderParam.getPlaceParent().equals(placeSponsor.getServiceCode())
                );
                if (flag) {
                    return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PLACE_NOT_TEAM));
                }
            }
            // 推荐人安置人左区或者右区只能有1个，验证安置人是否已经有点位
            List<CuMemberExt> cuMemberExtList = iSaOrderService.queryMemberExtByCondition(CuMember.builder().pkPlaceParent(placeMember.getPkId()).category(10).placeDept(orderParam.getPlaceDept()).build());
            if (CollectionUtil.isNotEmpty(cuMemberExtList)) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PLACE_PARENT_DEPT_EXIST));
            }
            // 安置部门为第二部门时，需要判断推荐人是否推荐过首单，可以安置在第二部门，否则只能在第一部门；
            // 推荐过左区可以放右区，需要验证安置人是否有有单
            // 西非不验证安置部门是否推荐过首单，只需要验证安置左区必须有人
            if (orderParam.getPlaceDept() == EPlaceDept.RIGHT_DEPT.getValue()) {
                // 推荐人是否有首单
                // 从参数中获取是否需要验证安置人有首单
                Integer pkCountry = orderParam.getPkSettleCountry();
                if (!placeMember.getPkId().equals(parentMember.getPkId()) && iSaOrderService.validateFirstOrder(placeMember.getPkId(), pkCountry)) {
                    return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PLACE_PARENT_NOT_REFERENCE));
                }
                // 安置人左区是否有人
                if (iSaOrderService.validateLeftExistMember(placeMember.getPkId(), pkCountry)) {
                    return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PLACE_PARENT_NOT_EXIST));
                }
            }
        }
        return AjaxResult.success(orderParam);
    }

    /**
     * 验证需要注册的信息, 订单保存时需要调用的验证
     *
     * @param orderParam 所有信息
     */
    protected AjaxResult validateSaveMember(OrderParam orderParam) {
        // 安置编号
        String placeParent = orderParam.getPlaceParent();
        // 安置部门
        Integer placeDept = orderParam.getPlaceDept();
        AjaxResult result = validateFun(orderParam);
        if (result != null) {
            return result;
        }
        // 验证是否首单，首单安置人安置部门不能变动
        if (orderParam.getIsFirst()) {
            // 判断安置人跟安置部门是否一致
            if (!(placeParent.equals(orderParam.getPlaceParent()) && placeDept.equals(orderParam.getPlaceDept()))) {
                return AjaxResult.error(MemberMsgConstants.PLACE_IS_LAST_LEFT);
            }
        } else {
            // 验证过首单后可以不用在验证安置人，不是首单的情况直接验证安置人
            // 验证安置人
            result = validatePlaceParentMemberCode(orderParam);
            if ((Integer) result.get(AjaxResult.CODE_TAG) == HttpStatus.ERROR) {
                return result;
            }
        }
        return AjaxResult.success(orderParam);
    }

    protected AjaxResult validateFun(OrderParam orderParam) {
        // 报单中心
        Long centerCodeId = orderParam.getCenterCodeId();
        // 验证权限
        AjaxResult result = validateRegisterAuthority(centerCodeId, orderParam.getSpecialArea());
        if ((Integer) result.get(AjaxResult.CODE_TAG) == HttpStatus.ERROR) {
            return result;
        }
        // 验证手机号
        result = validatePhone(orderParam);
        if ((Integer) result.get(AjaxResult.CODE_TAG) == HttpStatus.ERROR) {
            return result;
        }
        // 验证推荐人
        result = validateReferenceRelation(orderParam);
        if ((Integer) result.get(AjaxResult.CODE_TAG) == HttpStatus.ERROR) {
            return result;
        }
        return null;
    }

    /**
     * 对安置位置进行加锁预防位置重复
     *
     * @param placeParentId 安置人
     * @param placeDept     安置位置
     */
    protected boolean validatePlacePosition(Long placeParentId, Integer placeDept) {
        // 验证通过对安置人，安置部门加锁，防止同时安置引起错误，最后解锁
        return iSaOrderService.lockKey(getLockKey(placeParentId, placeDept));
    }

    /**
     * @param placeParentId 安置位置
     * @param placeDept     安置部门
     */
    private String getLockKey(Long placeParentId, Integer placeDept) {
        return CacheConstants.POSITION +
                placeParentId +
                placeDept;
    }

    /**
     * 空单注册 验证权限，验证编号是否有报单权限
     *
     * @param centerCodeId 验证的权限
     */
    protected AjaxResult validateRegisterAuthority(Long centerCodeId, Integer specialArea) {
        // 前台登录验证登录会员，后台空点验证输入的报单人
        CuMember cuMember = iSaOrderService.getCuMemberByKey(centerCodeId);
        if (cuMember == null || cuMember.getRegisterAuthority() == ERegistrationAuthority.ORDINARY.getValue()) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REGISTER_AUTHORITY));
        }
        return AjaxResult.success();
    }

    /**
     * 检查输入的条件
     *
     * @param orderParam 条件
     * @return boolean
     */
    protected Boolean checkRecMsgBoolean(OrderParam orderParam) {
        if (orderParam.getDeliveryWay() != null && (EDelivery.COMPANY_PICKED_UP.getValue() == orderParam.getDeliveryWay() ||
                EDelivery.SHOP_PICKED_UP.getValue() == orderParam.getDeliveryWay())) {
            orderParam.setTransType(null);
            return orderParam.getSpecialArea() != null
                    && orderParam.getOrderItemsParams() != null
                    && orderParam.getOrderItemsParams().size() > 0;
        } else {
            return orderParam.getSpecialArea() != null
                    && orderParam.getDeliveryWay() != null && orderParam.getTransType() != null
                    && orderParam.getRecName() != null && orderParam.getRecPhone() != null
                    && orderParam.getRecProvince() != null && orderParam.getRecCity() != null
                    && orderParam.getOrderItemsParams() != null && orderParam.getRecAddress() != null
                    && orderParam.getOrderItemsParams().size() > 0;
        }
    }

    /**
     * 检查输入的条件
     *
     * @param orderParam 条件
     * @return boolean
     */
    protected Boolean checkRecPostageMsgBoolean(@RequestBody OrderParam orderParam) {
        return orderParam.getSpecialArea() != null
                && orderParam.getDeliveryWay() != null && orderParam.getTransType() != null
                && orderParam.getRecProvince() != null && orderParam.getRecCity() != null
                && orderParam.getOrderItemsParams() != null
                && orderParam.getOrderItemsParams().size() > 0;
    }

    /**
     * 初始化参数
     *
     * @param orderParam 参数
     */
    protected void initSecurityOrderParam(OrderParam orderParam) {
        orderParam.setCenterCodeId(SecurityUtils.getUserId());
        initPkCountry(orderParam);
        if (orderParam.getPostage() == null) {
            orderParam.setPostage(BigDecimal.ZERO);
        }
        if (orderParam.getTransType() == null) {
            // 国内默认陆运 海外默认海运
            if (orderParam.getPkSettleCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                orderParam.setTransType(ETransportType.LAND.getValue());
            } else {
                orderParam.setTransType(ETransportType.LAND.getValue());
            }
        }
    }

    protected void initPkCountry(OrderParam orderParam) {
        if (orderParam.getPkSettleCountry() == null) {
            orderParam.setPkSettleCountry(SecurityUtils.getPkCountry());
        }
        orderParam.setPkLoginSettleCountry(SecurityUtils.getPkCountry());
    }

    /**
     * 验证手机号注册次数
     *
     * @param cuMemberExtList 会员数量
     */
    private Boolean validatePhoneCount(List<CuMemberExt> cuMemberExtList) {
        // 判断次数，获取系统参数，从redis中获取系统参数
        String value = iSaOrderService.querySystemConfigByKey(cuMemberExtList.get(0).getPkSettleCountry(), ESystemConfig.REGISTER_NUMBER.getKey());
        return cuMemberExtList.size() < Integer.parseInt(value);
    }

    protected CuMemberAccount getCuMemberAccount(OrderParam orderParam) {
        CuMemberAccount cuMemberAccount = CuMemberAccount.builder().pkMember(orderParam.getCenterCodeId()).build();
        cuMemberAccount.setPkCountry(orderParam.getPkLoginSettleCountry());
        return cuMemberAccount;
    }

    /**
     * 验证会员账户、会员状态
     *
     * @param orderParam 参数
     * @return AjaxResult
     */
    protected AjaxResult validateMemberAccount(OrderParam orderParam) {
        List<CuMemberAccountExt> cuMemberAccountExtList = iSaOrderService.queryMemberAccountByCondition(getCuMemberAccount(orderParam));
        if (cuMemberAccountExtList == null || cuMemberAccountExtList.size() <= 0) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.CENTER_NOT_EXISTS));
        }
        CuMemberAccountExt cuMemberAccountExt = cuMemberAccountExtList.get(0);
        // 验证密码
        if (!SecurityUtils.matchesPassword(orderParam.getPayPwd(), cuMemberAccountExt.getPayPwd())) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_PASSWORD_NOT_MATCH));
        }
        // 验证账户状态、钱包状态
        if (cuMemberAccountExt.getAccountStatus() != EAccountStatus.NORMAL.getValue()) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_ACCOUNT_STATUS_LOCK));
        }
        return AjaxResult.success(cuMemberAccountExt);
    }

    /**
     * 验证升级关系，只能给自己或者自己安置伞下升级
     *
     * @param orderParam 前台传递的参数
     */
    protected AjaxResult validateUpgradeRelation(OrderParam orderParam) {
        CuMember upgradeMember = iSaOrderService.getCuMemberByCode(orderParam.getUpgradeMemberCode());
        if (upgradeMember == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_DOES_NOT_EXITS));
        }
        if (null != orderParam.getCenterCodeId() && orderParam.getCenterCodeId().equals(upgradeMember.getPkId())) {
            orderParam.setUpgradeMemberName(upgradeMember.getMemberName());
        } else {
            orderParam.setUpgradeMemberName(CommonUtil.getMemberName(upgradeMember.getPkVertex(), upgradeMember.getMemberName(), upgradeMember.getNickName()));
        }

        if (!orderParam.getCenterCodeId().equals(upgradeMember.getPkId())) {
            // 可以给别人升级，只能是自己的安置伞下
            List<CuMemberExt> cuMemberExtList = iSaOrderService.queryPlaceSponsorUnderUmbrella(orderParam.getCenterCodeId(), upgradeMember.getMemberCode());
            boolean flag = cuMemberExtList.stream().noneMatch(cuMemberExt -> cuMemberExt.getPkId().equals(upgradeMember.getPkId()));
            if (flag) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PLACE_NOT_TEAM));
            }
        }
        return AjaxResult.success(orderParam);
    }

    protected SaOrder getSaOrderQueryParam(OrderParam orderParam) {
        SaOrder saOrder = SaOrder.builder()
                .orderCode(orderParam.getOrderCode())
                .orderStatus(EOrderStatus.WAIT_PAY.getValue())
                .orderType(orderParam.getSpecialArea()).build();
        saOrder.setPkCountry(orderParam.getPkSettleCountry());
        return saOrder;
    }

    /**
     * 查询订单返回值，用于支付
     *
     * @param saOrder    订单
     * @param orderParam 参数
     */
    protected OrderReturn getOrderReturn(SaOrder saOrder, OrderParam orderParam) {
        // 封装订单信息
        long maxPayTime = iSaOrderService.getIsToBePayTime(orderParam.getPkSettleCountry(), saOrder.getOrderType());
        // 剩余支付秒数
        //查询带关闭参数
        // 获取行政区划map
        Integer pkLoginCountry = orderParam.getPkLoginSettleCountry();
        BigDecimal orderAmount = saOrder.getOrderAmount();
        if (!Objects.equals(pkLoginCountry, saOrder.getPkCountry())) {
            // 结算国当地币 转美金  美金登录当地币
            CurrencyDTO loginCountryCurrency = iCurrencyServiceApi.getCurrency(pkLoginCountry).getData();
            CurrencyDTO settleCountryCurrency = iCurrencyServiceApi.getCurrency(saOrder.getPkCountry()).getData();
            orderAmount = ComputeUtil.computeMultiply(ComputeUtil.computeDivide(orderAmount, settleCountryCurrency.getInExchangeRate()), loginCountryCurrency.getInExchangeRate());
        }
        Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(orderParam.getPkSettleCountry()).getData();
        OrderReturn orderReturn = OrderReturn.builder()
                .orderCode(saOrder.getOrderCode())
                .orderAmount(ComputeUtil.computeAdd(orderAmount, saOrder.getPostage()))
                .specialArea(saOrder.getOrderType())
                .isToBePay(EYesNo.NO.getIntValue())
                .pkCountry(saOrder.getPkCountry())
                .postage(saOrder.getPostage())
                .deliveryWay(saOrder.getDeliveryWay())
                .transType(saOrder.getTranType())
                .recName(saOrder.getRecName())
                .recPhone(saOrder.getRecPhone())
                .recProvince(areaMap.get(saOrder.getRecProvince()))
                .recCity(areaMap.get(saOrder.getRecCity()))
                .recCounty(areaMap.get(saOrder.getRecCounty()))
                .recAddress(saOrder.getRecAddress())
                .build();
        if (maxPayTime > 0) {
            orderReturn.setIsToBePay(EYesNo.YES.getIntValue());
            // 计算订单目前秒数
            long currentTime = DateUtils.parseDateToSecond() - DateUtils.parseDateToSecond(saOrder.getCreationTime());
            long payTime = maxPayTime - currentTime;
            if (payTime < 0) {
                payTime = 0;
            }
            orderReturn.setPayTime(payTime);
        }
        return orderReturn;
    }

    /**
     * 将购物车的数量转换到sku种
     */
    protected void convertShoppingCarToSku(OrderParam orderParam) {
        ShoppingCartVO shoppingCartVO = new ShoppingCartVO();
        shoppingCartVO.setDeleteList(orderParam.getDeleteList());
        List<ShoppingCartRedis> shoppingCartRedisList = iShoppingCartService.queryShopping(orderParam.getCenterCodeId(), shoppingCartVO);
        List<OrderItemsParam> orderItemsParamList = new ArrayList<>(shoppingCartRedisList.size());
        shoppingCartRedisList.forEach(shoppingCartRedis -> {
            OrderItemsParam orderItemsParam = OrderItemsParam.builder()
                    .pkId(shoppingCartRedis.getPkId())
                    .channel(shoppingCartRedis.getSource())
                    .waresCode(shoppingCartRedis.getWaresCode())
                    .quantity(shoppingCartRedis.getNumber())
                    .build();
            List<WaresItemsParam> waresItemsParamList = new ArrayList<>(shoppingCartRedis.getProductGroup().size());
            for (ProductGroup productGroup : shoppingCartRedis.getProductGroup()) {
                WaresItemsParam waresItemsParam = WaresItemsParam.builder()
                        .pkWaresSpecsSku(productGroup.getPkSkuId())
                        .quantity(productGroup.getQuantity())
                        .build();
                waresItemsParamList.add(waresItemsParam);
            }
            orderItemsParam.setWaresItemsParamList(waresItemsParamList);
            orderItemsParamList.add(orderItemsParam);
        });
        orderParam.setOrderItemsParams(orderItemsParamList);
    }

    /**
     * 校验休止期、已终止的会员不允许报单
     *
     * @param pkMember 会员ID
     * @return AjaxResult
     */
    protected AjaxResult validateMemberDeclaration(Long pkMember) {
        CuMemberExt cuMember = iMemberServiceApi.getMemberById(pkMember).getData();
        Integer expireStatus = cuMember.getExpireStatus();

        if (expireStatus.equals(EExpireStatus.TERMINATED.getValue())) {
            return AjaxResult.error(SaOrderMsgConstants.TERMINATED_NOT_DECLARATION);
        }

        return AjaxResult.success();
    }


}
