package com.hzs.sale.order.controller.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
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.utils.ComputeUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.ext.SaOrderItemsExt;
import com.hzs.common.domain.sale.ext.SaOrderSelfLogExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.domain.sale.order.SaOrderSelfLog;
import com.hzs.common.domain.scm.ic.ext.IcAvailableNumExt;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.account.IBusinessCommission;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.account.dto.MemberAmountDTO;
import com.hzs.member.account.dto.MemberBalanceDTO;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.sale.deliver.service.ISaDeliverItemsService;
import com.hzs.sale.deliver.vo.SelfDataBarCodeVO;
import com.hzs.sale.deliver.vo.SelfDataProductVO;
import com.hzs.sale.deliver.vo.SelfDataVO;
import com.hzs.sale.order.controller.vo.OrderItemVO;
import com.hzs.sale.order.controller.vo.OrderVo;
import com.hzs.sale.order.controller.vo.StoreOrderVo;
import com.hzs.sale.order.dto.OrderBusinessTemplate;
import com.hzs.sale.order.dto.OrderQueryChargeDTO;
import com.hzs.sale.order.param.*;
import com.hzs.sale.order.service.IOrderBusinessService;
import com.hzs.sale.order.service.ISaOrderSelfLogService;
import com.hzs.sale.order.service.ISaOrderService;
import com.hzs.sale.order.vo.*;
import com.hzs.sale.product.IProductServiceApi;
import com.hzs.sale.util.OrderUtil;
import com.hzs.system.base.IAreaServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.ISystemConfigServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IServiceChargeServiceApi;
import com.hzs.system.config.dto.ServiceChargeDTO;
import com.hzs.system.sys.IUserServiceApi;
import com.hzs.system.sys.dto.UserAuthorityDTO;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 订单业务办理
 * @Author: jiang chao
 * @Time: 2023/1/31 10:31
 * @Classname: OrderBusinessController
 * @PackageName: com.hzs.sale.order.controller.manager
 */
@Slf4j
@RestController
@RequestMapping("/manage/order-business")
public class SaOrderBusinessController extends BaseController {

    @Autowired
    private ISaOrderService iSaOrderService;
    @Autowired
    private IOrderBusinessService iOrderBusinessService;

    @Autowired
    private UserTokenService userTokenService;

    @DubboReference
    private IAreaServiceApi iAreaServiceApi;
    @DubboReference
    private IBusinessCommission iBusinessCommission;
    @DubboReference
    private IProductServiceApi productServiceApi;
    @DubboReference
    private IUserServiceApi iUserServiceApi;
    @DubboReference
    private IMemberServiceApi iMemberServiceApi;
    @DubboReference
    private IServiceChargeServiceApi iServiceChargeServiceApi;
    @DubboReference
    private ICurrencyServiceApi iCurrencyServiceApi;
    @DubboReference
    private ISystemConfigServiceApi systemConfigServiceApi;

    @Autowired
    private ISaOrderSelfLogService saOrderSelfLogService;
    private ISaDeliverItemsService saDeliverItemsService;

    @Autowired
    public void setSaDeliverItemsService(ISaDeliverItemsService saDeliverItemsService) {
        this.saDeliverItemsService = saDeliverItemsService;
    }

    /**
     * 订单业务列表
     *
     * @param param
     * @return
     */
    @Log(module = EOperationModule.HANDLE_BUSINESS, business = EOperationBusiness.ORDER_BUSINESS, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(OrderBusinessParam param) {
        DateUtils.handTimeStartAndEnd(param.getCreationTime());
        DateUtils.handTimeStartAndEnd(param.getPayTime());

        Integer pkCountry = SecurityUtils.getPkCountry();

        // 获取管理员权限（角色地区范围、体系列表、团队列表）
        UserAuthorityDTO userAuthorityDTO = iUserServiceApi.getUserAuthority(SecurityUtils.getUserId()).getData();
        param.setAreaScopeList(userAuthorityDTO.getRoleAreaScopeList());
        param.setVertexIdList(userAuthorityDTO.getVertexIdList());
        param.setTeamList(userAuthorityDTO.getUserTeamList());

        startPage();
        List<OrderBusinessVO> list = iSaOrderService.queryOrderBusinessList(param, pkCountry);
        if (CollectionUtil.isNotEmpty(list)) {
            // 获取行政区划map
            Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();
            // 获得当前国家是日结还是周结
            String settleCycle = systemConfigServiceApi.getBonusSystemConfig(pkCountry, ESystemConfig.EXPAND_CAP_METHOD.getKey()).getData();

            for (OrderBusinessVO orderBusinessVO : list) {
                // 省市区处理
                OrderUtil.handleOrderAddress(areaMap, orderBusinessVO);

                if (pkCountry.equals(CountryConstants.CHINA_COUNTRY)) {
                    if (null != orderBusinessVO.getInExchangeRate()) {
                        orderBusinessVO.setOrderAchieveRmb(orderBusinessVO.getOrderAchieve().multiply(orderBusinessVO.getInExchangeRate()));
                    }
                }

                if (EOrderType.RESALE_INTEGRAL_ORDER.getValue() != orderBusinessVO.getOrderType()) {
                    // 订单类型不为 复消积分订单 才处理是否显示退单
                    // 控制是否显示退单
                    if (Objects.equals(Integer.toString(EExpandCapMethod.WEEK_SETTLE.getValue()), settleCycle)) {
                        // 周结
                        if (null != orderBusinessVO.getPayTime() && DateUtils.compareDateAfter(DateUtils.parseStringToDate(DateUtils.getRecentlyTuesday(DateUtils.currentDate())), orderBusinessVO.getPayTime())) {
                            orderBusinessVO.setReturnFlag(EYesNo.YES.getIntValue());
                        }
                    } else {
                        // 日结
                        if (null != orderBusinessVO.getPayTime() && DateUtils.compareDateAfter(DateUtils.beforeDate(MagicNumberConstants.CANCEL_ORDER, ChronoUnit.DAYS, DateUtils.currentDate()), orderBusinessVO.getPayTime())) {
                            orderBusinessVO.setReturnFlag(EYesNo.YES.getIntValue());
                        }
                    }
                }

            }
        }
        return getDataTable(list);
    }

    /**
     * 下载模板
     *
     * @param response
     */
    @PostMapping("/template")
    public void template(HttpServletResponse response) {
        ExcelUtil<OrderBusinessTemplate> util = new ExcelUtil<>(OrderBusinessTemplate.class);
        util.exportExcel(response, null, "订单业务导入模板");
    }

    /**
     * 导入数据
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Log(module = EOperationModule.HANDLE_BUSINESS, business = EOperationBusiness.ORDER_BUSINESS, method = EOperationMethod.IMPORT)
    @PostMapping("/import")
    public AjaxResult batchDeliverImport(MultipartFile file) throws Exception {
        ExcelUtil<OrderBusinessTemplate> util = new ExcelUtil<>(OrderBusinessTemplate.class);
        List<OrderBusinessTemplate> templateList = util.importExcel(file.getInputStream());

        if (CollectionUtil.isNotEmpty(templateList)) {
            Integer pkCountry = SecurityUtils.getPkCountry();

            OrderBusinessParam param = new OrderBusinessParam();
            param.setOrderCodeList(templateList.stream().map(OrderBusinessTemplate::getOrderCode).collect(Collectors.toList()));
            param.setMemberCodeList(templateList.stream().map(OrderBusinessTemplate::getMemberCodeCode).collect(Collectors.toList()));

            List<OrderBusinessVO> list = iSaOrderService.queryOrderBusinessList(param, pkCountry);

            if (CollectionUtil.isNotEmpty(list)) {
                // 获取行政区划map
                Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();

                for (OrderBusinessVO orderBusinessVO : list) {
                    // 省市区处理
                    OrderUtil.handleOrderAddress(areaMap, orderBusinessVO);
                }
            }
            return AjaxResult.success(list);
        }
        return AjaxResult.success();
    }


    /**
     * 修改地址数据（批量）
     *
     * @param orderList 订单编号列表
     * @return
     */
    @GetMapping("/address-data")
    public AjaxResult addressData(@RequestParam("orderList") List<String> orderList) {
        Integer pkCountry = SecurityUtils.getPkCountry();

        // 去重订单号
        orderList = orderList.stream().distinct().collect(Collectors.toList());

        // 查询订单信息以及详情
        List<SaOrderExt> saOrderList = iSaOrderService.queryOrderListByCodeList(orderList, pkCountry);
        if (CollectionUtil.isEmpty(saOrderList) || orderList.size() != saOrderList.size()) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_NOT_EXIST));
        }

        // 如果已经转结算国，之前订单不能操作
        for (SaOrderExt saOrder : saOrderList) {
            if (!saOrder.getPkCountry().equals(saOrder.getPkSettleCountry())) {
                // 用户已转结算国，不能进行操作
                return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.SETTLEMENT_COUNTRY_NOT_OPERATE));
            }
        }

        // 本次业务修改费用
        Map<Long, OrderQueryChargeDTO> queryChargeMap = iOrderBusinessService.queryChargeLog(saOrderList, EApprovalBusiness.ORDER_CHANGE_ADDRESS, pkCountry);

        // 处理返回订单数据
        List<OrderBusinessAddressVO> resultList = new ArrayList<>(saOrderList.size());
        for (SaOrderExt saOrder : saOrderList) {
            // 订单明细处理
            resultList.add(OrderBusinessAddressVO.builder()
                    .orderCode(saOrder.getOrderCode())
                    .memberCode(saOrder.getMemberCode())
                    .memberName(saOrder.getMemberName())
                    .recName(saOrder.getRecName())
                    .recPhone(saOrder.getRecPhone())
                    .recProvince(saOrder.getRecProvince())
                    .recCity(saOrder.getRecCity())
                    .recCounty(saOrder.getRecCounty())
                    .recAddress(saOrder.getRecAddress())
                    .pkAccount(queryChargeMap.get(saOrder.getPkId()).getPkAccount())
                    .accountKey(queryChargeMap.get(saOrder.getPkId()).getAccountKey())
                    .cost(queryChargeMap.get(saOrder.getPkId()).getCost())
                    .build());
        }
        return AjaxResult.success(resultList);
    }

    /**
     * 修改地址校验
     *
     * @param orderList
     * @return
     */
    @GetMapping("/address-check")
    public AjaxResult addressCheck(@RequestParam("orderList") List<String> orderList) {
        Integer pkCountry = SecurityUtils.getPkCountry();

        // 查询订单信息以及详情
        List<SaOrderExt> saOrderList = iSaOrderService.queryOrderListByCodeList(orderList, pkCountry);
        if (CollectionUtil.isEmpty(saOrderList) || orderList.size() != saOrderList.size()) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_NOT_EXIST));
        }

        // 校验订单是否存在进行中的签呈
        String checkStr = iOrderBusinessService.checkBusinessExist(orderList, pkCountry);
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 本次业务修改费用
        Map<Long, OrderQueryChargeDTO> queryChargeMap = iOrderBusinessService.queryChargeLog(saOrderList, EApprovalBusiness.ORDER_CHANGE_ADDRESS, pkCountry);
        // 业务修改费用
        OrderQueryChargeDTO orderQueryChargeDTO = queryChargeMap.get(saOrderList.get(0).getPkId());
        // 当返回的币种为0时，则不进行处理
        if (0 != orderQueryChargeDTO.getPkAccount()) {
            // 扣款会员数据
            List<MemberBalanceDTO> memberBalanceDTOList = new ArrayList<>();
            // 订单创建人ID列表
            List<Long> pkCreatorList = saOrderList.stream().map(SaOrderExt::getPkCreator).distinct().collect(Collectors.toList());
            // 订单创建会员列表
            List<CuMemberExt> memberList = iMemberServiceApi.findMemberByMemberId(pkCreatorList, null).getData();

            // 实际扣款国家map（key：国家ID， value：会员ID列表）
            Map<Integer, List<Long>> costMemberMap = new HashMap<>();
            for (CuMemberExt cuMemberExt : memberList) {
                // 按国家区分跨国数据
                costMemberMap.computeIfAbsent(cuMemberExt.getPkSettleCountry(), k -> new ArrayList<>()).add(cuMemberExt.getPkId());
            }

            for (Integer costCountry : costMemberMap.keySet()) {
                // 当前国家下的订单涉及会员
                List<Long> costMemberList = costMemberMap.get(costCountry);

                if (pkCountry.equals(costCountry)) {
                    // 当前结算国数据
                    // 扣款map（key 扣款人， value 扣款金额累计）
                    Map<Long, BigDecimal> accountMap = new HashMap<>();
                    // 遍历订单，将同创建人
                    for (SaOrderExt saOrder : saOrderList) {
                        if (costMemberList.contains(saOrder.getPkCreator())) {
                            // 按订单支付人来进行购款
                            accountMap.merge(saOrder.getPkCreator(), queryChargeMap.get(saOrder.getPkId()).getCost(), BigDecimal::add);
                        }
                    }
                    // 校验扣款金额是否足够
                    List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
                    // 封装扣款会员数据
                    for (Long key : accountMap.keySet()) {
                        memberAmountDTOList.add(MemberAmountDTO.builder()
                                .pkMember(key)
                                .tradeAmount(accountMap.get(key))
                                .build());
                    }
                    // 返回的都是有余额不足的，金额为目前账户所剩
                    memberBalanceDTOList.addAll(iBusinessCommission.selectBalanceNotEnoughMember(BusinessCommissionDTO.builder()
                            .pkCountry(costCountry)
                            .pkAccount(orderQueryChargeDTO.getPkAccount())
                            .memberAmountDTOList(memberAmountDTOList)
                            .build()).getData());
                } else {
                    // 跨国数据
                    // 订单创建人所属国家业务扣款账户
                    ServiceChargeDTO costServiceChargeDTO = iServiceChargeServiceApi.getServiceChargeByType(ServiceChargeDTO.builder()
                            .pkCountry(costCountry)
                            .type(EApprovalBusiness.ORDER_CHANGE_PRODUCT.getValue())
                            .quantity(1)
                            .build()).getData();
                    if (null == costServiceChargeDTO) {
                        continue;
                    }

                    // 扣款map（key 扣款人， value 扣款金额累计）
                    Map<Long, BigDecimal> accountMap = new HashMap<>();
                    // 遍历订单，将同创建人
                    for (SaOrderExt saOrder : saOrderList) {
                        if (costMemberList.contains(saOrder.getPkCreator())) {
                            // 按订单支付人来进行购款
                            // 扣款金额
                            BigDecimal cost = queryChargeMap.get(saOrder.getPkId()).getCost();

                            // 根据汇率计算实际需要扣款金额
                            CurrencyDTO costCurrencyDTO = iCurrencyServiceApi.getCurrency(costCountry).getData();
                            // 扣款金额 = 订单结算国扣款金额 除 订单结算国汇率 乘 订单创建人结算国汇率
                            cost = cost.divide(saOrder.getInExchangeRate(), 2, BigDecimal.ROUND_HALF_UP).multiply(costCurrencyDTO.getInExchangeRate()).setScale(2, BigDecimal.ROUND_HALF_UP);
                            accountMap.merge(saOrder.getPkCreator(), cost, BigDecimal::add);
                        }
                    }
                    // 校验扣款金额是否足够
                    List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
                    // 封装扣款会员数据
                    for (Long key : accountMap.keySet()) {
                        memberAmountDTOList.add(MemberAmountDTO.builder()
                                .pkMember(key)
                                .tradeAmount(accountMap.get(key))
                                .build());
                    }
                    // 返回的都是有余额不足的，金额为目前账户所剩
                    memberBalanceDTOList.addAll(iBusinessCommission.selectBalanceNotEnoughMember(BusinessCommissionDTO.builder()
                            .pkCountry(costCountry)
                            .pkAccount(costServiceChargeDTO.getPkAccount())
                            .memberAmountDTOList(memberAmountDTOList)
                            .build()).getData());
                }
            }

            if (CollectionUtil.isNotEmpty(memberBalanceDTOList)) {
                StringBuilder sb = new StringBuilder();
                for (MemberBalanceDTO memberBalanceDTO : memberBalanceDTOList) {
                    sb.append(memberBalanceDTO.getMemberCode()).append("，");
                }
                // 余额不足，是否继续
                sb.append(TransactionUtils.getContent(SaOrderMsgConstants.BALANCE_ENOUGH_CONTINUE));
                return AjaxResult.success(null, sb.toString());
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改地址确认（走签呈）
     *
     * @param paramList
     * @return
     */
    @Log(module = EOperationModule.HANDLE_BUSINESS, business = EOperationBusiness.ORDER_BUSINESS, method = EOperationMethod.SUBMIT, remark = "修改地址")
    @PostMapping("/address-confirm")
    public AjaxResult addressConfirm(@RequestBody List<OrderAddressParam> paramList) {
        if (CollectionUtil.isEmpty(paramList)) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        OrderAddressParam param = paramList.get(0);
        if (null == param.getSignType() || CollectionUtil.isEmpty(param.getItemList())) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        // 订单编号列表
        List<String> orderList = new ArrayList<>();
        for (OrderAddressDetailParam detailParam : param.getItemList()) {
            orderList.add(detailParam.getOrderCode());
            if (StringUtils.isAnyEmpty(detailParam.getOrderCode(), detailParam.getRecName(), detailParam.getRecPhone(), detailParam.getRecAddress())
                    || null == detailParam.getRecProvince() || null == detailParam.getRecCity()) {
                // 订单编号、收货人、收货地址、省、市、详细地址，必填
                return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
            }
        }

        // 校验订单是否存在进行中的签呈
        String checkStr = iOrderBusinessService.checkBusinessExist(orderList, SecurityUtils.getPkCountry());
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 确认修改地址并发起审批
        String str = iOrderBusinessService.changeAddressApprovalSubmit(param, userTokenService.getLoginUser());
        if (null == str) {
            return AjaxResult.success();
        }
        return AjaxResult.error(str);
    }

    /**
     * 修改地址确认（不走签呈）
     *
     * @param paramList
     * @return
     */
    @Log(module = EOperationModule.HANDLE_BUSINESS, business = EOperationBusiness.ORDER_BUSINESS, method = EOperationMethod.FREE_SIGN, remark = "修改地址")
    @PostMapping("/address-confirm-free-sign")
    public AjaxResult addressConfirmFreeSign(@RequestBody List<OrderAddressParam> paramList) {
        if (CollectionUtil.isEmpty(paramList)) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        OrderAddressParam param = paramList.get(0);
        // 订单编号列表
        List<String> orderList = new ArrayList<>();
        for (OrderAddressDetailParam detailParam : param.getItemList()) {
            orderList.add(detailParam.getOrderCode());
            if (StringUtils.isAnyEmpty(detailParam.getOrderCode(), detailParam.getRecName(), detailParam.getRecPhone(), detailParam.getRecAddress())
                    || null == detailParam.getRecProvince() || null == detailParam.getRecCity()) {
                // 订单编号、收货人、收货地址、省、市、详细地址，必填
                return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
            }
        }

        // 校验订单是否存在进行中的签呈
        String checkStr = iOrderBusinessService.checkBusinessExist(orderList, SecurityUtils.getPkCountry());
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 确认修改地址不发起审批
        String str = iOrderBusinessService.changeAddressApprovalFreeSign(param, userTokenService.getLoginUser());
        if (null == str) {
            return AjaxResult.success();
        }
        return AjaxResult.error(str);
    }


    /**
     * 调换货物数据
     *
     * @param orderCode 订单编号
     * @return
     */
    @GetMapping("/product-data")
    public AjaxResult productData(@RequestParam("orderCode") String orderCode) {
        Integer pkCountry = SecurityUtils.getPkCountry();

        // 查询订单信息以及详情
        SaOrderExt saOrder = iSaOrderService.queryOrderByCode(orderCode, pkCountry);
        if (null == saOrder) {
            return AjaxResult.error(orderCode + TransactionUtils.getContent(SaOrderMsgConstants.ORDER_NOT_EXIST));
        }
        if (EOrderType.RESALE_INTEGRAL_ORDER.getValue() == saOrder.getOrderType()) {
            // 复消积分订单不能调换货物
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.NOT_RE_RESALE_INTEGRAL_ORDER));
        }

        // 如果已经转结算国，之前订单不能操作
        if (!saOrder.getPkCountry().equals(saOrder.getPkSettleCountry())) {
            // 用户已转结算国，不能进行操作
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.SETTLEMENT_COUNTRY_NOT_OPERATE));
        }

//        // 过滤赠品，只有非赠品才能进行调换货
//        List<SaOrderItemsExt> orderItemsExtList = saOrder.getOrderItemsExtList().stream().filter(saOrderItemsExt -> EYesNo.NO.getIntValue() == saOrderItemsExt.getIsGift()).collect(Collectors.toList());

        // 业务修改费用
        Map<Long, OrderQueryChargeDTO> queryChargeMap = iOrderBusinessService.queryChargeLog(Collections.singletonList(saOrder), EApprovalBusiness.ORDER_CHANGE_PRODUCT, pkCountry);

        // 调换货物订单以及产品PV是否需要处理
        if (saOrder.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
            // 如果是中国订单
            // 汇率（目前只有中国需要由美金转人民币显示，其它国家显示就是美金不需要转换）
            BigDecimal baseExchangeRate = saOrder.getInExchangeRate();
            if (null != baseExchangeRate) {
                // 基础汇率不为空，则进行转换
                saOrder.setOrderAchieve(saOrder.getOrderAchieve().multiply(baseExchangeRate));

                for (SaOrderItemsExt saOrderItemsExt : saOrder.getOrderItemsExtList()) {
                    saOrderItemsExt.setAchievementRmb(saOrderItemsExt.getAchievement().multiply(baseExchangeRate));
                }
            }
        }

        return AjaxResult.success(OrderBusinessProductVO.builder()
                .orderCode(saOrder.getOrderCode())
                .memberCode(saOrder.getMemberCode())
                .memberName(saOrder.getMemberName())
                .orderAmount(saOrder.getOrderAmount())
                .orderAchieve(saOrder.getOrderAchieve())
                .orderAssAchievement(saOrder.getOrderAssAchieve())
                .postage(saOrder.getPostage())
                .detailList(BeanUtil.copyToList(saOrder.getOrderItemsExtList(), OrderBusinessProductDetailVO.class))
                .pkAccount(queryChargeMap.get(saOrder.getPkId()).getPkAccount())
                .accountKey(queryChargeMap.get(saOrder.getPkId()).getAccountKey())
                .cost(queryChargeMap.get(saOrder.getPkId()).getCost())
                .build());
    }

    /**
     * 调换货物校验
     *
     * @param orderCode 订单编号
     * @return
     */
    @GetMapping("/product-check")
    public AjaxResult productCheck(@RequestParam("orderCode") String orderCode) {
        Integer pkCountry = SecurityUtils.getPkCountry();

        // 查询订单信息以及详情
        SaOrderExt saOrder = iSaOrderService.queryOrderByCode(orderCode, pkCountry);
        if (null == saOrder) {
            return AjaxResult.error(orderCode + TransactionUtils.getContent(SaOrderMsgConstants.ORDER_NOT_EXIST));
        }

        // 校验订单是否存在进行中的签呈
        String checkStr = iOrderBusinessService.checkBusinessExist(Collections.singletonList(orderCode), pkCountry);
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 业务修改费用
        Map<Long, OrderQueryChargeDTO> queryChargeMap = iOrderBusinessService.queryChargeLog(Collections.singletonList(saOrder), EApprovalBusiness.ORDER_CHANGE_PRODUCT, pkCountry);
        // 业务手续费数据
        OrderQueryChargeDTO orderQueryChargeDTO = queryChargeMap.get(saOrder.getPkId());

        if (orderQueryChargeDTO.getCost().compareTo(BigDecimal.ZERO) > 0) {
            // 扣款金额大于0，则进行处理
            // 扣款国家
            Integer costCountry = pkCountry;
            // 扣款账户
            Integer costAccount = orderQueryChargeDTO.getPkAccount();
            // 扣款金额
            BigDecimal cost = orderQueryChargeDTO.getCost();

            // 订单下单人信息
            CuMember cuMember = iMemberServiceApi.getMember(saOrder.getPkCreator()).getData();
            if (!costCountry.equals(cuMember.getPkSettleCountry())) {
                // 当前国家与订单创建人结算国家不同，跨国报单需要转换手续费
                costCountry = cuMember.getPkSettleCountry();

                // 订单创建人所属国家业务扣款账户
                ServiceChargeDTO costServiceChargeDTO = iServiceChargeServiceApi.getServiceChargeByType(ServiceChargeDTO.builder()
                        .pkCountry(costCountry)
                        .type(EApprovalBusiness.ORDER_CHANGE_PRODUCT.getValue())
                        .quantity(1)
                        .build()).getData();
                if (null == costServiceChargeDTO) {
                    return AjaxResult.success();
                }
                costAccount = costServiceChargeDTO.getPkAccount();

                // 根据汇率计算实际需要扣款金额
                CurrencyDTO costCurrencyDTO = iCurrencyServiceApi.getCurrency(costCountry).getData();
                // 扣款金额 = 订单结算国扣款金额 除 订单结算国汇率 乘 订单创建人结算国汇率
                cost = cost.divide(saOrder.getInExchangeRate(), 2, BigDecimal.ROUND_HALF_UP).multiply(costCurrencyDTO.getInExchangeRate()).setScale(2, BigDecimal.ROUND_HALF_UP);
            }

            // 校验扣款金额是否足够
            List<MemberBalanceDTO> memberBalanceDTOList = iBusinessCommission.selectBalanceNotEnoughMember(BusinessCommissionDTO.builder()
                    .pkCountry(costCountry)
                    .pkAccount(costAccount)
                    .memberAmountDTOList(Collections.singletonList(MemberAmountDTO.builder()
                            // 订单创建人（下单人）
                            .pkMember(saOrder.getPkCreator())
                            .tradeAmount(cost)
                            .build()))
                    .build()).getData();
            if (CollectionUtil.isNotEmpty(memberBalanceDTOList)) {
                // 余额不足，是否继续
                return AjaxResult.success(null, memberBalanceDTOList.get(0).getMemberCode() + TransactionUtils.getContent(SaOrderMsgConstants.BALANCE_ENOUGH_CONTINUE));
            }
        }
        return AjaxResult.success();
    }

    /**
     * 调换货物确认（走签呈）
     *
     * @param paramList
     * @return
     */
    @Log(module = EOperationModule.HANDLE_BUSINESS, business = EOperationBusiness.ORDER_BUSINESS, method = EOperationMethod.SUBMIT, remark = "调换货物")
    @PostMapping("/product-confirm")
    public AjaxResult productConfirm(@RequestBody List<OrderProductParam> paramList) {
        if (CollectionUtil.isEmpty(paramList)) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        // 调换货物为单个操作，此处只需要取第一条就行
        OrderProductParam param = paramList.get(0);
        if (null == param.getSignType() || CollectionUtil.isEmpty(param.getItemList())) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        if (StringUtils.isEmpty(param.getOrderCode()) || null == param.getPostage() || CollectionUtil.isEmpty(param.getItemList())) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        for (OrderProductDetailParam detailParam : param.getItemList()) {
            if (StringUtils.isAnyEmpty(detailParam.getSpecsName(), detailParam.getSpecsNameId())
                    || null == detailParam.getPkProduct() || null == detailParam.getQuantity() || null == detailParam.getPrice()
                    || (null == detailParam.getAchievement() || null == detailParam.getAssAchievement())) {
                return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
            }
            // 如果没有传入是否赠品，默认为否
            if (null == detailParam.getIsGift()) {
                detailParam.setIsGift(EDealerYesNo.NO.getValue());
            }
        }

        Integer pkCountry = SecurityUtils.getPkCountry();

        // 校验订单是否存在进行中的签呈
        String checkStr = iOrderBusinessService.checkBusinessExist(Collections.singletonList(param.getOrderCode()), pkCountry);
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 确认调换货物并发起审批
        String str = iOrderBusinessService.changeProductApprovalSubmit(param, userTokenService.getLoginUser());
        if (null == str) {
            return AjaxResult.success();
        }
        return AjaxResult.error(str);
    }

    /**
     * 调换货物确认（不走签呈）
     *
     * @param paramList
     * @return
     */
    @Log(module = EOperationModule.HANDLE_BUSINESS, business = EOperationBusiness.ORDER_BUSINESS, method = EOperationMethod.FREE_SIGN, remark = "调换货物")
    @PostMapping("/product-confirm-free-sign")
    public AjaxResult productConfirmFreeSign(@RequestBody List<OrderProductParam> paramList) {
        if (CollectionUtil.isEmpty(paramList)) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        // 调换货物为单个操作，此处只需要取第一条就行
        OrderProductParam param = paramList.get(0);
        if (StringUtils.isEmpty(param.getOrderCode()) || null == param.getPostage() || CollectionUtil.isEmpty(param.getItemList())) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        for (OrderProductDetailParam detailParam : param.getItemList()) {
            if (StringUtils.isAnyEmpty(detailParam.getSpecsName(), detailParam.getSpecsNameId())
                    || null == detailParam.getPkProduct() || null == detailParam.getQuantity() || null == detailParam.getPrice()
                    || (null == detailParam.getAchievement() || null == detailParam.getAssAchievement())) {
                return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
            }
            // 如果没有传入是否赠品，默认为否
            if (null == detailParam.getIsGift()) {
                detailParam.setIsGift(EDealerYesNo.NO.getValue());
            }
        }

        Integer pkCountry = SecurityUtils.getPkCountry();

        // 校验订单是否存在进行中的签呈
        String checkStr = iOrderBusinessService.checkBusinessExist(Collections.singletonList(param.getOrderCode()), pkCountry);
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 调换货物不走签呈
        String str = iOrderBusinessService.changeProductApprovalFreeSign(param, userTokenService.getLoginUser());
        if (null == str) {
            return AjaxResult.success();
        }
        return AjaxResult.error(str);
    }


    /**
     * 退单数据
     *
     * @param orderCode 订单编号
     * @return
     */
    @GetMapping("/return-data")
    public AjaxResult returnData(@RequestParam("orderCode") String orderCode) {
        // 查询订单信息以及详情
        SaOrderExt saOrder = iSaOrderService.queryOrderByCode(orderCode, SecurityUtils.getPkCountry());
        if (null == saOrder) {
            // 订单已不存在
            return AjaxResult.error(orderCode + TransactionUtils.getContent(SaOrderMsgConstants.ORDER_NOT_EXIST));
        }
        if (EPayStatus.UNPAID.getValue() == saOrder.getOrderStatus()) {
            // 未支付订单，不能进行退单
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_UNPAID_NOT_RETURN));
        }

        // 如果已经转结算国，之前订单不能操作
        if (!saOrder.getPkCountry().equals(saOrder.getPkSettleCountry())) {
            // 用户已转结算国，不能进行操作
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.SETTLEMENT_COUNTRY_NOT_OPERATE));
        }

        // 2023-09-06 00:00:00 之前的订单不能进行退单
        long dateLong = 1693929600000L;
        if (saOrder.getCreationTime().getTime() < dateLong) {
            return AjaxResult.error("历史订单撤单请联系管理员");
        }

        return AjaxResult.success(saOrder);
    }

    /**
     * 退单确认（走签呈）
     *
     * @param paramList
     * @return
     */
    @Log(module = EOperationModule.HANDLE_BUSINESS, business = EOperationBusiness.ORDER_BUSINESS, method = EOperationMethod.SUBMIT, remark = "退单")
    @PostMapping("/return-confirm")
    public AjaxResult returnConfirm(@RequestBody List<OrderReturnParam> paramList) {
        if (CollectionUtil.isEmpty(paramList)) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        OrderReturnParam param = paramList.get(0);
        if (StringUtils.isAnyEmpty(param.getOrderCode(), param.getReturnRemark()) || null == param.getSignType() || null == param.getReturnAmount()) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }

        Integer pkCountry = SecurityUtils.getPkCountry();

        // 校验订单是否存在进行中的签呈
        String checkStr = iOrderBusinessService.checkBusinessExist(Collections.singletonList(param.getOrderCode()), pkCountry);
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 确认退单并发起审批
        String str = iOrderBusinessService.returnOrderApprovalSubmit(param, userTokenService.getLoginUser());
        if (null == str) {
            return AjaxResult.success();
        }
        return AjaxResult.error(str);
    }

    /**
     * 合并退单数据
     *
     * @param orderCode 订单编号
     * @return
     */
    @GetMapping("/return-data-batch")
    public AjaxResult returnDataBatch(@RequestParam("orderCode") String orderCode) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 查询订单信息以及详情
        SaOrderExt saOrder = iSaOrderService.queryOrderByCode(orderCode, pkCountry);
        if (null == saOrder) {
            // 订单已不存在
            return AjaxResult.error(orderCode + TransactionUtils.getContent(SaOrderMsgConstants.ORDER_NOT_EXIST));
        }
        if (EPayStatus.UNPAID.getValue() == saOrder.getOrderStatus()) {
            // 未支付订单，不能进行退单
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_UNPAID_NOT_RETURN));
        }

//        if (EOrderType.REGISTER_ORDER.getValue() != saOrder.getOrderType()
//                && EOrderType.FANS_ORDER.getValue() != saOrder.getOrderType()) {
//            // 非 注册订单、嗨粉注册订单 不能进行合并退单
//            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_NOT_RETURN));
//        }

        // 如果已经转结算国，之前订单不能操作
        if (!saOrder.getPkCountry().equals(saOrder.getPkSettleCountry())) {
            // 用户已转结算国，不能进行操作
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.SETTLEMENT_COUNTRY_NOT_OPERATE));
        }

        // 2023-09-06 00:00:00 之前的订单不能进行退单
        long dateLong = 1693929600000L;
        if (saOrder.getCreationTime().getTime() < dateLong) {
            return AjaxResult.error("历史订单撤单请联系超级管理员");
        }

        List<SaOrderExt> resultList = new ArrayList<>();
        resultList.add(saOrder);

//        if (EOrderType.REGISTER_ORDER.getValue() == saOrder.getOrderType()
//                || EOrderType.FANS_ORDER.getValue() == saOrder.getOrderType()
//                || EOrderType.SPECIAL_REGISTER_ORDER.getValue() == saOrder.getOrderType()
//        ) {
//            // 注册类订单，需要拉取所有订单
//            resultList.addAll(iSaOrderService.queryAllOrderByMember(saOrder.getPkMember(), pkCountry));
//        }

//        iSaOrderService.queryPlaceParentOrderList(saOrder.getPkMember());

        return AjaxResult.success(resultList);
    }

    /**
     * 合并退单确认（走签呈）
     *
     * @param paramList 批量退单入参
     * @return
     */
    @Log(module = EOperationModule.HANDLE_BUSINESS, business = EOperationBusiness.ORDER_BUSINESS, method = EOperationMethod.SUBMIT, remark = "合并退单")
    @PostMapping("/return-batch-confirm")
    public AjaxResult returnBatchConfirm(@RequestBody List<OrderReturnBatchParam> paramList) {
        if (CollectionUtil.isEmpty(paramList)) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }

        OrderReturnBatchParam param = paramList.get(0);
        if (null == param.getSignType() || CollectionUtil.isEmpty(param.getUserIdList())) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }

        List<String> orderCodeList = new ArrayList<>();
        for (OrderReturnParam orderReturnParam : param.getOrderReturnParamList()) {
            if (StringUtils.isEmpty(orderReturnParam.getOrderCode())) {
                // 缺少参数
                return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
            }
            orderCodeList.add(orderReturnParam.getOrderCode());
        }

        // 校验订单是否存在进行中的签呈
        String checkStr = iOrderBusinessService.checkBusinessExist(orderCodeList, SecurityUtils.getPkCountry());
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 确认退单并发起审批
        String str = iOrderBusinessService.batchReturnOrderApprovalSubmit(param, userTokenService.getLoginUser());
        if (null == str) {
            return AjaxResult.success();
        }
        return AjaxResult.error(str);
    }


    /**
     * 撤销订单数据（批量）,点击撤单按钮,整单撤销
     * 查询伞下会员信息
     *
     * @param orderCancelParam 订单列表
     */
    @PostMapping("/cancel-order-submit")
    @Log(module = EOperationModule.CANCEL_ORDER_SUBMIT, method = EOperationMethod.INSERT)
    public AjaxResult cancelData(@RequestBody OrderCancelParam orderCancelParam) {
        orderCancelParam.setPkCountry(SecurityUtils.getPkCountry());
        ValidateCancelOrderVO validateCancelOrderVO = iOrderBusinessService.validateCancelOrder(orderCancelParam);
        if (validateCancelOrderVO.getSaOrderExt() == null) {
            return AjaxResult.error(validateCancelOrderVO.getMsg());
        }
        // 本次业务修改费用
        List<SaOrderExt> saOrderExtList = new ArrayList<>();
        SaOrderExt saOrderExt = validateCancelOrderVO.getSaOrderExt();
        saOrderExtList.add(saOrderExt);
        EApprovalBusiness approveBusiness = EApprovalBusiness.ORDER_CANCEL;
        if (ECancelOrderType.OTHER_CANCEL_PART_ORDER.getValue() == orderCancelParam.getCancelType()) {
            approveBusiness = EApprovalBusiness.ORDER_CANCEL_PRODUCT;
        }
        Map<Long, OrderQueryChargeDTO> queryChargeMap = iOrderBusinessService.queryChargeLog(saOrderExtList, approveBusiness, SecurityUtils.getPkCountry());
        // 撤销订单，撤销产品，撤销除升级订单
        if (ECancelOrderType.MERGE_CANCEL_ORDER.getValue() == orderCancelParam.getCancelType()) {
            // 撤销升级订单
            return AjaxResult.success(OrderCancelVO.builder()
                    .orderCode(validateCancelOrderVO.getSaOrderExt().getOrderCode())
                    .memberList(validateCancelOrderVO.getMemberList())
                    .pkAccount(queryChargeMap.get(saOrderExt.getPkId()).getPkAccount())
                    .accountKey(queryChargeMap.get(saOrderExt.getPkId()).getAccountKey())
                    .cost(queryChargeMap.get(saOrderExt.getPkId()).getCost())
                    .build());
        } else {
            OrderCancelVO orderCancelVO = OrderCancelVO.builder()
                    .orderCode(saOrderExt.getOrderCode())
                    .build();
            List<OrderCancelDetailVO> orderCancelDetailVOList = new ArrayList<>();
            if (ECancelOrderType.OTHER_CANCEL_PART_ORDER.getValue() == orderCancelParam.getCancelType()) {
                saOrderExt.getOrderItemsList().forEach(saOrderItems -> {
                    String productName = productServiceApi.getProduct(saOrderItems.getPkProduct()).getData().getProductName();
                    OrderCancelDetailVO orderCancelDetailVO = OrderCancelDetailVO.builder()
                            .pkId(saOrderItems.getPkId())
                            .productName(productName)
                            .orderAmount(saOrderItems.getPrice())
                            .number(saOrderItems.getQuantity())
                            .achievement(saOrderItems.getAchievement())
                            .assAchievement(saOrderItems.getAssAchievement())
                            .build();
                    orderCancelDetailVOList.add(orderCancelDetailVO);
                });
            } else {
                saOrderExt.getOrderItemsExtList().forEach(saOrderItems -> {
                    OrderCancelDetailVO orderCancelDetailVO = OrderCancelDetailVO.builder()
                            .pkId(saOrderItems.getPkId())
                            .productName(saOrderItems.getProductName())
                            .orderAmount(saOrderItems.getPrice())
                            .number(saOrderItems.getQuantity())
                            .achievement(saOrderItems.getAchievement())
                            .assAchievement(saOrderItems.getAssAchievement())
                            .build();
                    orderCancelDetailVOList.add(orderCancelDetailVO);
                });
            }
            orderCancelVO.setOrderCancelDetailVOList(orderCancelDetailVOList);
            orderCancelVO.setMemberCode(saOrderExt.getMemberCode());
            orderCancelVO.setMemberName(saOrderExt.getMemberName());
            orderCancelVO.setPkAccount(queryChargeMap.get(saOrderExt.getPkId()).getPkAccount());
            orderCancelVO.setAccountKey(queryChargeMap.get(saOrderExt.getPkId()).getAccountKey());
            orderCancelVO.setCost(queryChargeMap.get(saOrderExt.getPkId()).getCost());
            return AjaxResult.success(orderCancelVO);
        }
    }

    /**
     * 撤销订单并入库（走签呈），签呈页面点击确定按钮
     *
     * @param orderCancelParam 参数
     */
    @PostMapping("/cancel-order-confirm")
    @Log(module = EOperationModule.CANCEL_ORDER_CONFIRM, method = EOperationMethod.INSERT)
    public AjaxResult cancelOrder(@RequestBody OrderCancelParam orderCancelParam) {
        orderCancelParam.setPkCountry(SecurityUtils.getPkCountry());
        if (ECancelOrderType.OTHER_CANCEL_PART_ORDER.getValue() == orderCancelParam.getCancelType()) {
            if (orderCancelParam.getOrderCancelDetailParamList() == null || orderCancelParam.getOrderCancelDetailParamList().size() == 0) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
            }
        }
        ValidateCancelOrderVO validateCancelOrderVO = iOrderBusinessService.validateCancelOrder(orderCancelParam);
        AjaxResult validateCancelOrder = validateCancelOrderVO(orderCancelParam, validateCancelOrderVO);
        if (validateCancelOrder != null) {
            return validateCancelOrder;
        }
        iOrderBusinessService.cancelOrder(orderCancelParam, validateCancelOrderVO, userTokenService.getLoginUser());
        return AjaxResult.success();
    }

    /**
     * 撤销订单并入库,全免
     *
     * @param orderCancelParam 参数
     */
    @PostMapping("/free-cancel-order-confirm")
    @Log(module = EOperationModule.CANCEL_ORDER_CONFIRM, method = EOperationMethod.INSERT)
    public AjaxResult freeCostCancelOrder(@RequestBody OrderCancelParam orderCancelParam) {
        orderCancelParam.setPkCountry(SecurityUtils.getPkCountry());
        if (ECancelOrderType.OTHER_CANCEL_PART_ORDER.getValue() == orderCancelParam.getCancelType()) {
            if (orderCancelParam.getOrderCancelDetailParamList() == null || orderCancelParam.getOrderCancelDetailParamList().size() == 0) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
            }
        }
        if (orderCancelParam.getCancelRoad() == null || (orderCancelParam.getCancelRoad() != 1 && orderCancelParam.getCancelRoad() != 3)) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
        }
        ValidateCancelOrderVO validateCancelOrderVO = iOrderBusinessService.validateCancelOrder(orderCancelParam);
        AjaxResult validateCancelOrder = validateCancelOrderVO(orderCancelParam, validateCancelOrderVO);
        if (validateCancelOrder != null) {
            return validateCancelOrder;
        }
        // 2023.11.22 不走签呈也需要添加中间操作表，用于区分部分撤单和调换货物
        iOrderBusinessService.revokeSaOrderByOrderCode(SecurityUtils.getUserId(), orderCancelParam, validateCancelOrderVO);
        return AjaxResult.success();
    }

    private AjaxResult validateCancelOrderVO(OrderCancelParam orderCancelParam, ValidateCancelOrderVO validateCancelOrderVO) {
        if (validateCancelOrderVO.getSaOrderExt() == null) {
            return AjaxResult.error(validateCancelOrderVO.getMsg());
        }
        if (ECancelOrderType.OTHER_CANCEL_PART_ORDER.getValue() == orderCancelParam.getCancelType()) {
            SaOrderExt saOrderExt = validateCancelOrderVO.getSaOrderExt();
            if (saOrderExt.getOrderItemsList() == null) {
                return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_EMPTY));
            }
            Map<Long, String> productMap = new HashMap<>(ComputeUtil.mapInitCapacity(orderCancelParam.getOrderCancelDetailParamList().size()));
            saOrderExt.getOrderItemsList().forEach(saOrderItems -> {
                String productName = productServiceApi.getProduct(saOrderItems.getPkProduct()).getData().getProductName();
                productMap.put(saOrderItems.getPkId(), productName);
            });
            orderCancelParam.getOrderCancelDetailParamList().forEach(orderCancelDetailParam -> {
                if (productMap.containsKey(orderCancelDetailParam.getPkId())) {
                    orderCancelDetailParam.setProductName(productMap.get(orderCancelDetailParam.getPkId()));
                }
            });
        }
        return null;
    }


    /**
     * 订单业务列表
     *
     * @param selfPickUpParam 自提参数
     */
    @Log(module = EOperationModule.SELF_ORDER, business = EOperationBusiness.ORDER_BUSINESS, method = EOperationMethod.SELECT)
    @PostMapping("/self-list")
    public TableDataInfo selfOrderList(@RequestBody SelfPickUpParam selfPickUpParam) {
        startPage();
        selfPickUpParam.setPkSettleCountry(SecurityUtils.getPkCountry());
//        if (selfPickUpParam.getApproveStatus() == null) {
//            selfPickUpParam.setApproveStatus(EApproveRechargeStatus.SUBMIT.getValue());
//        }
        if (selfPickUpParam.getEndDate() != null) {
            selfPickUpParam.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, selfPickUpParam.getEndDate()));
        }
        List<SaOrderSelfLogExt> orderSelfLogList = saOrderSelfLogService.querySaOrderSelfLog(selfPickUpParam);
        return getDataTable(orderSelfLogList);
    }

    /**
     * 自提订单-同意驳回
     *
     * @param selfPickUpParam 自提参数
     */
    @Log(module = EOperationModule.SELF_ORDER, business = EOperationBusiness.ORDER_BUSINESS, method = EOperationMethod.APPROVAL)
    @PostMapping("/self-approve")
    public AjaxResult agreeMemberSelf(@RequestBody SelfPickUpParam selfPickUpParam) {
        if (selfPickUpParam.getPkId() == null || selfPickUpParam.getOrderCode() == null || selfPickUpParam.getApproveStatus() == null) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_EMPTY));
        }
        SaOrderSelfLog saOrderSelfLog = saOrderSelfLogService.querySaOrderSelfLogById(selfPickUpParam.getPkId());
        if (saOrderSelfLog == null || selfPickUpParam.getApproveStatus() <= saOrderSelfLog.getApproveStatus()) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_EMPTY));
        }
        // 代表同意 或驳回
        if (EApproveRechargeStatus.SUBMIT.getValue() != saOrderSelfLog.getApproveStatus()) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.SELF_ORDER_APPROVE));
        }
        SaOrder saOrder = iSaOrderService.querySaleOrderByOrderCode(SaOrder.builder().orderStatus(EOrderStatus.PAY.getValue()).orderCode(selfPickUpParam.getOrderCode()).build());
        if (saOrder == null) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_EMPTY));
        } else {
            // 验证订单只能是当天的
            if (EApproveRechargeStatus.REJECT.getValue() != selfPickUpParam.getApproveStatus() &&
                    !DateUtils.compareDateEqual(DateUtils.currentDate(), saOrder.getPayTime())) {
                return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_CURRENT_DATE));
            }
            selfPickUpParam.setPkCreator(SecurityUtils.getUserId());
            saOrderSelfLogService.updateSaOrderSelfLog(selfPickUpParam, selfPickUpParam.getPkId());
            return AjaxResult.success(selfPickUpParam);
        }
    }

    /**
     * 自提订单-自提
     *
     * @param selfPickUpParam 自提参数
     */
    @Log(module = EOperationModule.SELF_ORDER, business = EOperationBusiness.ORDER_BUSINESS, method = EOperationMethod.SELECT)
    @PostMapping("/self-order")
    public AjaxResult selfOrder(@RequestBody SelfPickUpParam selfPickUpParam) {
        if (selfPickUpParam.getPkId() == null) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_EMPTY));
        }
        SaOrderSelfLog saOrderSelfLog = saOrderSelfLogService.querySaOrderSelfLogById(selfPickUpParam.getPkId());
        if (saOrderSelfLog == null || EApproveRechargeStatus.WAIT.getValue() != saOrderSelfLog.getApproveStatus()) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_EMPTY));
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<Long> orderIdList = new ArrayList<>();
        orderIdList.add(saOrderSelfLog.getPkOrder());
        // 订单 + 明细列表
        List<SaOrderExt> saOrderExtList = iSaOrderService.queryOrderListByIdList(orderIdList, pkCountry);

        // 去重订单号列表
        List<String> orderCodeList = saOrderExtList.stream().map(SaOrderExt::getOrderCode).distinct().collect(Collectors.toList());
        // 校验订单是否存在进行中的签呈
        String checkStr = iOrderBusinessService.checkBusinessExist(orderCodeList, pkCountry);
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 提货商品列表
        List<SelfDataProductVO> productList = new ArrayList<>();
        // 追溯码列表
        List<SelfDataBarCodeVO> barCodeList = new ArrayList<>();

        for (SaOrderExt saOrderExt : saOrderExtList) {
            for (SaOrderItemsExt saOrderItemsExt : saOrderExt.getOrderItemsExtList()) {
                if (EOrderStatus.PAY.getValue() != saOrderItemsExt.getOrderStatus()) {
                    // 不为已付款，则不允许进行自提
                    return AjaxResult.error(saOrderItemsExt.getProductName() + TransactionUtils.getContent(SaOrderMsgConstants.DELIVER_NOT_SELF));
                }

                // 自提商品数据
                productList.add(SelfDataProductVO.builder()
                        .itemId(saOrderItemsExt.getPkId())
                        .orderCode(saOrderItemsExt.getOrderCode())
                        .productName(saOrderItemsExt.getProductName())
                        .specsName(saOrderItemsExt.getSpecsName())
                        .quantity(saOrderItemsExt.getQuantity())
                        .memberCode(saOrderItemsExt.getMemberCode())
                        .memberName(saOrderItemsExt.getMemberName())
                        .build());

                for (int i = 0; i < saOrderItemsExt.getQuantity(); i++) {
                    // 追溯码数据
                    barCodeList.add(SelfDataBarCodeVO.builder()
                            .itemId(saOrderItemsExt.getPkId())
                            .orderCode(saOrderItemsExt.getOrderCode())
                            .productId(saOrderItemsExt.getPkProduct())
                            .productName(saOrderItemsExt.getProductName())
                            .specsName(saOrderItemsExt.getSpecsName())
                            .build());
                }
            }
        }

        return AjaxResult.success(SelfDataVO.builder()
                .productList(productList)
                .barCodeList(barCodeList)
                .build());
    }

    /**
     * @param orderQueryParam 订单参数
     * @Description: 撤销订单
     * @return: AjaxResult
     * @Author: sui q
     * @Date: 2022/8/27 16:56
     */
    @PostMapping("/validate-bind")
    public AjaxResult validateOrderBindBarCode(@RequestBody OrderQueryParam orderQueryParam) {
        log.info(orderQueryParam.getOrderCode());
        // 验证订单编号、订单类型是否存在
        if (StringUtils.isEmpty(orderQueryParam.getOrderCode())) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_CODE_EMPTY));
        }
        if (saDeliverItemsService.validateOrderBindBarCode(orderQueryParam.getOrderCode(), orderQueryParam.getItemIdList())) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_BIND_BAR_CODE));
        }
        return AjaxResult.success();
    }

    /**
     * 查询列表,查询代发货的店铺自提、店铺配送订单
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/list-store-order")
    @Log(module = EOperationModule.STORE_SEND, business = EOperationBusiness.STORE_SEND, method = EOperationMethod.SELECT)
    public TableDataInfo listStoreOrder(@RequestBody OrderQueryParam orderQueryParam) {
        startPage();
        orderQueryParam.setPkCountry(SecurityUtils.getPkCountry());
        orderQueryParam.setOrderStatus(EOrderStatus.PAY.getValue());
        List<SaOrderExt> saOrderExtList = iSaOrderService.queryStoreSaOrderByParam(orderQueryParam);
        List<OrderVo> orderVoList = getOrderVos(saOrderExtList);
        TableDataInfo dataTable = getDataTable(saOrderExtList);
        dataTable.setRows(orderVoList);
        return dataTable;
    }

    /**
     * 分页查询会员某个时间段内的奖金汇总
     */
    @PostMapping("/export-store-order")
    @Log(module = EOperationModule.STORE_SEND, business = EOperationBusiness.STORE_SEND, method = EOperationMethod.EXPORT)
    public void exportListAvailableNum(HttpServletResponse response, OrderQueryParam orderQueryParam) {
        orderQueryParam.setPkCountry(SecurityUtils.getPkCountry());
        orderQueryParam.setOrderStatus(EOrderStatus.PAY.getValue());
        List<SaOrderExt> saOrderExtList = iSaOrderService.queryStoreSaOrderByParam(orderQueryParam);
        List<StoreOrderVo> orderVoList = new ArrayList<>();
        for (SaOrderExt saOrderExt : saOrderExtList) {
            if (saOrderExt.getOrderItemsExtList() != null && saOrderExt.getOrderItemsExtList().size() > 0) {
                for (int i = 0; i < saOrderExt.getOrderItemsExtList().size(); i++) {
                    SaOrderItemsExt saOrderItemsExt = saOrderExt.getOrderItemsExtList().get(i);
                    StoreOrderVo orderVo = BeanUtil.copyProperties(saOrderExt, StoreOrderVo.class);
                    orderVo.setPkId(saOrderExt.getPkId());
                    orderVo.setRecProvince(saOrderExt.getRecProvinceName());
                    orderVo.setRecCity(saOrderExt.getRecCityName());
                    orderVo.setProductName(saOrderItemsExt.getProductName());
                    orderVo.setProductCode(saOrderItemsExt.getProductCode());
                    orderVo.setSpecsName(saOrderItemsExt.getSpecsName());
                    orderVo.setQuantity(saOrderItemsExt.getQuantity());
                    for (EOrderType orderType : EOrderType.values()) {
                        if (orderType.getValue() == orderVo.getOrderType()) {
                            orderVo.setOrderTypeVal(orderType.getLabel());
                            break;
                        }
                    }
                    for (EOrderStatus orderStatus : EOrderStatus.values()) {
                        if (orderStatus.getValue() == orderVo.getOrderStatus()) {
                            orderVo.setOrderStatusVal(orderStatus.getLabel());
                            break;
                        }
                    }
                    orderVoList.add(orderVo);
                }
            }

        }
        ExcelUtil<StoreOrderVo> util = new ExcelUtil<>(StoreOrderVo.class);
        util.exportExcel(response, orderVoList, "店铺订单导出");
    }

    private static List<OrderVo> getOrderVos(List<SaOrderExt> saOrderExtList) {
        List<OrderVo> orderVoList = new ArrayList<>();
        for (SaOrderExt saOrderExt : saOrderExtList) {
            OrderVo orderVo = BeanUtil.copyProperties(saOrderExt, OrderVo.class);
            orderVo.setPkId(saOrderExt.getPkId());
            orderVo.setRecProvince(saOrderExt.getRecProvinceName());
            orderVo.setRecCity(saOrderExt.getRecCityName());
            orderVo.setOrderItemVOList(BeanUtil.copyToList(saOrderExt.getOrderItemsExtList(), OrderItemVO.class));
            orderVoList.add(orderVo);
        }
        return orderVoList;
    }
}
