/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: OrderAdapter
 * @Package cn.freemud.adapter
 * @Description:
 * @author: liming.guo
 * @date: 2018/5/21 20:34
 * @version V1.0
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
package cn.freemud.adapter;

import cn.freemud.base.util.DateUtil;
import cn.freemud.constant.CommonsConstant;
import cn.freemud.constant.CustomerScoreConstant;
import cn.freemud.constant.RedisKeyConstant;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.bo.CreateOrderBONew;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.order.CreateOrderOperateDto;
import cn.freemud.entities.dto.order.CreatePrepayRequestDto;
import cn.freemud.entities.dto.order.UnifiedPayResponseDto;
import cn.freemud.entities.dto.pay.*;
import cn.freemud.entities.dto.promotion.OrderBeanRequest;
import cn.freemud.entities.dto.promotion.ShoppingCartGoodsResponse;
import cn.freemud.entities.dto.shoppingCart.ActivityDiscountsDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.ttpay.OrderInfo;
import cn.freemud.entities.vo.*;
import cn.freemud.entities.vo.encircle.CreateReserveOrderVo;
import cn.freemud.entities.vo.encircle.PreviewOrderInfoVo;
import cn.freemud.entities.vo.order.CreateOrderUnionPayCardVo;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.enums.OrderChannelType;
import cn.freemud.enums.PayStatus;
import cn.freemud.enums.QueryOrderStatus;
import cn.freemud.enums.RefundStatus;
import cn.freemud.enums.ResponseResult;
import cn.freemud.enums.*;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.management.entities.dto.request.BatchOrderRefundV2Request;
import cn.freemud.management.entities.dto.request.pay.PayRefundRequestDto;
import cn.freemud.redis.RedisCache;
import cn.freemud.utils.AppLogUtil;
import cn.freemud.utils.BarcodeUtil;
import cn.freemud.utils.QrCodeUtil;
import cn.freemud.utils.WebUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freemud.api.assortment.datamanager.entity.db.AssortmentOpenPlatformPartnerConfig;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.api.assortment.datamanager.enums.IappIdType;
import com.freemud.api.assortment.datamanager.manager.AssortmentOpenPlatformPartnerConfigManager;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.adapter.OrderCenterSdkAdapter;
import com.freemud.application.sdk.api.ordercenter.entities.v1.*;
import com.freemud.application.sdk.api.ordercenter.enums.*;
import com.freemud.application.sdk.api.ordercenter.enums.OrderType;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.OrderStatusV1;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.OrderTypeV1;
import com.freemud.application.sdk.api.ordercenter.request.AfterOrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.request.OrderConditionsReq;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtendedReq;
import com.freemud.application.sdk.api.ordercenter.response.BaseDownLoadResponse;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.AfterSalesOrderResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderSettlementResp;
import com.freemud.sdk.api.assortment.order.constant.OrderRedisKeyConstant;
import com.freemud.sdk.api.assortment.order.entities.OrderRefundConfigEntity;
import com.freemud.sdk.api.assortment.order.entities.promption.ActivityUpdateStockRequest;
import com.freemud.sdk.api.assortment.order.entities.promption.SubtractStockGoodsVO;
import com.freemud.sdk.api.assortment.order.entities.promption.SubtractStockVO;
import com.freemud.sdk.api.assortment.order.enums.*;
import com.freemud.sdk.api.assortment.order.request.order.*;
import com.freemud.sdk.api.assortment.order.request.payment.CombPayRequest;
import com.freemud.sdk.api.assortment.order.request.payment.MultiPayRequest;
import com.freemud.sdk.api.assortment.order.request.payment.PayPlatformVO;
import com.freemud.sdk.api.assortment.order.request.payment.ProductVO;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrderByIdResponse;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.awt.geom.Point2D;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.freemud.constant.OrderRefundConstant.ALLOW_REFUND;


@Component
public class OrderAdapter {


    private static Gson gson = new Gson();
    private static FastDateFormat yyyyMMddHHmmss = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    public static final String PAY_CODE_10102 = "10102"; // svc储值卡支付，可用于判断订单是否用储值卡支付

    @Value("${mccafe.partner.id}")
    private String mcCafePartnerId;
    @Value("${mcCafe.refund.interval}")
    private String mccafeRefundInterval;
    @Value("${macafe.waimai.tag}")
    private String maCafeWaimaiTag;
    @Value("${macafe.pick.tag}")
    private String maCafePickTag;
    @Value("${mccafe.monthCard.goodsId}")
    private String mccafeMonthCardGoodsId;
    @Value("${mcCafe.withOrderBuy.cardId}")
    private String withOrderBuyCardId;
    @Value("${mccafe.universal.coupon.code}")
    private String withOrderBuyCouponCode;
    @Value("${pay.turnoff.refund}")
    private String payTurnoffRefund = "0";
    @Value("${pay.turnoff.refund.partnerId}")
    private String payTurnoffRefundPartnerId = "0";

    /**
     * coco商户
     */
    @Value("#{'${coco.partnerId}'.split(',')}")
    private List<String> cocoPartnerId;
    @Value("${saas.refund.notify.callback}")
    private String refundNotifyCallback;

    @Autowired
    private ShoppingCartAdapter shoppingCartAdapter;
    @Autowired
    private OrderCenterSdkAdapter orderCenterSdkAdapter;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AssortmentOpenPlatformPartnerConfigManager assortmentOpenPlatformPartnerConfigManager;

    /**
     * @param createOrderVo
     * @param shoppingCartGoodsDto
     * @return
     */
    public BaseCreateOrderRequest convent2CreateOrderDto(CreateOrderVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto,
                                                         StoreResponseDto storeResponseDto) {
        BaseCreateOrderRequest createOrderDto = getCreateOrderDto(createOrderVo);
        ArrayList<CreateOrderAccountRequest> orderAccountDtos = new ArrayList<>();
        long deliveryAmount = 0;
        long discountDeliveryAmount = 0;
        if (createOrderVo.getMenuType().equals(BusinessTypeEnum.SAAS_DELIVERY.getCode())) {
            deliveryAmount = shoppingCartGoodsDto.getDeliveryAmount() == null ? 9l : shoppingCartGoodsDto.getDeliveryAmount();
            discountDeliveryAmount = shoppingCartGoodsDto.getDeliveryAmount() == null ? 9l : shoppingCartGoodsDto.getDeliveryAmount();
            // 参加满减活动 || 有运费券
            boolean isUseFreightCoupon = false;
            List<ActivityDiscountsDto> activityDiscountsDtos = shoppingCartGoodsDto.getActivityDiscountsDtos();
            if (CollectionUtils.isNotEmpty(activityDiscountsDtos)) {
                ActivityDiscountsDto activityDiscountsDto = activityDiscountsDtos.stream().filter(a -> a.getActivityType() != null
                        && a.getActivityType().equals(ActivityTypeEnum.TYPE_34.getCode())).findFirst().orElse(null);
                if (activityDiscountsDto != null) {
                    isUseFreightCoupon = true;
                }
            }
            if ((shoppingCartGoodsDto.getIsDiscountDelivery() || isUseFreightCoupon)
                    && deliveryAmount > shoppingCartGoodsDto.getDiscountDeliveryAmount()) {
                discountDeliveryAmount = shoppingCartGoodsDto.getDiscountDeliveryAmount();
            }

        } else if (createOrderVo.getMenuType().equals(BusinessTypeEnum.SAAS_MALL.getCode())) {
            deliveryAmount = shoppingCartGoodsDto.getDeliveryAmount() == null ? 0 : shoppingCartGoodsDto.getDeliveryAmount();
            discountDeliveryAmount = shoppingCartGoodsDto.getDeliveryAmount() == null ? 0 : shoppingCartGoodsDto.getDeliveryAmount();
        }
        Long packageAmount = shoppingCartGoodsDto.getPackageAmount() == null ? 0L : shoppingCartGoodsDto.getPackageAmount();
        Long totalScore = shoppingCartGoodsDto.getTotalScore() == null ? 0L : shoppingCartGoodsDto.getTotalScore();
        createOrderDto.setTotalScore(totalScore);

        //商城实付无需加上配送费用和包装费
        if (createOrderVo.getMenuType().equals(BusinessTypeEnum.SAAS_MALL.getCode())) {
            createOrderDto.setAmount(shoppingCartGoodsDto.getTotalAmount());
        } else {
            createOrderDto.setAmount(shoppingCartGoodsDto.getTotalAmount() + discountDeliveryAmount + packageAmount);
        }
        // 解析购物车信息
        List<ShoppingCartGoodsDto.CartGoodsDetailDto> cartGoodsDetailDtos = shoppingCartGoodsDto.getProducts();
        List<ActivityDiscountsDto> activityDiscountsDtos = shoppingCartGoodsDto.getActivityDiscountsDtos();
        List<CreateOrderProductRequest> products = new ArrayList<>();

        //随单购商品
        if (null != shoppingCartGoodsDto.getPayCardFee() && 0l != shoppingCartGoodsDto.getPayCardFee() && StringUtils.isNotBlank(createOrderVo.getCardKeyCode())) {
            products.add(getMcCafeWithOrderVirtualProduct(shoppingCartGoodsDto, createOrderVo));
        }

        // 根据购物车商品信息获取优惠信息
        int orderAccountIndex = 0;
        for (ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto : cartGoodsDetailDtos) {
            Integer qty = cartGoodsDetailDto.getQty();
            if (qty > 0) {
                CreateOrderProductRequest createOrderProductDto = null;
                if (mcCafePartnerId.equals(createOrderDto.getCompanyId())) {
                    createOrderProductDto = convent2MCCafeOrderProduct(cartGoodsDetailDto);
                } else {
                    // fisherman --> 购物车的加料商品 加价购商品 套餐组合商品 都在这里进行转换
                    createOrderProductDto = convent2OrderProduct(cartGoodsDetailDto);
                }
                createOrderProductDto.setIgnoreProductPrice(1);
                products.add(createOrderProductDto);
                if (CollectionUtils.isNotEmpty(cartGoodsDetailDto.getActivityDiscountsDtos())) {
                    if (mcCafePartnerId.equals(createOrderDto.getCompanyId())) {
                        createOrderProductDto.setAccounts(getMCCafeAccounts(createOrderProductDto, cartGoodsDetailDto.getActivityDiscountsDtos()));
                    } else if (cocoPartnerId.contains(createOrderDto.getCompanyId())) {
                        createOrderProductDto.setAccounts(getCocoAccounts(createOrderProductDto, cartGoodsDetailDto.getActivityDiscountsDtos()));
                    } else {
                        createOrderProductDto.setAccounts(getAccounts(createOrderProductDto, cartGoodsDetailDto.getActivityDiscountsDtos()));
                    }
                }
            }
        }

        createOrderDto.setProducts(products);
        boolean hasDeliveryMonthCard = false;
        for (ActivityDiscountsDto activityDiscountsDto : activityDiscountsDtos) {
            // fisherman 3.0.34 运费券 这里塞进去的
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId(activityDiscountsDto.getActivityCode())
                    .name(activityDiscountsDto.getActivityName())
                    .price(activityDiscountsDto.getDiscountAmount().longValue())
                    .accountType(getQueryOrderAccountType(getOrderAccountType(activityDiscountsDto.getActivityType())))
                    .sequence(orderAccountIndex++)
                    .build();
            if (mcCafePartnerId.equals(createOrderDto.getCompanyId())) {
                //购买月享卡2.0并且不当单使用时，过滤掉无意义的0元优惠
                if(activityDiscountsDto.getDiscountAmount() == 0 && ActivityTypeEnum.TYPE_38.getCode().equals(activityDiscountsDto.getActivityType())
                        && activityDiscountsDto.getExtendType() == 12   //12=月享卡2.0
                        && (shoppingCartGoodsDto.getMonthCardDiscount() == null || shoppingCartGoodsDto.getMonthCardDiscount().getDiscountAmount() == 0)) {
                    continue;
                }
                JSONObject jsonObject = new JSONObject();
                if (ActivityTypeEnum.TYPE_11.getCode().equals(activityDiscountsDto.getActivityType())
                        || ActivityTypeEnum.TYPE_12.getCode().equals(activityDiscountsDto.getActivityType())
                        || ActivityTypeEnum.TYPE_32.getCode().equals(activityDiscountsDto.getActivityType())
                        || ActivityTypeEnum.TYPE_37.getCode().equals(activityDiscountsDto.getActivityType())
                        || ActivityTypeEnum.TYPE_38.getCode().equals(activityDiscountsDto.getActivityType())) {
                    jsonObject.put("tenderId", activityDiscountsDto.getTenderId());
                } else if (ActivityTypeEnum.TYPE_34.getCode().equals(activityDiscountsDto.getActivityType())) {
                    jsonObject.put("customerCode", activityDiscountsDto.getTenderId());
                    if (null != activityDiscountsDto.getExtendType() && activityDiscountsDto.getExtendType() == 2) {
                        hasDeliveryMonthCard = true;
                    }
                }
                if (null != activityDiscountsDto.getExtendType()) {
                    jsonObject.put("extendType", activityDiscountsDto.getExtendType());
                }
                createOrderAccountDto.setAddInfo(jsonObject.toJSONString());
            }
            orderAccountDtos.add(createOrderAccountDto);
        }

        if (deliveryAmount > 0) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId("")
                    .name("配送费")
                    .price(deliveryAmount)
                    .accountType(getQueryOrderAccountType(OldOrderAccountType.getByCode(OrderAccountType.DELIVERY_AMOUNT.getCode())))
                    .sequence(orderAccountIndex++)
                    .actualPrice(discountDeliveryAmount)
                    .build();
            if (hasDeliveryMonthCard && StringUtils.isNotBlank(storeResponseDto.getBenefitCardDiscountAmount())) {
                createOrderAccountDto.setNote(Double.valueOf(Double.valueOf(storeResponseDto.getBenefitCardDiscountAmount()) * 100).intValue() + "");
            }
            orderAccountDtos.add(createOrderAccountDto);
        }
        if (packageAmount > 0) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId("")
                    .name("包装费")
                    .price(packageAmount)
                    .accountType(getQueryOrderAccountType(OldOrderAccountType.getByCode(OrderAccountType.PACK_AMOUNT.getCode())))
                    .sequence(orderAccountIndex++)
                    .build();
            orderAccountDtos.add(createOrderAccountDto);
        }
        Long scoreReduceAmount = shoppingCartGoodsDto.getScoreReduceAmount() != null ? shoppingCartGoodsDto.getScoreReduceAmount() : 0;
        if (scoreReduceAmount > 0 && CustomerScoreConstant.SUBSTRACT.getValue().equals(createOrderVo.getUseCustomerScore())) {
//            Integer reduceScore = shoppingCartGoodsDto.getReduceScore() != null ? shoppingCartGoodsDto.getReduceScore().intValue() : 0;
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId("")
                    .name("积分扣减")
                    .price(0 - scoreReduceAmount)
                    .accountType(getQueryOrderAccountType(OldOrderAccountType.getByCode(OrderAccountType.CUSTOMER_SUB.getCode())))
                    .sequence(orderAccountIndex++)
                    .build();
            orderAccountDtos.add(createOrderAccountDto);
        }
        Long cardOriginalAmount = shoppingCartGoodsDto.getCardOriginalAmount() != null ? shoppingCartGoodsDto.getCardOriginalAmount() : 0L;
        if (cardOriginalAmount > 0) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId("")
                    .name("会员卡原价")
                    .price(cardOriginalAmount)
                    .accountType(getQueryOrderAccountType(OldOrderAccountType.getByCode(OrderAccountType.CARD_ORIGINAL_AMOUNT.getCode())))
                    .sequence(orderAccountIndex++)
                    .build();
            orderAccountDtos.add(createOrderAccountDto);
        }
        Long cardDiscountAmount = shoppingCartGoodsDto.getCardDiscountAmount() != null ? shoppingCartGoodsDto.getCardDiscountAmount() : 0L;
        if (cardDiscountAmount > 0) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId("")
                    .name("会员卡优惠金额")
                    .price(0 - cardDiscountAmount)
                    .accountType(getQueryOrderAccountType(OldOrderAccountType.getByCode(OrderAccountType.CARD_DISCOUNT_AMOUNT.getCode())))
                    .sequence(orderAccountIndex++)
                    .build();
            orderAccountDtos.add(createOrderAccountDto);
        }
        if (shoppingCartGoodsDto.getMonthCardDiscount() != null && shoppingCartGoodsDto.getMonthCardDiscount().getDiscountAmount() != 0) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId("")
                    .name(shoppingCartGoodsDto.getMonthCardDiscount().getDiscountDesc())
                    .price(shoppingCartGoodsDto.getMonthCardDiscount().getDiscountAmount())
                    .accountType(QueryOrderAccountType.MONTH_CARD_TOTAL_DISCOUNT)
                    .sequence(orderAccountIndex++)
                    .build();
            orderAccountDtos.add(createOrderAccountDto);
        }
        createOrderDto.setAccounts(CollectionUtils.isNotEmpty(orderAccountDtos) ? orderAccountDtos : Collections.emptyList());

        createOrderDto.setTotalDiscountAmount(shoppingCartGoodsDto.getTotalDiscountAmount());
        // update by miaohui 20201030 for 【ID1018638】【C端服务端】活动库存接口调整对接
        ActivityUpdateStockRequest activityUpdateStockRequest = this.initActivityUpdateStockRequest(activityDiscountsDtos);

        //设置库存扣减
        List<SubtractStockVO> stocks = this.getStocks(shoppingCartGoodsDto.getStocks());
        activityUpdateStockRequest.setStock(stocks);

        createOrderDto.setActivityUpdateStockRequest(activityUpdateStockRequest);
        createOrderDto.setPayChannelType(createOrderVo.getPayChannelType());

        // 买一赠一寄件信息
        if (createOrderVo.getChooseGoods() != null && !createOrderVo.getChooseGoods().isEmpty()) {
            createOrderDto.setChooseGoods(JSONArray.parseArray(JSONObject.toJSONString(createOrderVo.getChooseGoods()), BaseCreateOrderRequest.ChooseGood.class));
        }
        return createOrderDto;
    }

    private List<CreateOrderAccountRequest> getMaterialAccounts(CreateOrderProductRequest createOrderProductDto, ShoppingCartGoodsDto.CartGoodsDetailDto material) {
        List<CreateOrderAccountRequest> orderAccountDtos = createOrderProductDto.getAccounts();
        if (CollectionUtils.isEmpty(orderAccountDtos)) {
            orderAccountDtos = new ArrayList<>();
        }
        List<ActivityDiscountsDto> activityDiscountsDtos = material.getActivityDiscountsDtos();
        for (ActivityDiscountsDto activityDiscountsDto : activityDiscountsDtos) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId(activityDiscountsDto.getActivityCode())
                    .name(activityDiscountsDto.getActivityName())
                    .price(activityDiscountsDto.getDiscountAmount().longValue())
                    .accountType(getQueryOrderAccountType(getOrderAccountType(activityDiscountsDto.getActivityType())))
                    .sequence(createOrderProductDto.getSequence())
                    .productId(material.getSpuId())
                    .discountQty(createOrderProductDto.getNumber())
                    .build();
            orderAccountDtos.add(createOrderAccountDto);
        }
        return orderAccountDtos;

    }

    public List<CreateOrderAccountRequest> getAccounts(CreateOrderProductRequest createOrderProductDto, List<ActivityDiscountsDto> activityDiscountsDtos) {
        List<CreateOrderAccountRequest> orderAccountDtos = new ArrayList<>();
        for (ActivityDiscountsDto activityDiscountsDto : activityDiscountsDtos) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId(activityDiscountsDto.getActivityCode())
                    .name(activityDiscountsDto.getActivityName())
                    .price(activityDiscountsDto.getDiscountAmount().longValue())
                    .accountType(getQueryOrderAccountType(getOrderAccountType(activityDiscountsDto.getActivityType())))
                    .sequence(createOrderProductDto.getSequence())
                    .productId(createOrderProductDto.getSpecification())
                    .discountQty((activityDiscountsDto.getActualActivityGoodsNumber() == null || activityDiscountsDto.getActualActivityGoodsNumber() == 0)
                            ? createOrderProductDto.getNumber() : activityDiscountsDto.getActualActivityGoodsNumber())
                    .build();
            orderAccountDtos.add(createOrderAccountDto);
        }
        return orderAccountDtos;
    }

    public List<CreateOrderAccountRequest> getMCCafeAccounts(CreateOrderProductRequest createOrderProductDto, List<ActivityDiscountsDto> activityDiscountsDtos) {
        List<CreateOrderAccountRequest> orderAccountDtos = new ArrayList<>();
        for (ActivityDiscountsDto activityDiscountsDto : activityDiscountsDtos) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId(activityDiscountsDto.getActivityCode())
                    .name(activityDiscountsDto.getActivityName())
                    .price(activityDiscountsDto.getDiscountAmount().longValue())
                    .accountType(getQueryOrderAccountType(getOrderAccountType(activityDiscountsDto.getActivityType())))
                    .sequence(createOrderProductDto.getSequence())
                    .productId(createOrderProductDto.getSpecification())
                    .discountQty((activityDiscountsDto.getActualActivityGoodsNumber() == null || activityDiscountsDto.getActualActivityGoodsNumber() == 0)
                            ? createOrderProductDto.getNumber() : activityDiscountsDto.getActualActivityGoodsNumber())
                    .build();
            JSONObject jsonObject = new JSONObject();
            if (ActivityTypeEnum.TYPE_32.getCode().equals(activityDiscountsDto.getActivityType())
                    || ActivityTypeEnum.TYPE_35.getCode().equals(activityDiscountsDto.getActivityType())
                    || ActivityTypeEnum.TYPE_37.getCode().equals(activityDiscountsDto.getActivityType())
                    || ActivityTypeEnum.TYPE_38.getCode().equals(activityDiscountsDto.getActivityType())) {
                jsonObject.put("tenderId", activityDiscountsDto.getTenderId());
            }
            if (null != activityDiscountsDto.getExtendType()) {
                jsonObject.put("extendType", activityDiscountsDto.getExtendType());
            }
            createOrderAccountDto.setAddInfo(jsonObject.toJSONString());
            orderAccountDtos.add(createOrderAccountDto);
        }
        return orderAccountDtos;
    }

    public List<CreateOrderAccountRequest> getCocoAccounts(CreateOrderProductRequest createOrderProductDto, List<ActivityDiscountsDto> activityDiscountsDtos) {
        List<CreateOrderAccountRequest> orderAccountDtos = new ArrayList<>();
        for (ActivityDiscountsDto activityDiscountsDto : activityDiscountsDtos) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId(activityDiscountsDto.getActivityCode())
                    .name(activityDiscountsDto.getActivityName())
                    .price(activityDiscountsDto.getDiscountAmount().longValue())
                    .accountType(getQueryOrderAccountType(getOrderAccountType(activityDiscountsDto.getActivityType())))
                    .sequence(createOrderProductDto.getSequence())
                    .productId(createOrderProductDto.getSpecification())
                    .discountQty(activityDiscountsDto.getActualActivityGoodsNumber())
                    .build();
            orderAccountDtos.add(createOrderAccountDto);
        }
        return orderAccountDtos;
    }

    /**
     * 获取两个点的距离 单位米
     *
     * @param shopLng
     * @param shopLat
     * @param addressLng
     * @param addressLat
     * @return
     */
    public double getDistance(String shopLng, String shopLat, String addressLng, String addressLat) {
        if (StringUtils.isBlank(shopLng) || StringUtils.isBlank(shopLat) || StringUtils.isBlank(addressLng) || StringUtils.isBlank(addressLat)) {
            return 100000;
        }
        return WebUtil.calDistance(Double.valueOf(shopLng), Double.valueOf(shopLat), Double.valueOf(addressLng), Double.valueOf(addressLat));
    }

    /**
     * 判断收货地址是否在配送范围
     *
     * @param storeDeliveryInfoDto 门店配送信息
     * @param userLongitude        用户经度
     * @param userLatitude         用户维度
     * @return
     */
    public boolean checkUserEnableDelivery(StoreDeliveryInfoDto storeDeliveryInfoDto, String userLongitude, String userLatitude) {
        if (!storeDeliveryInfoDto.getEnableTakeaway()) {
            return false;
        }
        //兼容老版本 为空设置默认按自定义配送
        if (storeDeliveryInfoDto.getScopeConfig() == null) {
            storeDeliveryInfoDto.setScopeConfig(ScopeConfigType.DEFINITION.getCode());
        }
        if (ScopeConfigType.getByCode(storeDeliveryInfoDto.getScopeConfig()) == null) {
            return false;
        }
        ScopeConfigType scopeConfigType = ScopeConfigType.getByCode(storeDeliveryInfoDto.getScopeConfig());
        if (ScopeConfigType.RADIUS.equals(scopeConfigType)) {
            if (storeDeliveryInfoDto.getDeliveryRadius() == null || storeDeliveryInfoDto.getDeliveryRadius() <= 0) {
                return false;
            }
            //用户收货地址距离门店距离 单位米
            double distance = getDistance(storeDeliveryInfoDto.getLongitude(), storeDeliveryInfoDto.getLatitude(),
                    userLongitude, userLatitude);
            if (distance > storeDeliveryInfoDto.getDeliveryRadius().doubleValue()) {
                return false;
            }
            return true;
        }
        List<Point2D.Double> points = storeDeliveryInfoDto.getPoint2DList();
        if (CollectionUtils.isEmpty(points)) {
            return false;
        }
        Point2D.Double point2D = new Point2D.Double(Double.parseDouble(userLongitude), Double.parseDouble(userLatitude));
        return WebUtil.IsPtInPoly(point2D, points);
    }

    /**
     * 通过CreateOrderVo 创建 CreateOrderDto
     *
     * @param createOrderVo
     * @return
     */
    public BaseCreateOrderRequest getCreateOrderDto(CreateOrderVo createOrderVo) {
        UserDeliveryInfoDto userDeliveryInfoDto = createOrderVo.getUserDeliveryInfoDto();
        String deliveryType = userDeliveryInfoDto != null && userDeliveryInfoDto.getStoreDeliveryInfoDto() != null
                ? userDeliveryInfoDto.getStoreDeliveryInfoDto().getDeliveryType() : "";
//        createOrderVo.setUserDeliveryInfoDto(userDeliveryInfoDto);
//        Integer orderType;
        OrderType newOrderType = null;
        String receiveAddress = createOrderVo.getStoreAddress();
        // fisherman -> 爱马哥 orderType落库的类型处理
        if (Objects.equals(createOrderVo.getOrderType(), CreateOrderType.TAKE_OUT.getCode())) {
//            orderType = OrderTypeV1.TAKE_OUT.getCode();
            newOrderType = getNewOrderType(OrderTypeV1.TAKE_OUT,createOrderVo.getExpectTime(),createOrderVo.getBizType());
            receiveAddress = (userDeliveryInfoDto != null ? userDeliveryInfoDto.getReceiveOfficeName() + "," + userDeliveryInfoDto.getReceiveAddress() : "");
        } else if (Objects.equals(createOrderVo.getOrderType(), CreateOrderType.COLLECT_GOODS.getCode())) {
            if (Objects.equals(createOrderVo.getReachStoreType(), OrderTypeV1.EAT_IN.getCode())) {
//                orderType = OrderTypeV1.EAT_IN.getCode();
                newOrderType = getNewOrderType(OrderTypeV1.EAT_IN,createOrderVo.getExpectTime(),createOrderVo.getBizType());
            } else {
                newOrderType = getNewOrderType(OrderTypeV1.COLLECT_GOODS,createOrderVo.getExpectTime(),createOrderVo.getBizType());
//                orderType = OrderTypeV1.COLLECT_GOODS.getCode();
            }
        } else if (Objects.equals(createOrderVo.getOrderType(), CreateOrderType.SAASMALL.getCode())) {
//            orderType = OrderTypeV1.EAT_IN.getCode();
            newOrderType = OrderType.GENERAL_DINE_IN;
            receiveAddress = (userDeliveryInfoDto != null ? userDeliveryInfoDto.getReceiveProvince() + userDeliveryInfoDto.getReceiveCity() + userDeliveryInfoDto.getReceiveRegion() + userDeliveryInfoDto.getReceiveAddress() : "");
            createOrderVo.setMobile(userDeliveryInfoDto != null ? userDeliveryInfoDto.getReceiveMobile() : "");
            createOrderVo.setContactsName(userDeliveryInfoDto != null ? userDeliveryInfoDto.getReceiveUserName() : "");
        } else {
            throw new ServiceException(ResponseResult.PARAMETER_MISSING, "非法的订单类型");
        }

        String latitude = userDeliveryInfoDto != null ? userDeliveryInfoDto.getUserLatitude() : "";
        String longitude = userDeliveryInfoDto != null ? userDeliveryInfoDto.getUserLongitude() : "";
        String remark = StringUtils.isNotBlank(createOrderVo.getOrderRemark()) ? createOrderVo.getOrderRemark() : "";
        BaseCreateOrderRequest createOrderDto = new BaseCreateOrderRequest();
        createOrderDto.setCompanyId(createOrderVo.getPartnerId());
        createOrderDto.setShopId(createOrderVo.getShopId());
        createOrderDto.setThirdShopId(createOrderVo.getThirdShopId());
        createOrderDto.setShopName(createOrderVo.getStoreName());
        createOrderDto.setShopNameEn(createOrderVo.getStoreNameEn());
        createOrderDto.setUserId(createOrderVo.getUserId());
        createOrderDto.setUserName(createOrderVo.getUserName());
        createOrderDto.setContactsName(createOrderVo.getContactsName());
        createOrderDto.setPhone(createOrderVo.getMobile());
        createOrderDto.setAddress(receiveAddress);
        createOrderDto.setLatitude(latitude);
        createOrderDto.setLongitude(longitude);
//        createOrderDto.setOrderType(convent2OrderTypeEnum(orderType));
        createOrderDto.setNewOrderType(newOrderType);
        createOrderDto.setPayType(QueryPayType.ONLINE_PAY);
        //  爱马哥蛋糕预定 预定单需求, bizType= 7  其他的场景默认传递null(到基础服务默认设置为1)
        createOrderDto.setBizType(createOrderVo.getBizType());
        //电子风味卡
        if (Objects.nonNull(createOrderVo.getUnionPayCard())) {
            createOrderDto.setPayChannel(PayChannelType.USVCP.getEbcode());
            createOrderDto.setPayChannelName(PayChannelType.USVCP.getName());
            createOrderDto.setPayChannelType(PayChannelType.USVCP.getIndex());
        }
        if (StringUtils.isNotBlank(createOrderVo.getChannel())) {
            PayChannelType channelType = PayChannelType.getByIndex(Byte.parseByte(createOrderVo.getChannel()));
            if (channelType != null) {
                createOrderDto.setPayChannel(channelType.getEbcode());
                createOrderDto.setPayChannelName(channelType.getName());
                createOrderDto.setPayChannelType(channelType.getIndex());
            }
        }
        createOrderDto.setRemark(remark);
        createOrderDto.setReceiveId(createOrderVo.getReceiveId());
        createOrderDto.setGmtExpect(StringUtils.isNotBlank(createOrderVo.getExpectTime()) ? DateUtil.convert2Date(createOrderVo.getExpectTime(), "yyyy-MM-dd HH:mm:ss").getTime() : null);
//        BaseCreateOrderRequest.DeliveryTypeInfo deliveryTypeInfo = new BaseCreateOrderRequest.DeliveryTypeInfo();
//        deliveryTypeInfo.setDeliveryType(QueryDeliveryType.getByCode(deliveryType));
//        createOrderDto.setAddInfo(deliveryTypeInfo);
        createOrderDto.setDeliveryType(StoreDeliveryMethod.getByCode(deliveryType));
        createOrderDto.setAmount(0L);
        createOrderDto.setBarCounter(createOrderVo.getTableNumber());
        createOrderDto.setOperator(createOrderVo.getUserName());
        createOrderDto.setMenuType(BusinessTypeEnum.getByCode(createOrderVo.getMenuType()));
        createOrderDto.setMarketingType(createOrderVo.getMarketingType());
        // 【ID1030916】订单查询门店获取预计送达时间
        createOrderDto.setEstimateDeliveryCompleteTime(createOrderVo.getUserDeliveryInfoDto() == null ? null : createOrderVo.getUserDeliveryInfoDto().getEstimateDeliveryCompleteTime());
        return createOrderDto;
    }

    /**
     * 提取公共方法
     * @param shoppingCartStocks
     * @return
     */
    private List<SubtractStockVO> getStocks(List<SubtractStockVO> shoppingCartStocks){
        List<SubtractStockVO> stocks = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(shoppingCartStocks)) {
            for (SubtractStockVO stockVO : shoppingCartStocks) {
                SubtractStockVO stockBeanDto = new SubtractStockVO();
                stockBeanDto.setActivityCode(stockVO.getActivityCode());
                stockBeanDto.setActivityStock(stockVO.getActivityStock() == null ? 1 : stockVO.getActivityStock());
                if (CollectionUtils.isNotEmpty(stockVO.getGoodsStock())) {
                    List<SubtractStockGoodsVO> goodsStockDTOS = new ArrayList<>();
                    stockVO.getGoodsStock().forEach(goods -> {
                        SubtractStockGoodsVO goodsStockDTO = new SubtractStockGoodsVO();
                        goodsStockDTO.setBenefitSeq(goods.getBenefitSeq());
                        goodsStockDTO.setGoodsId(goods.getGoodsId());
                        int stock = goods.getStock() == null ? 1 : goods.getStock();
                        goodsStockDTO.setStock(stock);
                        goodsStockDTOS.add(goodsStockDTO);
                    });
                    stockBeanDto.setGoodsStock(goodsStockDTOS);
                }
                // fisherman 用户限购库存-> 返回促销的值
                stockBeanDto.setUserGoodsStock(stockVO.getUserGoodsStock());
                stocks.add(stockBeanDto);
            }
        }
        return stocks;
    }

    public ConfirmOrderDto convent2ConfirmOrderDto(PaysuccessNoticeMessage message) {
        ConfirmOrderDto confirmOrderDto = new ConfirmOrderDto();
        confirmOrderDto.setOrderId(message.getTrans_id());
        confirmOrderDto.setPayVoucher(message.getOut_trade_no());
        confirmOrderDto.setPlatformCoupon(Double.valueOf(message.getPlatform_coupon()).intValue());
        confirmOrderDto.setMerchantCoupon(Double.valueOf(message.getMerchant_coupon()).intValue());
        confirmOrderDto.setOrderSettlementAmount(message.getTotal_fee());
        return confirmOrderDto;
    }

    public QueryOrdersRequest convent2QueryOrdersDto(QueryOrderDto queryOrderDto, String memberId, String channelType) {
        QueryOrdersRequest queryOrdersDto = new QueryOrdersRequest();
        queryOrdersDto.setUserId(memberId);
        queryOrdersDto.setCompanyId(queryOrderDto.getPartnerId());
        queryOrdersDto.setPageSize(queryOrderDto.getPageSize() != null ? queryOrderDto.getPageSize() : 10);
        queryOrdersDto.setPageNumber(queryOrderDto.getPageNumber() != null ? queryOrderDto.getPageNumber() : 1);
        queryOrdersDto.setStartDate(queryOrderDto.getStartDate());
        queryOrdersDto.setEndDate(queryOrderDto.getEndDate());
        queryOrdersDto.setUserId(memberId);
        List<Integer> orderClients = new ArrayList<>();
        List<Integer> bizTypes = new ArrayList<>();
        if (OrderChannelType.IWC.getCode().equals(channelType)) {
            //未定，暂无
        } else if (OrderChannelType.SAASMALL.getCode().equals(channelType)) {
            orderClients = Arrays.asList(OrderClientType.SAAS.getIndex(),OrderClientType.ALIPAY.getIndex());
            bizTypes.add(BizTypeEnum.MALL.getBizType());
            //新版查微商城订单marketingType　不传
            if(queryOrderDto.getMarketingType() == null || Objects.equals(1,queryOrderDto.getMarketingType())){
                queryOrdersDto.setMarketingType(MarketTypeEnum.ORDER.getIndex());
            }
            //微商城拼团
            if(Objects.equals(MarketTypeEnum.GROUPB.getIndex(),queryOrderDto.getMarketingType())){
                queryOrdersDto.setMarketingType(MarketTypeEnum.GROUPB.getIndex());
            }
        } else if (OrderChannelType.APP.getCode().equals(channelType)) {
            orderClients.add(OrderClientType.APP.getIndex());
            bizTypes = Arrays.asList(BizTypeEnum.ORDINARY.getBizType(), BizTypeEnum.SALE_COUPON.getBizType());
        } else if (OrderChannelType.CASHIER.getCode().equals(channelType)) {
            orderClients = Arrays.asList(OrderClientType.SAAS.getIndex(),OrderClientType.ALIPAY.getIndex());
            bizTypes.add(BizTypeEnum.ORDINARY.getBizType());
            queryOrdersDto.setMarketingType(MarketTypeEnum.CASHIER.getIndex());
        } else if (OrderChannelType.TIKTOK.getCode().equals(channelType)) {//抖音目前只有卖券,点餐业务已废弃
            orderClients = Arrays.asList(OrderClientType.TIKTOKPAY.getIndex());
            bizTypes.add(BizTypeEnum.SALE_COUPON.getBizType());
        } else {
            orderClients = Arrays.asList(OrderClientType.SAAS.getIndex(), OrderClientType.ALIPAY.getIndex(), OrderClientType.APP.getIndex(), OrderClientType.ASSISTANT.getIndex());
            bizTypes = Arrays.asList(BizTypeEnum.ORDINARY.getBizType(), BizTypeEnum.SALE_COUPON.getBizType(), BizTypeEnum.ADVANCE_ORDER.getBizType());
            queryOrdersDto.setMarketingTypes(Arrays.asList(MarketTypeEnum.ORDER.getIndex(), MarketTypeEnum.COLLAGE.getIndex(),
                    MarketTypeEnum.WE_CHAT_LIVE_SELL.getIndex(),MarketTypeEnum.CASHIER.getIndex(),MarketTypeEnum.TIKTOK_MARKET_ORDER.getIndex()));
        }
        List<Integer> payStatus = Arrays.asList(PayStatus.HAVE_PAID.getCode(), PayStatus.HAVE_REFUND.getCode(), PayStatus.COMPLETE.getCode());
        queryOrdersDto.setPayStatus((Integer[]) payStatus.toArray());
        //TODO 查询退款的待确定
        if (queryOrderDto.getQueryOrderStatus() != null) {
            if (QueryOrderStatus.ALL_BILL.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                queryOrdersDto.setStatus(OrderStatusV1.getAllCodes());

                if (Objects.equals(queryOrderDto.getMarketingType(), MarketTypeEnum.GROUPB.getIndex())) {
                    Integer[] statuses = new Integer[]{OrderStatusV1.TAKE_ORDER.getCode(), OrderStatusV1.WAIT_PAY.getCode(), OrderStatusV1.RECEIPT.getCode(),
                            OrderStatusV1.DISTRIBUTION.getCode(), OrderStatusV1.COMPLETE.getCode()};
                    queryOrdersDto.setStatus(statuses);
                }
            }
            if (QueryOrderStatus.TAKE_MEAL.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                Integer[] statuses = new Integer[]{OrderStatusV1.TAKE_ORDER.getCode(), OrderStatusV1.RECEIPT.getCode(),
                        OrderStatusV1.DISTRIBUTION.getCode(), OrderStatusV1.COMPLETE_MAKE.getCode()};
                queryOrdersDto.setStatus(statuses);
            }
            if (QueryOrderStatus.FINISH.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                queryOrdersDto.setStatus(new Integer[]{OrderStatusV1.COMPLETE.getCode()});
            }
            if (QueryOrderStatus.REFUND_BILL.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                Integer[] statuses = new Integer[]{RefundStatus.APPLY_REFUND.getCode(), RefundStatus.AGREE_REFUND.getCode(), RefundStatus.COMPLETE_REFUND.getCode()};
                queryOrdersDto.setRefundStatus(statuses);
            }
            if (QueryOrderStatus.NO_PAY.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                queryOrdersDto.setPayStatus(new Integer[]{PayStatus.NOT_PAY.getCode()});
            }
            if (QueryOrderStatus.ORDER_CANCEL.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                queryOrdersDto.setStatus(new Integer[]{OrderStatusV1.CANCEL.getCode()});
            }
            if (QueryOrderStatus.ORDER_CANCEL_MIXUE.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                queryOrdersDto.setStatus(new Integer[]{OrderStatusV1.CANCEL.getCode()});
                queryOrdersDto.setPayStatus(new Integer[]{PayStatus.NOT_PAY.getCode()});
            }

        }

        // 兼容历史版本，如果传参是4 查询拆程4和5
        if (queryOrderDto.getQueryOrderType() != null) {
            if (Objects.equals(queryOrderDto.getQueryOrderType(), OrderTypeV1.COLLECT_GOODS.getCode())) {
                queryOrdersDto.setType(new Integer[]{OrderTypeV1.COLLECT_GOODS.getCode(), OrderTypeV1.EAT_IN.getCode()});
            } else {
                queryOrdersDto.setType(new Integer[]{queryOrderDto.getQueryOrderType()});
            }
        }

        if (OrderChannelType.IWC.getCode().equals(channelType)) {
            Integer[] statuses = new Integer[]{OrderStatusV1.COMPLETE.getCode(), OrderStatusV1.CANCEL.getCode(), OrderStatusV1.WAIT_PAY.getCode()};
            queryOrdersDto.setStatus(statuses);
            Integer[] payWCStatus = new Integer[]{PayStatus.NOT_PAY.getCode(), PayStatus.HAVE_PAID.getCode(), PayStatus.HAVE_REFUND.getCode(), PayStatus.COMPLETE.getCode()};
            queryOrdersDto.setPayStatus(payWCStatus);
        }
//        List<Integer> bizTypes = Arrays.asList(BizTypeEnum.ORDINARY.getBizType(), BizTypeEnum.SALE_COUPON.getBizType(), BizTypeEnum.ADVANCE_ORDER.getBizType());
//        if (OrderChannelType.SAASMALL.getCode().equals(channelType)) {
//            Integer[] statuses = new Integer[]{OrderStatus.COMPLETE.getCode(), OrderStatus.CALCEL.getCode()};
//            queryOrdersDto.setStatus(statuses);
//            queryOrdersDto.setType(new Integer[]{});
//            bizTypes.add(BizTypeEnum.MALL.getBizType());
//        }
        //商品订单和卖券订单
        queryOrdersDto.setBizTypes(bizTypes);
        queryOrdersDto.setOrderClients(orderClients);

        return queryOrdersDto;
    }

    public QueryOrdersDto convent2QueryOrdersDtoMcCafe(McCafeQueryOrderVo queryOrderDto, String memberId, String channelType) {
        QueryOrdersDto queryOrdersDto = new QueryOrdersDto();
        queryOrdersDto.setUserId(memberId);
        queryOrdersDto.setCompanyId(queryOrderDto.getPartnerId());
        queryOrdersDto.setPageSize(queryOrderDto.getPageSize() != null ? queryOrderDto.getPageSize() : 10);
        queryOrdersDto.setPageNumber(queryOrderDto.getPageNumber() != null ? queryOrderDto.getPageNumber() : 1);
        queryOrdersDto.setStartDate(queryOrderDto.getStartDate());
        queryOrdersDto.setEndDate(queryOrderDto.getEndDate());

        if (OrderChannelType.IWC.getCode().equals(channelType)) {
            queryOrdersDto.setSource(new String[]{"meals"});
        } else if (OrderChannelType.SAASMALL.getCode().equals(channelType)) {
            queryOrdersDto.setSource(new String[]{"saasmall"});
        } else if (OrderChannelType.APP.getCode().equals(channelType)) {
            queryOrdersDto.setSource(new String[]{"app"});
        } else {
            queryOrdersDto.setSource(new String[]{"saas"});
        }

        List<Integer> payStatus = Arrays.asList(PayStatus.HAVE_PAID.getCode(), PayStatus.HAVE_REFUND.getCode(), PayStatus.COMPLETE.getCode());
        queryOrdersDto.setPayStatus((Integer[]) payStatus.toArray());
        if (CollectionUtils.isNotEmpty(queryOrderDto.getQueryOrderStatus())) {
            Set<Integer> setStatus = new HashSet<>();
            if (queryOrderDto.getQueryOrderStatus().contains(QueryOrderStatus.ALL_BILL.getCode())) {
                List<Integer> integers = Arrays.asList(OrderStatusV1.getAllCodes());
                setStatus.addAll(integers);
            }
            if (queryOrderDto.getQueryOrderStatus().contains(QueryOrderStatus.TAKE_MEAL.getCode())) {
                Integer[] statuses = new Integer[]{OrderStatusV1.TAKE_ORDER.getCode(), OrderStatusV1.RECEIPT.getCode(),
                        OrderStatusV1.DISTRIBUTION.getCode(), OrderStatusV1.COMPLETE_MAKE.getCode()};
                List<Integer> integers = Arrays.asList(statuses);
                setStatus.addAll(integers);
            }
            if (queryOrderDto.getQueryOrderStatus().contains(QueryOrderStatus.FINISH.getCode())) {
                setStatus.add(OrderStatusV1.COMPLETE.getCode());
            }
            if (queryOrderDto.getQueryOrderStatus().contains(QueryOrderStatus.REFUND_BILL.getCode())) {
                Integer[] statuses = new Integer[]{RefundStatus.APPLY_REFUND.getCode(), RefundStatus.AGREE_REFUND.getCode(), RefundStatus.COMPLETE_REFUND.getCode()};
                queryOrdersDto.setRefundStatus(statuses);
            }
            if (queryOrderDto.getQueryOrderStatus().contains(QueryOrderStatus.NO_PAY.getCode())) {
                queryOrdersDto.setPayStatus(new Integer[]{PayStatus.NOT_PAY.getCode()});
            }
            if (queryOrderDto.getQueryOrderStatus().contains(QueryOrderStatus.ORDER_CANCEL.getCode())) {
                setStatus.add(OrderStatusV1.CANCEL.getCode());
            }
            queryOrdersDto.setStatus(setStatus.toArray(new Integer[setStatus.size()]));
        }

        // 兼容历史版本，如果传参是4 查询拆程4和5
        if (CollectionUtils.isNotEmpty(queryOrderDto.getQueryOrderType())) {
            Set<Integer> set = new HashSet<>();
            if (queryOrderDto.getQueryOrderType().contains(OrderTypeV1.COLLECT_GOODS.getCode())) {
                set.add(OrderTypeV1.COLLECT_GOODS.getCode());
                set.add(OrderTypeV1.EAT_IN.getCode());
            }
            if (queryOrderDto.getQueryOrderType().contains(OrderTypeV1.TAKE_OUT.getCode())) {
                set.add(OrderTypeV1.TAKE_OUT.getCode());
            }
            queryOrdersDto.setType(set.toArray(new Integer[set.size()]));
        }

        //商品订单和卖券订单
        queryOrdersDto.setBizTypes(Arrays.asList(1, 6));

        return queryOrdersDto;
    }

    public List<QueryOrderResponseVo> convent2QueryOrderResponseVos(List<OrderBeanV1> ordersBeans, String wxAppId, String iAppId) {
        if (CollectionUtils.isEmpty(ordersBeans)) {
            return Collections.emptyList();
        }

        List<QueryOrderResponseVo> list = Lists.newArrayList();
        OrderBeanV1 orderBean = ordersBeans.get(0);
        String partnerId = "";
        if (null != orderBean) {
            partnerId = orderBean.getCompanyId();
        }
        String configStr = redisCache.hashGet(MessageFormat.format(OrderRedisKeyConstant.ORDER_COMPLAIN_KEY, partnerId, wxAppId), OrderRedisKeyConstant.HashKeyForOrderComplainConfig.ORDER_COMPLAIN_TYPE);
        Boolean buttonComplain = false;
        if (CommonsConstant.ORDER_COMPLAIN_OPEN.equals(configStr)) {
            buttonComplain = true;
        }
        for (OrderBeanV1 ordersBean : ordersBeans) {

            QueryOrderResponseVo responseVo = new QueryOrderResponseVo();
            responseVo.setOid(ordersBean.getOid());
            responseVo.setShopId(ordersBean.getShopId());
            responseVo.setShopName(ordersBean.getShopName());
            responseVo.setShopNameEn(ordersBean.getShopNameEn());
            responseVo.setShopAddress(ordersBean.getShopAddress());
            responseVo.setShopPhone(ordersBean.getShopPhone());
            responseVo.setButtonComplain(buttonComplain);
            responseVo.setReceiveAddress(ordersBean.getAddress());
            if (BizTypeEnum.MALL.getBizType() == ordersBean.getBizType()) {
                responseVo.setReceiveUsername(ordersBean.getContactsName());
            } else {
                responseVo.setReceiveUsername(ordersBean.getUserName());
            }

            responseVo.setReceiveProvince(ordersBean.getReceiveProvince());
            responseVo.setReceiveCity(ordersBean.getReceiveCity());
            responseVo.setReceiveRegion(ordersBean.getReceiveRegion());
            responseVo.setReceiveMobile(ordersBean.getPhone());
            if (ordersBean.getAddInfo() != null && StringUtils.isNotEmpty(ordersBean.getAddInfo().getRiderPhone()))
                responseVo.setRiderPhone(ordersBean.getAddInfo().getRiderPhone());
            if (ordersBean.getAddInfo() != null && StringUtils.isNotEmpty(ordersBean.getAddInfo().getExtInfo())) {
                JSONObject extInfo = JSONObject.parseObject(ordersBean.getAddInfo().getExtInfo());
                responseVo.setReceiveId(extInfo.getString("receiveId"));
            }
            responseVo.setTakeMealType(ordersBean.getGmtExpect() == null ? 0 : 1);
            responseVo.setTakeMealTypeDesc(responseVo.getTakeMealType() == 0 ? "立即取餐" : "预约取餐");
            String extInfo = ordersBean.getExtInfo();
            OrderExtInfoDto orderExtInfoDto = null;
            if (StringUtils.isNotBlank(extInfo)) {
                orderExtInfoDto = gson.fromJson(extInfo, OrderExtInfoDto.class);
                responseVo.setTotalScore(orderExtInfoDto.getTotalScore());
            }
            responseVo.setWxappid(orderExtInfoDto != null ? orderExtInfoDto.getAppid() : "");
            responseVo.setReserveDeliveryTime("");
            if (ordersBean.getGmtExpect() != null) {
                Date gmtExpect = new Date(ordersBean.getGmtExpect());
                responseVo.setTakeMealTime(DateUtil.convert2String(gmtExpect, "yyyy-MM-dd HH:mm:ss"));
                responseVo.setReserveDeliveryTime(responseVo.getTakeMealTime());
            } else {
                //如果是尽快送出，如果有外卖时间，下单时间<外卖开始时间，外卖预约=外卖开始时间+预计送达时间，
                // 如果下单时间>=外卖开始时间,外卖预约=下单时间+预计送达时间，
                if (OrderTypeV1.TAKE_OUT.getCode() == ordersBean.getOrderType().intValue()) {
                    responseVo.setTakeMealTime("尽快送出");
                } else {
                    responseVo.setTakeMealTime("我已到店");
                }
                if (ordersBean.getEstimateDeliveryCompleteTime() != null) {
                    responseVo.setReserveDeliveryTime(DateUtil.convert2String(new Date(ordersBean.getEstimateDeliveryCompleteTime()), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
                } else {
                    // 更新该字段 用于 预计送达时间
                    if (orderExtInfoDto != null && StringUtils.isNotBlank(orderExtInfoDto.getDeliveryHoursDayStart())

                            && StringUtils.isNotBlank(orderExtInfoDto.getPayDate())) {
                        Date createTime = new Date(ordersBean.getGmtCreate());
                        Date deliveryHoursDayStart = DateUtil.convert2Date(orderExtInfoDto.getDeliveryHoursDayStart(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
                        Integer serviceTime = orderExtInfoDto.getServiceTime();
                        if (serviceTime == null) {
                            serviceTime = 50;
                        }
                        if (createTime.before(deliveryHoursDayStart)) {
                            responseVo.setReserveDeliveryTime(DateUtil.convert2String(DateUtil.addMinutes(deliveryHoursDayStart, serviceTime), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
                        } else {
                            responseVo.setReserveDeliveryTime(DateUtil.convert2String(DateUtil.addMinutes(createTime, serviceTime), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
                        }
                    }
                }
            }
            responseVo.setOrderCreateTime(yyyyMMddHHmmss.format(new Date(ordersBean.getGmtCreate())));

            //到店的用餐方式有：打包带走、店内就餐 ,外卖没有用餐方式
            if (OrderTypeV1.COLLECT_GOODS.getCode().equals(ordersBean.getOrderType())) {
                responseVo.setTakeOut(1);
                responseVo.setTakeOutDesc("打包带走");
            } else if (OrderTypeV1.EAT_IN.getCode().equals(ordersBean.getOrderType())) {
                responseVo.setTakeOut(0);
                responseVo.setTakeOutDesc("店内就餐");
            } else {
                responseVo.setTakeOut(0);
                responseVo.setTakeOutDesc("");
            }
            //配置麦咖啡文案
            if (OrderTypeV1.TAKE_OUT.getCode().equals(ordersBean.getOrderType())) {
                responseVo.setMcCafeOrderTag(maCafeWaimaiTag);
            } else {
                responseVo.setMcCafeOrderTag(maCafePickTag);
            }
            responseVo.setTableNumber(ordersBean.getBarCounter());
            // fisherman 支付状态描述
            responseVo.setPayStatus(ordersBean.getPayStatus());
            responseVo.setPayStatusDesc(Optional.ofNullable(PayStatus.getByCode(ordersBean.getPayStatus()))
                    .map(PayStatus::getDesc).orElse(""));
            responseVo.setPayStatusDescEn(Optional.ofNullable(PayStatus.getByCode(ordersBean.getPayStatus()))
                    .map(PayStatus::getDescEn).orElse(""));

            responseVo.setPayVoucher(orderExtInfoDto != null ? orderExtInfoDto.getPayTransId() : "");
            if (mcCafePartnerId.equals(ordersBean.getCompanyId()) && StringUtils.isNotBlank(responseVo.getPayVoucher())) {
                responseVo.setPayVoucherBarCode(Base64.getEncoder().encodeToString(
                        BarcodeUtil.generateBarCode128(responseVo.getPayVoucher(), null, null, true, true)));
            }
            responseVo.setPayCreateTime(orderExtInfoDto != null ? orderExtInfoDto.getPayDate() : "");
            responseVo.setPayChannel(ordersBean.getPayChannel());
            if (StringUtils.isNotBlank(ordersBean.getPayChannelType())) {
                PayChannelType ebcode = PayChannelType.getByIndex(Byte.parseByte(ordersBean.getPayChannelType()));
                if (ebcode != null) {
                    responseVo.setOrderPayType(ebcode.getName());
                    responseVo.setOrderPayTypeDescEn(ebcode.getNameEn());
                } else {
                    responseVo.setOrderPayType(PayChannelType.WECHAT.getName());
                    responseVo.setOrderPayTypeDescEn(PayChannelType.WECHAT.getNameEn());
                }
            } else if (ordersBean.getOrderPayItem() != null && ordersBean.getOrderPayItem().size() > 0) {
                responseVo.setOrderPayType(PayChannelType.COMB.getName());
                responseVo.setOrderPayTypeDescEn(PayChannelType.COMB.getNameEn());
            } else {
                if (OrderClientType.ALIPAY.getIndex().toString().equals(ordersBean.getOrderClient())) {
                    responseVo.setOrderPayType("支付宝支付");
                    responseVo.setOrderPayTypeDescEn(PayChannelType.ALIPAY.getNameEn());
                } else {
                    responseVo.setOrderPayType("微信支付");
                    responseVo.setOrderPayTypeDescEn(PayChannelType.WECHAT.getNameEn());
                }
            }

            //取餐码用日订单序号代替- v1.5.4变更为四位随机数
            responseVo.setTakeCode(ordersBean.getOtherCode());
            responseVo.setAmount(ordersBean.getAmount());
            responseVo.setActualPayAmount(ordersBean.getActualPayAmount());
            OrderViewStatusDto orderViewStatusDto = getOrderViewStatusDesc(ordersBean, wxAppId);
            //围餐需求  订单中存在未称重的商品称重商品则金额为0
            if (IappIdType.WC_XCX.getCode().equals(iAppId)) {
                if (!this.queryExistWeightNoNum(ordersBean)) {
                    responseVo.setAmount(0L);
                }
            }
            responseVo.setOrderStatus(orderViewStatusDto.getOrderStatus());
            // 放入订单流转时间
            ArrayList<QueryOrderResponseVo.OrderStatusFlow> orderChangeTime = getOrderTimeDesc(ordersBean);
            responseVo.setOrderStatusFlows(orderChangeTime);
            responseVo.setOrderStatusDesc(orderViewStatusDto.getOrderStatusDesc());
            responseVo.setOrderStatusDescEn(orderViewStatusDto.getOrderStatusDescEn());
            responseVo.setOrderStatusDescText(orderViewStatusDto.getOrderStatusDescText());
            if (CollectionUtils.isNotEmpty(ordersBean.getRefundList())) {
                responseVo.setRefundTips(orderViewStatusDto.getRefundStatusText());
            }
            if (OrderStatusV1.COMPLETE.getV2Code().equals(ordersBean.getStatusV2()) && null != ordersBean.getGmtCompleteTime() && 0l != ordersBean.getGmtCompleteTime()) {
                responseVo.setCompleteTime(DateUtil.convert2String(new Date(ordersBean.getGmtCompleteTime()), "yyyy-MM-dd HH:mm:ss"));
            }
            responseVo.setTakeMealFlows(getTakeMealFlows(ordersBean));
            responseVo.setRiderName(orderViewStatusDto.getRiderName());
            responseVo.setRiderText(orderViewStatusDto.getRiderText());
            responseVo.setRiderPhoto(StringUtils.isBlank(orderViewStatusDto.getRiderPhoto()) ? "" : orderViewStatusDto.getRiderPhoto()
                    + "?imageView2/1/w/80/h/80/interlace/1/q/100");
            responseVo.setShopImageUrl(ordersBean.getShopImageUrl() + "?imageView2/1/w/80/h/80/interlace/1/q/100");
            responseVo.setLongitude(ordersBean.getLongitude() != null ? ordersBean.getLongitude().toString() : "");
            responseVo.setLatitude(ordersBean.getLatitude() != null ? ordersBean.getLatitude().toString() : "");
            responseVo.setHasThirdDelivery(false);
            // 当取餐码不为空且门店自提且付款时，提供二维码图片
            if (StringUtils.isNotEmpty(responseVo.getTakeCode())
                    && (Objects.equals(responseVo.getOrderType(), OrderTypeV1.COLLECT_GOODS.getCode()) || Objects.equals(responseVo.getOrderType(), OrderTypeV1.EAT_IN.getCode()))
                    && !Objects.equals(responseVo.getOrderStatus(), OrderStatusV1.CANCEL.getCode())) {
                String oidBase64Image = null;
                try {
                    oidBase64Image = QrCodeUtil.createQrCode(responseVo.getOid(), 200, "PNG");
                } catch (Exception ignore) {

                }
                responseVo.setOidBase64Image(oidBase64Image);
            }
            //设置是否是第三方配送单
            if (ordersBean.getAddInfo() != null && StringUtils.isNotEmpty(ordersBean.getAddInfo().getDeliveryId()) && !"0".equals(ordersBean.getAddInfo().getDeliveryId())) {
                responseVo.setHasThirdDelivery(true);
                responseVo.setDeliveryId(ordersBean.getAddInfo().getDeliveryId());
            }
            responseVo.setDeliveryStatus(ordersBean.getDeliverStatus());
            responseVo.setQueueIndex(ordersBean.getQueueIndex());
            responseVo.setButtonRefund(orderViewStatusDto.getButtonRefund());
            responseVo.setButtonContactPartner(orderViewStatusDto.getButtonContactPartner());
            responseVo.setButtonContactRider(orderViewStatusDto.getButtonContactRider());
            responseVo.setButtonEvaluate(orderViewStatusDto.getButtonEvaluate());
            responseVo.setButtonMealCode(orderViewStatusDto.getButtonMealCode());
            responseVo.setOrderType(ordersBean.getOrderType());
            if (IappIdType.WC_XCX.getCode().equals(iAppId)) {
                responseVo.setOrderTypeDesc("围餐");
                responseVo.setOrderTypeDescEn("Round the table");
            } else if (BizTypeEnum.MALL.getBizType() == ordersBean.getBizType()) {
                responseVo.setOrderTypeDesc("商城订单");
            } else {
                // TODO: 21-11-25  OrderTypeGather 待合并
                responseVo.setOrderTypeDesc(Optional.ofNullable(OrderTypeV1.getByCode(ordersBean.getOrderType())).map(OrderTypeV1::getDesc).orElse(""));
            }
            responseVo.setOrderRemark(ordersBean.getRemark());
            if (ordersBean.getGmtModified() != null) {
                responseVo.setModifiedTime(DateUtil.convert2String(new Date(ordersBean.getGmtModified()), "yyyy-MM-dd HH:mm:ss"));
            }
            if (ordersBean.getHasRefund() != null && ordersBean.getHasRefund() && CollectionUtils.isNotEmpty(ordersBean.getRefundList())) {
                if (mcCafePartnerId.equals(ordersBean.getCompanyId())) {
                    RefundBeanV1 latestRefundBean = ordersBean.getRefundList().get(0);
                    for (int i = 0; i < ordersBean.getRefundList().size(); i++) {
                        RefundBeanV1 refundBean = ordersBean.getRefundList().get(i);
                        if (RefundStatus.COMPLETE_REFUND.getCode().equals(refundBean.getStatus())
                                || RefundStatus.APPLY_REFUND.getCode().equals(refundBean.getStatus())) {
                            responseVo.setRid(refundBean.getRid());
                            responseVo.setRefundStatus(refundBean.getStatus());
                            responseVo.setRefundStatusDesc(Optional.ofNullable(RefundStatus.getByCode(refundBean.getStatus()))
                                    .map(RefundStatus::getDesc).orElse(""));
                            responseVo.setRefundReason(refundBean.getReason());
                            String refundCreateTime = DateUtil.convert2String(new Date(Long.parseLong(refundBean.getCreateTime())), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
                            responseVo.setRefundCreateTime(refundCreateTime);
                            break;
                        } else {
                            if (new Date(Long.valueOf(refundBean.getCreateTime())).after(new Date(Long.valueOf(latestRefundBean.getCreateTime())))) {
                                latestRefundBean = refundBean;
                            }
                        }
                    }

                    if (StringUtils.isBlank(responseVo.getRid())) {
                        if (new Date().getTime() - Long.parseLong(latestRefundBean.getCreateTime()) > Long.valueOf(mccafeRefundInterval)) {
                            responseVo.setAfterRefundInterval(true);
                        }
                        responseVo.setRefundIntervalTime(Long.valueOf(latestRefundBean.getCreateTime()) + Long.valueOf(mccafeRefundInterval));
                    }

                } else {
                    RefundBeanV1 refundBean = ordersBean.getRefundList().get(0);
                    responseVo.setRid(refundBean.getRid());
                    responseVo.setRefundStatus(refundBean.getStatus());
                    responseVo.setRefundStatusDescEn(Optional.ofNullable(RefundStatus.getByCode(refundBean.getStatus()))
                            .map(RefundStatus::getDescEn).orElse(""));
                    responseVo.setRefundStatusDesc(getRefundStatusDesc(refundBean, ordersBean));
                    responseVo.setRefundReason(refundBean.getReason());
                    String refundCreateTime = DateUtil.convert2String(new Date(Long.parseLong(refundBean.getCreateTime())), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
                    responseVo.setRefundCreateTime(refundCreateTime);
                }
            } else {
                responseVo.setAfterRefundInterval(true);
            }
            //如果是已取消、拒单、已完成的订单，则设置不能申请取消订单
            if (OrderStatusV1.CANCEL.getV2Code().equals(ordersBean.getStatusV2())
                    || OrderStatusV1.COMPLETE.getV2Code().equals(ordersBean.getStatusV2())) {
                responseVo.setAfterRefundInterval(false);
            }
            //商品信息转换
            convent2ProductVos(ordersBean.getProductList(), responseVo, ordersBean.getCompanyId());
            responseVo.setOrderAccounts(convent2OrderAccountVo(ordersBean.getApportionDetails()));
            Long promotionAmount = 0L;
            Long deliveryAmount = 0L;
            Long packageAmount = 0L;
            Long originalDeliveryAmount = 0L;
            //限时特价优惠金额
            Long discountLimitAmount = 0L;
            Long couponAmount = 0L;
            //满减总优惠金额
            Long fullDiscountAmount = 0L;
            Long discountTotalAmount = 0L;
            //积分抵扣金额
            Long customerScoreAmount = 0L;
            String customerScorePrompt = null;
            List<CouponInfoVo> couponInfos = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(ordersBean.getAccountList())) {
                // fisherman 组装一单多券 使用的券信息
                for (AccountBeanV1 accountBean : ordersBean.getAccountList()) {
                    if (accountBean.getPrice() < 0 && !OldOrderAccountType.MONTH_CARD_TOTAL_DISCOUNT.getCode().equals(accountBean.getType())) {
                        discountTotalAmount = discountTotalAmount + (0 - accountBean.getPrice());
                    }
                    if (OrderAccountType.BUY_DISCOUNT.getCode().equals(accountBean.getType())) {
                        PromotionMessageDto promotionMessageDto = new PromotionMessageDto();
                        promotionMessageDto.setActivityId(accountBean.getAccountId());
                        promotionMessageDto.setActivityName(accountBean.getName());
                        promotionMessageDto.setPromotionAmount(accountBean.getPrice() < 0 ? 0 - accountBean.getPrice() : accountBean.getPrice());
                        promotionAmount = promotionMessageDto.getPromotionAmount();
                        fullDiscountAmount = accountBean.getPrice() < 0 ? 0 - accountBean.getPrice() : accountBean.getPrice();
                        responseVo.setPromotionMessage(promotionMessageDto);
                    }
                    if (OrderAccountType.DELIVERY_AMOUNT.getCode().equals(accountBean.getType())) {
                        //deliveryAmount = accountBean.getPrice();
                        deliveryAmount = null != accountBean.getActualCostAmount() ? accountBean.getActualCostAmount() : accountBean.getPrice();
                        originalDeliveryAmount = accountBean.getPrice();
                    }
                    if (OrderAccountType.PACK_AMOUNT.getCode().equals(accountBean.getType())) {
                        packageAmount = accountBean.getPrice();
                    }
                    if (OrderAccountType.DISCOUNT_AMOUNT.getCode().equals(accountBean.getType())) {
                        discountLimitAmount = accountBean.getPrice() < 0 ? 0 - accountBean.getPrice() : accountBean.getPrice();
                    }
                    if (OrderAccountType.COUPON.getCode().equals(accountBean.getType())
                            || OrderAccountType.DISCOUNT_COUPON.getCode().equals(accountBean.getType())) {
                        CouponInfoVo couponInfoVo = new CouponInfoVo();
                        couponInfoVo.setCouponCode(accountBean.getAccountId());
                        couponInfoVo.setCouponName(accountBean.getName());
                        couponInfoVo.setCouponAmount(accountBean.getPrice() < 0 ? 0 - accountBean.getPrice() : accountBean.getPrice());
                        // fisherman  后续已维护到 couponinfos ,请停止维护 该字段
                        responseVo.setCouponInfo(couponInfoVo);
                        couponAmount = accountBean.getPrice() < 0 ? 0 - accountBean.getPrice() : accountBean.getPrice();
                    }
                    if (OrderAccountType.CUSTOMER_SUB.getCode().equals(accountBean.getType())) {
                        customerScoreAmount = accountBean.getPrice() < 0 ? 0 - accountBean.getPrice() : accountBean.getPrice();
                        DecimalFormat decimalFormat = new DecimalFormat("#.00");
                        customerScorePrompt = decimalFormat.format(customerScoreAmount / 100.0);
//                        customerScorePrompt = "积分抵扣-¥" + customerScoreAmountStr;
                    }
                    if (OldOrderAccountType.MONTH_CARD_TOTAL_DISCOUNT.getCode().equals(accountBean.getType())) {
                        responseVo.setMonthCardTotalDiscount(accountBean.getPrice());
                        responseVo.setMonthCardTotalDiscountName(accountBean.getName());
                    }
                    if (OldOrderAccountType.FREIGHT_COUPON.getCode().equals(accountBean.getType())) {
                        responseVo.setFreightCouponName(accountBean.getName());
                    }
                    if (OrderAccountType.verificationCoupon.contains(accountBean.getType())) {
                        CouponInfoVo couponInfoVo = new CouponInfoVo();
                        couponInfoVo.setCouponCode(accountBean.getAccountId());
                        couponInfoVo.setCouponName(accountBean.getName());
                        couponInfoVo.setCouponAmount(Math.abs(accountBean.getPrice()));
                        couponInfos.add(couponInfoVo);
                    }
                }
            }
            responseVo.setCouponInfos(couponInfos);
            responseVo.setDeliveryAmount(deliveryAmount);
            responseVo.setOriginalDeliveryAmount(originalDeliveryAmount);
            responseVo.setPackageAmount(packageAmount);
            responseVo.setDiscountLimitAmount(discountLimitAmount);
            responseVo.setFullDiscountAmount(fullDiscountAmount);
            responseVo.setItemAmount(responseVo.getAmount() - deliveryAmount - packageAmount + promotionAmount + couponAmount);
            responseVo.setCustomerScoreAmount(customerScoreAmount);
            responseVo.setCustomerScorePrompt(customerScorePrompt);
            //优惠总金额=优惠券金额+满减金额+限时折扣金额
            responseVo.setDiscountTotalAmount(discountTotalAmount);
            responseVo.setDownstreamThirdOrderCode(ordersBean.getDownstreamThirdOrderCode());
            responseVo.setEnableRefund(false);
            if (OrderStatusV1.TAKE_ORDER.getV2Code().equals(ordersBean.getStatusV2()) && PayStatus.HAVE_PAID.getCode().equals(ordersBean.getPayStatus())) {
                responseVo.setEnableRefund(true);
            }
            responseVo.setBizType(ordersBean.getBizType());
            List<Integer> newEnableRefundCodes = Lists.newArrayList(Arrays.asList(
                    OrderStatusV1.RECEIPT.getV2Code(), OrderStatusV1.COMPLETE_MAKE.getV2Code()));
            if (newEnableRefundCodes.contains(ordersBean.getStatusV2()) && PayStatus.HAVE_PAID.getCode().equals(ordersBean.getPayStatus())) {
                responseVo.setEnableRefund(true);
            }
            responseVo.setMarketingType(ordersBean.getMarketingType());
            responseVo.setReturnWords(ordersBean.getReturnWords());
            responseVo.setProgress(ordersBean.getProgress());
            responseVo.setQueueIndex(ordersBean.getQueueIndex());
            responseVo.setOrderProgressBarStatus(ordersBean.getOrderProgressBarStatus());
            responseVo.setProgressBarStatus(ordersBean.getProgressBarStatus());
            responseVo.setPayTurnoffRefund(getPayTurnoffRefund());

            //拼团信息
            responseVo.setSpellGroupCode(ordersBean.getSpellGroupCode());
            if (null != ordersBean.getAfterSalesOrderResp()) {
                if (StringUtils.isNotEmpty(ordersBean.getAfterSalesOrderResp().getExtInfo())) {
                    AfterOrderExtInfoDto afterOrderExtInfoDto = JSONObject.parseObject(ordersBean.getAfterSalesOrderResp().getExtInfo(), AfterOrderExtInfoDto.class);
                    if (null != afterOrderExtInfoDto) {
                        responseVo.setRefundMode(afterOrderExtInfoDto.getRefundMode());
                    }
                }
            }
            //是否展示申请退款按钮 true 展示 false 不展示
            responseVo.setRefundButtonDisable(getRefundButtonDisable(ordersBean));
            responseVo.setOrderCompareAfterSaleOrder(getOrderCompareAfterSaleOrder(ordersBean));
            responseVo.setExpressChannelCode(ordersBean.getExpressChannelCode());
            responseVo.setExpressChannelName(ordersBean.getExpressChannelName());
            responseVo.setExpressNo(ordersBean.getExpressNo());
            responseVo.setAutoReviceTime(null == orderExtInfoDto ? null : orderExtInfoDto.getAutoReceiveTime());
            responseVo.setAfterSalesOrderResp(ordersBean.getAfterSalesOrderResp());

            // bizType = 7 预定单的 额外信息返回
            OrderExtendedReq orderExtended = ordersBean.getOrderExtended();
            if (Objects.nonNull(orderExtended)) {
                responseVo.setUserPhone(orderExtended.getUserPhone());
                responseVo.setSendWord(orderExtended.getSendWord());
            }
            //是否已开发票
            responseVo.setNeedInvoice(orderBean.getNeedInvoice());
            list.add(responseVo);
        }

        return list;
    }

    private ArrayList<QueryOrderResponseVo.OrderStatusFlow> getOrderTimeDesc(OrderBeanV1 ordersBean) {
        ArrayList<QueryOrderResponseVo.OrderStatusFlow> orderStatusFlows = new ArrayList<>();
        if (ordersBean.getOperateTakeOrderTime() != null) {
            QueryOrderResponseVo.OrderStatusFlow orderStatusFlow = new QueryOrderResponseVo.OrderStatusFlow();
            orderStatusFlow.setStatus("订单提交成功");
            orderStatusFlow.setOrderTime(dateStringFormatToString(ordersBean.getOperateTakeOrderTime()));
            orderStatusFlows.add(orderStatusFlow);
        }
        if (ordersBean.getOperateWaitPayTime() != null) {
            QueryOrderResponseVo.OrderStatusFlow orderStatusFlow = new QueryOrderResponseVo.OrderStatusFlow();
            orderStatusFlow.setStatus("订单已支付");
            orderStatusFlow.setOrderTime(dateStringFormatToString(ordersBean.getOperateWaitPayTime()));
            orderStatusFlows.add(orderStatusFlow);
        }
        if (ordersBean.getOperateReceiptTime() != null) {
            QueryOrderResponseVo.OrderStatusFlow orderStatusFlow = new QueryOrderResponseVo.OrderStatusFlow();
            orderStatusFlow.setStatus("商家已接单");
            orderStatusFlow.setOrderTime(dateStringFormatToString(ordersBean.getOperateReceiptTime()));
            orderStatusFlows.add(orderStatusFlow);
        }
        if (ordersBean.getOperateCompleteMakeTime() != null) {
            QueryOrderResponseVo.OrderStatusFlow orderStatusFlow = new QueryOrderResponseVo.OrderStatusFlow();
            orderStatusFlow.setStatus("商家制作完成");
            orderStatusFlow.setOrderTime(dateStringFormatToString(ordersBean.getOperateCompleteMakeTime()));
            orderStatusFlows.add(orderStatusFlow);
        }

        if (OrderTypeV1.TAKE_OUT.getCode().equals(ordersBean.getOrderType()) && ordersBean.getDeliverStatus() != null) {
            String depatchTime = ordersBean.getDepatchTime();
            if (StringUtils.isNotEmpty(depatchTime)) {
                QueryOrderResponseVo.OrderStatusFlow orderStatusFlow = new QueryOrderResponseVo.OrderStatusFlow();
                orderStatusFlow.setStatus("骑手已接单");
                orderStatusFlow.setOrderTime(dateStringFormatToString(depatchTime));
                orderStatusFlows.add(orderStatusFlow);
            }

            String arriveShopTime = ordersBean.getArriveShopTime();
            if (StringUtils.isNotEmpty(arriveShopTime)) {
                QueryOrderResponseVo.OrderStatusFlow orderStatusFlow = new QueryOrderResponseVo.OrderStatusFlow();
                orderStatusFlow.setStatus("骑手已到店");
                orderStatusFlow.setOrderTime(dateStringFormatToString(arriveShopTime));
                orderStatusFlows.add(orderStatusFlow);
            }

            String sendTime = ordersBean.getSendTime();
            if (StringUtils.isNotEmpty(sendTime)) {
                QueryOrderResponseVo.OrderStatusFlow orderStatusFlow = new QueryOrderResponseVo.OrderStatusFlow();
                orderStatusFlow.setStatus("骑手已送出");
                orderStatusFlow.setOrderTime(dateStringFormatToString(sendTime));
                orderStatusFlows.add(orderStatusFlow);
            }

            String completeTime = ordersBean.getCompleteTime();
            if (StringUtils.isNotEmpty(completeTime)) {
                QueryOrderResponseVo.OrderStatusFlow orderStatusFlow = new QueryOrderResponseVo.OrderStatusFlow();
                orderStatusFlow.setStatus("订单已完成");
                orderStatusFlow.setOrderTime(dateStringFormatToString(completeTime));
                orderStatusFlows.add(orderStatusFlow);
            }
        } else {
            if (ordersBean.getOperateDistributionTime() != null) {
                QueryOrderResponseVo.OrderStatusFlow orderStatusFlow = new QueryOrderResponseVo.OrderStatusFlow();
                orderStatusFlow.setStatus("配送中");
                orderStatusFlow.setOrderTime(dateStringFormatToString(ordersBean.getOperateDistributionTime()));
                orderStatusFlows.add(orderStatusFlow);
            }
            if (ordersBean.getOperateCompleteTime() != null) {
                QueryOrderResponseVo.OrderStatusFlow orderStatusFlow = new QueryOrderResponseVo.OrderStatusFlow();
                orderStatusFlow.setStatus("订单已完成");
                orderStatusFlow.setOrderTime(dateStringFormatToString(ordersBean.getOperateCompleteTime()));
                orderStatusFlows.add(orderStatusFlow);
            }
            if (ordersBean.getOperateCalcelTime() != null) {
                QueryOrderResponseVo.OrderStatusFlow orderStatusFlow = new QueryOrderResponseVo.OrderStatusFlow();
                orderStatusFlow.setStatus("订单已取消");
                orderStatusFlow.setOrderTime(dateStringFormatToString(ordersBean.getOperateCalcelTime()));
                orderStatusFlows.add(orderStatusFlow);
            }
            if (ordersBean.getOperatePefuseTime() != null) {
                QueryOrderResponseVo.OrderStatusFlow orderStatusFlow = new QueryOrderResponseVo.OrderStatusFlow();
                orderStatusFlow.setStatus("订单已取消");
                orderStatusFlow.setOrderTime(dateStringFormatToString(ordersBean.getOperatePefuseTime()));
                orderStatusFlows.add(orderStatusFlow);
            }
        }

        return orderStatusFlows;
    }

    /**
     * 格式化日期字符串，从yyyy-MM-dd HH:mm:ss -> MM-dd HH:mm
     */
    public String dateStringFormatToString(String date) {
        return date.substring(5, 16);
    }

    /**
     * 获取取餐页的订单流水
     *
     * @param orderBean
     * @return
     */
    private ArrayList<QueryOrderResponseVo.TakeMealFlow> getTakeMealFlows(OrderBeanV1 orderBean) {
        if (orderBean == null) {
            return new ArrayList<>();
        }
        ArrayList<QueryOrderResponseVo.TakeMealFlow> takeMealFlows = new ArrayList<>();
        if (OrderTypeV1.COLLECT_GOODS.getCode().equals(orderBean.getOrderType()) || OrderTypeV1.EAT_IN.getCode().equals(orderBean.getOrderType())) {
            takeMealFlows.add(QueryOrderResponseVo.TakeMealFlow.builder()
                    .name("已下单")
                    .active(false)
                    .icon("icon-order")
                    .build());
            takeMealFlows.add(QueryOrderResponseVo.TakeMealFlow.builder()
                    .name("制作中")
                    .active(false)
                    .icon("icon-Make")
                    .build());
            takeMealFlows.add(QueryOrderResponseVo.TakeMealFlow.builder()
                    .name("可取餐")
                    .active(false)
                    .icon("icon-service")
                    .build());
            if (OrderStatusV1.TAKE_ORDER.getV2Code().equals(orderBean.getStatusV2())) {
                takeMealFlows.get(0).setActive(true);
            }
            if (OrderStatusV1.RECEIPT.getV2Code().equals(orderBean.getStatusV2())) {
                takeMealFlows.get(1).setActive(true);
            }
            if (OrderStatusV1.COMPLETE_MAKE.getV2Code().equals(orderBean.getStatusV2())) {
                takeMealFlows.get(2).setActive(true);
            }
        }
        if (OrderTypeV1.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
            takeMealFlows.add(QueryOrderResponseVo.TakeMealFlow.builder()
                    .name("已下单")
                    .active(false)
                    .icon("icon-order")
                    .build());
            takeMealFlows.add(QueryOrderResponseVo.TakeMealFlow.builder()
                    .name("制作中")
                    .active(false)
                    .icon("icon-Make")
                    .build());
            takeMealFlows.add(QueryOrderResponseVo.TakeMealFlow.builder()
                    .name("配送中")
                    .active(false)
                    .icon("icon-Delivery")
                    .build());
            takeMealFlows.add(QueryOrderResponseVo.TakeMealFlow.builder()
                    .name("已送达")
                    .active(false)
                    .icon("icon-service")
                    .build());
            if (OrderStatusV1.TAKE_ORDER.getV2Code().equals(orderBean.getStatusV2())) {
                takeMealFlows.get(0).setActive(true);
            }
            if (OrderStatusV1.RECEIPT.getV2Code().equals(orderBean.getStatusV2())) {
                takeMealFlows.get(1).setActive(true);
            }
            if (OrderStatusV1.DISTRIBUTION.getV2Code().equals(orderBean.getStatusV2())) {
                takeMealFlows.get(2).setActive(true);
            }
            if (OrderStatusV1.COMPLETE.getV2Code().equals(orderBean.getStatusV2())) {
                takeMealFlows.get(3).setActive(true);
            }
        }
        return takeMealFlows;
    }


    public OrderViewStatusDto getOrderViewStatusDesc(OrderBeanV1 orderBean, String wxAppId) {
        OrderViewStatusDto orderViewStatusDto = new OrderViewStatusDto();
        RefundBeanV1 refundBean = null;
        if (CollectionUtils.isNotEmpty(orderBean.getRefundList())) {
            refundBean = orderBean.getRefundList().get(0);
        }
        orderViewStatusDto.setButtonRefund(false);
        orderViewStatusDto.setButtonContactPartner(false);
        orderViewStatusDto.setButtonContactRider(false);
        orderViewStatusDto.setButtonEvaluate(false);
        orderViewStatusDto.setButtonMealCode(false);
        orderViewStatusDto.setRiderName("");
        orderViewStatusDto.setRiderText("");
        orderViewStatusDto.setRiderPhoto("");
        /**本次订单状态中英文翻译不考虑美业的业务**/
        if (OrderTypeV1.COLLECT_GOODS.getCode().equals(orderBean.getOrderType()) || OrderTypeV1.EAT_IN.getCode().equals(orderBean.getOrderType())) {
            if (OrderStatusV1.WAIT_PAY.getV2Code().equals(orderBean.getStatusV2())) {
                orderViewStatusDto.setOrderStatus(OrderStatusV1.WAIT_PAY.getCode());
                orderViewStatusDto.setOrderStatusDesc(OrderStatusV1.WAIT_PAY.getDesc());
                orderViewStatusDto.setOrderStatusDescEn(OrderStatusV1.WAIT_PAY.getDescEn());
                orderViewStatusDto.setOrderStatusDescText("");
            }
            if (OrderStatusV1.CANCEL.getV2Code().equals(orderBean.getStatusV2())) {
                orderViewStatusDto.setOrderStatus(OrderStatusV1.CANCEL.getCode());
                orderViewStatusDto.setOrderStatusDesc(OrderStatusV1.CANCEL.getDesc());
                orderViewStatusDto.setOrderStatusDescEn(OrderStatusV1.CANCEL.getDescEn());
                orderViewStatusDto.setOrderStatusDescText("");
            }
            if (OrderStatusV1.TAKE_ORDER.getV2Code().equals(orderBean.getStatusV2())) {
                if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatusV1.TAKE_ORDER.getCode());
                    orderViewStatusDto.setOrderStatusDesc(conventCreateOrderString(orderBean));
//                  orderViewStatusDto.setOrderStatusDesc(OrderStatus.TAKE_ORDER.getDesc());
                    orderViewStatusDto.setOrderStatusDescEn(OrderStatusV1.TAKE_ORDER.getDescEn());
                    orderViewStatusDto.setOrderStatusDescText("目前有" + orderBean.getQueueIndex() + "人在排队，凭此页到店领取哦~");
                    if (StringUtils.isBlank(orderBean.getQueueIndex()) || "0".equals(orderBean.getQueueIndex())) {
                        orderViewStatusDto.setOrderStatusDescText("凭此页到店领取哦~");
                    }
                    orderViewStatusDto.setButtonContactPartner(true);
                    orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                    orderViewStatusDto.setButtonMealCode(true);
                }
                //申请退款
                if (refundBean != null && RefundStatus.APPLY_REFUND.getCode().equals(refundBean.getStatus())) {
                    setApplyRefundDesc(orderViewStatusDto, orderBean);
                }
                //同意退款
                if (refundBean != null && RefundStatus.AGREE_REFUND.getCode().equals(refundBean.getStatus())) {
                    setAgreeRefundDesc(orderViewStatusDto, orderBean);
                }
                //已退货
                if (refundBean != null && RefundStatus.ALREADY_REFUND.getCode().equals(refundBean.getStatus())) {
                    setAgreeRefundDesc(orderViewStatusDto, orderBean);
                }
                //拒绝退款
                if (refundBean != null && RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    orderViewStatusDto.setRefundStatusText("如有疑问可致电商家沟通确认");
                }
            }
            if (OrderStatusV1.RECEIPT.getV2Code().equals(orderBean.getStatusV2())) {
                if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatusV1.RECEIPT.getCode());
//                  orderViewStatusDto.setOrderStatusDesc(OrderStatusV1.RECEIPT.getDesc());
                    orderViewStatusDto.setOrderStatusDescEn(OrderStatusV1.RECEIPT.getDescEn());
                    orderViewStatusDto.setOrderStatusDesc(conventProduceString(orderBean));
                    orderViewStatusDto.setOrderStatusDescText("目前有" + orderBean.getQueueIndex() + "人在排队，凭此页到店领取哦~");
                    if (StringUtils.isBlank(orderBean.getQueueIndex()) || "0".equals(orderBean.getQueueIndex())) {
                        orderViewStatusDto.setOrderStatusDescText("凭此页到店领取哦~");
                    }
                    orderViewStatusDto.setButtonContactPartner(true);
                    orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                    orderViewStatusDto.setButtonMealCode(true);
                }
                if (refundBean != null && RefundStatus.APPLY_REFUND.getCode().equals(refundBean.getStatus())) {
                    setApplyRefundDesc(orderViewStatusDto, orderBean);
                }
                if (refundBean != null && RefundStatus.AGREE_REFUND.getCode().equals(refundBean.getStatus())) {
                    setAgreeRefundDesc(orderViewStatusDto, orderBean);
                }
                if (refundBean != null && RefundStatus.ALREADY_REFUND.getCode().equals(refundBean.getStatus())) {
                    setAgreeRefundDesc(orderViewStatusDto, orderBean);
                }
                //拒绝退款
                if (refundBean != null && RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    orderViewStatusDto.setRefundStatusText("如有疑问可致电商家沟通确认");
                }
            }
            if (OrderStatusV1.COMPLETE_MAKE.getV2Code().equals(orderBean.getStatusV2())) {
                if (refundBean == null) {
                    orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                }
                if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatusV1.COMPLETE_MAKE.getCode());
                    orderViewStatusDto.setOrderStatusDesc("待取餐");
                    //制作完成 中文返回待取餐  英文反回制作完成
                    orderViewStatusDto.setOrderStatusDescEn("Goods to be collected");
                    orderViewStatusDto.setOrderStatusDescText("目前有" + orderBean.getQueueIndex() + "人在排队，凭此页到店领取哦~");
                    if (StringUtils.isBlank(orderBean.getQueueIndex()) || "0".equals(orderBean.getQueueIndex())) {
                        orderViewStatusDto.setOrderStatusDescText("凭此页到店领取哦~");
                    }
                    orderViewStatusDto.setButtonContactPartner(true);
                    orderViewStatusDto.setButtonMealCode(true);
                }
                if (refundBean != null && RefundStatus.APPLY_REFUND.getCode().equals(refundBean.getStatus())) {
                    setApplyRefundDesc(orderViewStatusDto, orderBean);
                }
                if (refundBean != null && RefundStatus.AGREE_REFUND.getCode().equals(refundBean.getStatus())) {
                    setAgreeRefundDesc(orderViewStatusDto, orderBean);
                }
                //拒绝退款
                if (refundBean != null && RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    orderViewStatusDto.setRefundStatusText("如有疑问可致电商家沟通确认");
                }
            }
        }
        if (OrderTypeV1.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
            if (OrderStatusV1.WAIT_PAY.getV2Code().equals(orderBean.getStatusV2())) {
                orderViewStatusDto.setOrderStatus(OrderStatusV1.WAIT_PAY.getCode());
                orderViewStatusDto.setOrderStatusDesc(OrderStatusV1.WAIT_PAY.getDesc());
                orderViewStatusDto.setOrderStatusDescEn(OrderStatusV1.WAIT_PAY.getDescEn());
                orderViewStatusDto.setOrderStatusDescText("");
            }
            if (OrderStatusV1.TAKE_ORDER.getV2Code().equals(orderBean.getStatusV2())) {
                if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    if (orderBean.getDeliverStatus() == null) {
                        orderViewStatusDto.setRiderName("商家自配送");
                    } else {
                        orderViewStatusDto.setRiderName("处理中");
                    }
                    orderViewStatusDto.setOrderStatus(OrderStatusV1.TAKE_ORDER.getCode());
                    orderViewStatusDto.setOrderStatusDesc(conventCreateOrderString(orderBean));
                    orderViewStatusDto.setOrderStatusDescEn(OrderStatusV1.TAKE_ORDER.getDescEn());
                    orderViewStatusDto.setOrderStatusDescText("请稍等片刻，美味即将到达哦~");
                    orderViewStatusDto.setButtonContactPartner(true);
                    orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                    orderViewStatusDto.setRiderText("正在为您匹配配送员");
                    orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                }
                if (refundBean != null && RefundStatus.APPLY_REFUND.getCode().equals(refundBean.getStatus())) {
                    setApplyRefundDesc(orderViewStatusDto, orderBean);
                }
                if (refundBean != null && RefundStatus.AGREE_REFUND.getCode().equals(refundBean.getStatus())) {
                    setAgreeRefundDesc(orderViewStatusDto, orderBean);
                }
                //拒绝退款
                if (refundBean != null && RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    orderViewStatusDto.setRefundStatusText("如有疑问可致电商家沟通确认");
                }
            }
            if (OrderStatusV1.RECEIPT.getV2Code().equals(orderBean.getStatusV2())) {
                if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    if (orderBean.getDeliverStatus() == null) {
                        orderViewStatusDto.setOrderStatus(OrderStatusV1.RECEIPT.getCode());
                        orderViewStatusDto.setOrderStatusDesc(conventProduceString(orderBean));
                        orderViewStatusDto.setOrderStatusDescText("请稍等片刻，美味即将到达哦~");
                        orderViewStatusDto.setRiderName("商家自配送");
                        orderViewStatusDto.setRiderText("正在为您匹配配送员");
                        orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                        orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                        orderViewStatusDto.setButtonContactPartner(true);
                    } else {
                        orderViewStatusDto.setOrderStatus(OrderStatusV1.RECEIPT.getCode());
                        orderViewStatusDto.setOrderStatusDesc(conventProduceString(orderBean));
                        orderViewStatusDto.setOrderStatusDescText("请稍等片刻，美味即将到达哦~");
                        orderViewStatusDto.setRiderName(StringUtils.isEmpty(orderBean.getRiderName()) ? "处理中" : orderBean.getRiderName());
                        orderViewStatusDto.setRiderText(StringUtils.isEmpty(orderBean.getRiderName()) ? "正在为您匹配配送员" : "配送员");
                        orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                        orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                        orderViewStatusDto.setButtonContactPartner(true);
                    }
                    //制作中
                    orderViewStatusDto.setOrderStatusDescEn("In production");
                }
                if (refundBean != null && RefundStatus.APPLY_REFUND.getCode().equals(refundBean.getStatus())) {
                    setApplyRefundDesc(orderViewStatusDto, orderBean);
                }
                if (refundBean != null && RefundStatus.AGREE_REFUND.getCode().equals(refundBean.getStatus())) {
                    setAgreeRefundDesc(orderViewStatusDto, orderBean);
                }
                //拒绝退款
                if (refundBean != null && RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    orderViewStatusDto.setRefundStatusText("如有疑问可致电商家沟通确认");
                }
            }
            if (OrderStatusV1.COMPLETE_MAKE.getV2Code().equals(orderBean.getStatusV2())) {
                if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    if (orderBean.getDeliverStatus() == null) {
                        orderViewStatusDto.setOrderStatus(OrderStatusV1.COMPLETE_MAKE.getCode());
                        orderViewStatusDto.setOrderStatusDesc("配送中");
                        orderViewStatusDto.setOrderStatusDescText("请稍等片刻，美味即将到达哦~");
                        orderViewStatusDto.setRiderName("商家自配送");
                        orderViewStatusDto.setRiderText("配送员已送出");
                        orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                        orderViewStatusDto.setButtonContactPartner(true);
                    } else {
                        orderViewStatusDto.setOrderStatus(OrderStatusV1.COMPLETE_MAKE.getCode());
                        orderViewStatusDto.setOrderStatusDesc("配送中");
                        orderViewStatusDto.setOrderStatusDescText("请稍等片刻，美味即将到达哦~");
                        orderViewStatusDto.setRiderName(StringUtils.isEmpty(orderBean.getRiderName()) ? "处理中" : orderBean.getRiderName());
                        orderViewStatusDto.setRiderText(StringUtils.isEmpty(orderBean.getRiderName()) ? "正在为您匹配配送员" : "配送员");
                        orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                        orderViewStatusDto.setButtonContactPartner(true);
                    }
                    orderViewStatusDto.setOrderStatusDescEn(OrderStatusV1.DISTRIBUTION.getDescEn());
                }
                if (refundBean != null && RefundStatus.APPLY_REFUND.getCode().equals(refundBean.getStatus())) {
                    setApplyRefundDesc(orderViewStatusDto, orderBean);
                }
                if (refundBean != null && RefundStatus.AGREE_REFUND.getCode().equals(refundBean.getStatus())) {
                    setAgreeRefundDesc(orderViewStatusDto, orderBean);
                }
                //拒绝退款
                if (refundBean != null && RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    orderViewStatusDto.setRefundStatusText("如有疑问可致电商家沟通确认");
                }
            }
            //TODO 判断配送中的逻辑 如果是有第三方配送，要查询第三方配送信息，显示骑手信息 如果有骑手信息 显示 联系骑手
            if (OrderStatusV1.DISTRIBUTION.getV2Code().equals(orderBean.getStatusV2())) {
                if (orderBean.getDeliverStatus() == null || DeliverStatus.OTHER.getCode().equals(orderBean.getDeliverStatus())
                        || DeliverStatus.DELIVER_OTHER.getCode().equals(orderBean.getDeliverStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatusV1.DISTRIBUTION.getCode());
                    orderViewStatusDto.setOrderStatusDesc(OrderStatusV1.DISTRIBUTION.getDesc());
                    orderViewStatusDto.setOrderStatusDescEn(OrderStatusV1.DISTRIBUTION.getDescEn());
                    orderViewStatusDto.setOrderStatusDescText("请稍等片刻，美味即将到达哦~");
                    orderViewStatusDto.setButtonContactPartner(true);
                    orderViewStatusDto.setRiderName("商家自配送");
                    orderViewStatusDto.setRiderText("配送员已送出");
                    orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                } else {
                    if (DeliverStatus.WATINGORDER.getCode().equals(orderBean.getDeliverStatus()) || DeliverStatus.SYSTEMGETORDER.getCode().equals(orderBean.getDeliverStatus())
                            || DeliverStatus.ALLOTRIDER.getCode().equals(orderBean.getDeliverStatus())
                            || DeliverStatus.RIDERARRIVESTORE.getCode().equals(orderBean.getDeliverStatus())
                            || DeliverStatus.DELIVERYCOLLECT.getCode().equals(orderBean.getDeliverStatus())) {
                        orderViewStatusDto.setOrderStatus(OrderViewStatus.RIDERDELIVERY.getCode());
                        orderViewStatusDto.setOrderStatusDesc("骑手取餐中");
                        orderViewStatusDto.setOrderStatusDescEn("Rider goes to collect goods");
                        orderViewStatusDto.setOrderStatusDescText("请稍等片刻，美味即将到达哦~");
                        orderViewStatusDto.setButtonRefund(true);
                        orderViewStatusDto.setButtonContactPartner(true);
                    }
                    if (DeliverStatus.RIDERDELIVERY.getCode().equals(orderBean.getDeliverStatus())
                            || DeliverStatus.RIDERSTARTDELIVERY.getCode().equals(orderBean.getDeliverStatus())
                            || DeliverStatus.DELIVERYERROR.getCode().equals(orderBean.getDeliverStatus())
                            || DeliverStatus.DELIVERYCANCEL.getCode().equals(orderBean.getDeliverStatus())) {
                        orderViewStatusDto.setOrderStatus(OrderViewStatus.DISTRIBUTION.getCode());
                        orderViewStatusDto.setOrderStatusDesc(OrderStatusV1.DISTRIBUTION.getDesc());
                        orderViewStatusDto.setOrderStatusDescEn(OrderStatusV1.DISTRIBUTION.getDescEn());
                        orderViewStatusDto.setOrderStatusDescText("请稍等片刻，美味即将到达哦~");
                        orderViewStatusDto.setButtonContactRider(true);
                        orderViewStatusDto.setButtonContactPartner(true);
                    }
                    orderViewStatusDto.setRiderName(StringUtils.isEmpty(orderBean.getRiderName()) ? "商家自配送" : orderBean.getRiderName());
                    orderViewStatusDto.setRiderText(StringUtils.isEmpty(orderBean.getRiderName()) ? "配送员已送出" : "配送员");
                    orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                }
            }
        }
        if (BizTypeEnum.MALL.getBizType() != orderBean.getBizType()) {
//            if (!OrderClientType.SAASMALL.getIndex().toString().equalsIgnoreCase(orderBean.getOrderClient())) {
            /**由于下方部分状态描述未找到枚举类，直接赋值英文字段**/
            if (refundBean != null && RefundStatus.AGREE_REFUND.getCode().equals(refundBean.getStatus())) {
                orderViewStatusDto.setOrderStatus(OrderStatusV1.CANCEL.getCode());
                orderViewStatusDto.setOrderStatusDesc(PayStatus.HAVE_REFUND.getDesc());
                orderViewStatusDto.setOrderStatusDescEn(PayStatus.HAVE_REFUND.getDescEn());
                orderViewStatusDto.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
                orderViewStatusDto.setRefundStatusText("订单金额已原路退还，请及时查看~");
                orderViewStatusDto.setButtonContactPartner(true);
            }
            if (refundBean != null && RefundStatus.ALREADY_REFUND.getCode().equals(refundBean.getStatus())) {
                orderViewStatusDto.setOrderStatus(OrderStatusV1.CANCEL.getCode());
                orderViewStatusDto.setOrderStatusDesc("退款中");
                orderViewStatusDto.setOrderStatusDescEn("Refund in progress");
                orderViewStatusDto.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
                orderViewStatusDto.setRefundStatusText("正在退款中，请稍等");
                orderViewStatusDto.setButtonContactPartner(true);
            }
            if (PayStatus.HAVE_REFUND.getCode().equals(orderBean.getPayStatus())) {
                orderViewStatusDto.setOrderStatus(OrderStatusV1.CANCEL.getCode());
                orderViewStatusDto.setOrderStatusDesc(PayStatus.HAVE_REFUND.getDesc());
                orderViewStatusDto.setOrderStatusDescEn(PayStatus.HAVE_REFUND.getDescEn());
                orderViewStatusDto.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
                orderViewStatusDto.setRefundStatusText("订单金额已原路退还，请及时查看~");
                orderViewStatusDto.setButtonContactPartner(true);
            }

            if (OrderStatusV1.COMPLETE.getV2Code().equals(orderBean.getStatusV2())) {
                // TODO: 2019/9/9 获取商户退款配置
                if (refundBean != null && refundBean.getStatus() != null) {
                    orderViewStatusDto.setButtonRefund(false);
                    orderViewStatusDto.setRefundStatusText("商家会处理退款申请，请稍后");

                    //拒绝退款
                    if (refundBean != null && RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                        orderViewStatusDto.setRefundStatusText("如有疑问可致电商家沟通确认");
                    }
                } else {
                    orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                }
                orderViewStatusDto.setOrderStatus(OrderStatusV1.COMPLETE.getCode());
                orderViewStatusDto.setOrderStatusDesc(OrderStatusV1.COMPLETE.getDesc());
                orderViewStatusDto.setOrderStatusDescEn(OrderStatusV1.COMPLETE.getDescEn());
                orderViewStatusDto.setOrderStatusDescText("订单已完成，记得来评价一下哦~");
                orderViewStatusDto.setButtonContactPartner(true);
                orderViewStatusDto.setButtonEvaluate(true);
                if (OrderTypeV1.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
                    if (orderBean.getDeliverStatus() == null) {
                        orderViewStatusDto.setRiderName("商家自配送");
                        orderViewStatusDto.setRiderText("配送员已配送完");
                        orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                    } else {
                        //TODO 如果是第三方配送，设置骑手信息
                        orderViewStatusDto.setRiderName(StringUtils.isEmpty(orderBean.getRiderName()) ? "商家自配送" : orderBean.getRiderName());
                        orderViewStatusDto.setRiderText(StringUtils.isEmpty(orderBean.getRiderName()) ? "配送员已配送完" : "配送员");
                        orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                    }
                }
            }
        } else {//微商城订单
            if (OrderStatusV1.WAIT_PAY.getV2Code().equals(orderBean.getStatusV2())) {
                orderViewStatusDto.setOrderStatus(OrderStatusV1.WAIT_PAY.getCode());
                orderViewStatusDto.setOrderStatusDesc("待支付");
                orderViewStatusDto.setOrderStatusDescText("");
            }
            if (OrderStatusV1.TAKE_ORDER.getV2Code().equals(orderBean.getStatusV2())) {
                orderViewStatusDto.setOrderStatus(OrderStatusV1.WAIT_PAY.getCode());
                orderViewStatusDto.setOrderStatusDesc("已支付");
                orderViewStatusDto.setOrderStatusDescText("");
            }
            if (OrderStatusV1.RECEIPT.getV2Code().equals(orderBean.getStatusV2())) {
                orderViewStatusDto.setOrderStatus(OrderStatusV1.RECEIPT.getCode());
                orderViewStatusDto.setOrderStatusDesc("待发货");
                orderViewStatusDto.setOrderStatusDescText("请稍等片刻，商品即将发货哦~");
                orderViewStatusDto.setRiderName("商品即将发货");
                orderViewStatusDto.setRiderText("正在为您商品打包");
                orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                orderViewStatusDto.setButtonContactPartner(true);
            }
            if (OrderStatusV1.DISTRIBUTION.getV2Code().equals(orderBean.getStatusV2())) {
                orderViewStatusDto.setOrderStatus(OrderStatusV1.DISTRIBUTION.getCode());
                orderViewStatusDto.setOrderStatusDesc("已发货");
                orderViewStatusDto.setOrderStatusDescText("请稍等片刻，商品已经发货哦~");
                orderViewStatusDto.setRiderName("商家自配送");
                orderViewStatusDto.setRiderText("商品运输中");
                orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                orderViewStatusDto.setButtonContactPartner(true);
            }
            if (OrderStatusV1.COMPLETE.getV2Code().equals(orderBean.getStatusV2())) {
                orderViewStatusDto.setOrderStatus(OrderStatusV1.COMPLETE.getCode());
                orderViewStatusDto.setOrderStatusDesc("已完成");
                orderViewStatusDto.setOrderStatusDescText("订单已经完成，记得来评价一下哦~");
                orderViewStatusDto.setRiderName("订单已完成");
                orderViewStatusDto.setRiderText("订单已经完成，记得来评价一下哦");
                orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                orderViewStatusDto.setButtonContactPartner(true);
            }
            if (OrderStatusV1.CANCEL.getV2Code().equals(orderBean.getStatusV2())) {
                orderViewStatusDto.setOrderStatus(OrderStatusV1.CANCEL.getCode());
                orderViewStatusDto.setOrderStatusDesc("已取消");
                orderViewStatusDto.setOrderStatusDescText("订单已经取消~");
                orderViewStatusDto.setRiderName("订单已取消");
                orderViewStatusDto.setRiderText("订单已经取消");
                orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                orderViewStatusDto.setButtonContactPartner(true);
            }
        }
        return orderViewStatusDto;
    }

    /**
     * 是否支持退款
     * fisherman 虚拟券是否可退款 在这里进行操作判断 【ID1039143】  1.已完成状态,2.配置的属性值>0&&时间范围内
     * bizType=1 && marketingType=11 小助手核销的订单不展示退款按钮 返回false
     *
     * @param orderBean 订单详情
     * @param wxAppId   wxappId
     * @return
     */
    public boolean checkRefundButton(OrderBeanV1 orderBean, String wxAppId) {
        OrderStatusV1 status = OrderStatusV1.getByCode(orderBean.getStatus());
        if (Objects.isNull(status)) {
            return false;
        }
        // [华莱士20210410] 微商城订单判断
        if (Objects.equals(BizTypeEnum.MALL.getBizType(), orderBean.getBizType())) {
            // 除 未支付 拒单 和 取消外，其他可退款
            return Stream.of(OrderStatusV1.WAIT_PAY, OrderStatusV1.CANCEL).noneMatch(s -> Objects.equals(status, s));
        }
        // 爱马哥 预定单 付款之后 预定当天之前的时间都可退款
        if (orderBean.getBizType().compareTo(BizTypeEnum.ADVANCE_ORDER.getBizType()) == 0) {
            return this.checkAdvanceOrder(orderBean.getGmtExpect());
        }
        boolean isMarketType2Tiktok =  orderBean.getBizType().compareTo(BizTypeEnum.ORDINARY.getBizType()) == 0
                &&  orderBean.getMarketingType().compareTo(MarketTypeEnum.TIKTOK_MARKET_ORDER.getIndex().byteValue()) == 0 ;
        if (isMarketType2Tiktok) {
            return false;
        }

        // fisherman 虚拟券商品是否可退款配置校验
        if (orderBean.getBizType().compareTo(BizTypeEnum.SALE_COUPON.getBizType()) == 0) {
            return this.checkRefundButtionBizTypeIs6(orderBean.getCompanyId(), orderBean.getBizType(),
                    orderBean.getStatus(),wxAppId, new Date(orderBean.getGmtCreate()), orderBean.getOrderType());
        }

        // 加价购选择虚拟商品券包，订单完成前可申请退款，完成之后不能申请退款 --> 这里的 bizType应该是 = 1的
        if (OrderStatusV1.COMPLETE.equals(status) && CollectionUtils.isNotEmpty(orderBean.getProductList())) {
            for (ProductBeanV1 productBeanV1 : orderBean.getProductList()){
                if(StringUtils.isNotEmpty(productBeanV1.getExtInfo())){
                    OrderProductAddInfoDto extInfo = JSONObject.parseObject(productBeanV1.getExtInfo(), OrderProductAddInfoDto.class);
                    if(CollectionUtils.isNotEmpty(extInfo.getProductBindingCoupons())){
                        return false;
                    }
                }
            }
        }

        boolean canRefund = false;
        // 查询小程序配置的退款设置
        String redisKey = MessageFormat.format(OrderRedisKeyConstant.ORDER_REFUND_CONFIG, orderBean.getCompanyId(), wxAppId);
        String hashKey;
        if (MarketTypeEnum.CASHIER.getIndex().byteValue()==orderBean.getMarketingType()) {
            //收银单，使用收银单的退款配置
            hashKey = OrderRedisKeyConstant.HashKeyForOrderRefundConfig.CASHIER;
        } else {
            hashKey = OrderTypeV1.TAKE_OUT.getCode().equals(orderBean.getOrderType())
                    ? OrderRedisKeyConstant.HashKeyForOrderRefundConfig.TAKE_OUT
                    : OrderRedisKeyConstant.HashKeyForOrderRefundConfig.EAT_IN;
        }
        String configStr = redisCache.hashGet(redisKey, hashKey);
        if (StringUtils.isEmpty(configStr)) {
            return true;
        }
        OrderRefundConfigEntity config = JSON.parseObject(configStr, OrderRefundConfigEntity.class);
        String orderRefund = null;
        if (MarketTypeEnum.CASHIER.getIndex().byteValue()==orderBean.getMarketingType()) {
            //收银单，使用收银单的退款配置 收银单只有完成的订单，直接判断是否可以退款就行
            orderRefund = config.getCashierOrderRefund();
        } else if (OrderTypeV1.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
            //外卖单，使用外卖单的退款配置
            switch (status) {
                // 未接单
                case TAKE_ORDER: orderRefund = config.getDeliveryTakeOrderRefund(); break;
                //已接单
                case RECEIPT: orderRefund = config.getDeliveryReceiptOrderRefund(); break;
                //制作完成
                case COMPLETE_MAKE: orderRefund = config.getDeliveryCompleteMakeOrderRefund(); break;
                // 订单完成
                case COMPLETE: orderRefund = config.getDeliveryOrderRefund(); break;
                default: break;
            }
        } else {
            //其他，使用堂食的退款配置（必须先判断收银单，因为收银单的类型也是堂食，只是orderClient不一样
            switch (status) {
                // 未接单
                case TAKE_ORDER: orderRefund = config.getTakeOrderRefund(); break;
                //已接单
                case RECEIPT: orderRefund = config.getReceiptOrderRefund(); break;
                //制作完成
                case COMPLETE_MAKE: orderRefund = config.getCompleteMakeOrderRefund(); break;
                // 订单完成
                case COMPLETE: orderRefund = config.getOrderRefund(); break;
                default: break;
            }
        }
        canRefund = ALLOW_REFUND.equals(orderRefund);
        // 如果是订单完成状态的 支持退款， 这里还需要校验一下是否在退款时间范围内
        if (OrderStatusV1.COMPLETE.getCode().equals(status.getCode()) && canRefund) {
            long currentTime = System.currentTimeMillis();
            long gmtModified = orderBean.getGmtModified();
            // 因允许退款日期在外卖类型的value中，如果订单类型为堂食，则会取不到这个值
            if (!OrderTypeV1.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
                configStr = redisCache.hashGet(redisKey, OrderRedisKeyConstant.HashKeyForOrderRefundConfig.TAKE_OUT);
                if (StringUtils.isNotEmpty(configStr)) {
                    OrderRefundConfigEntity ce = JSON.parseObject(configStr, OrderRefundConfigEntity.class);
                    config.setRefundDateRange(ce.getRefundDateRange());
                }
            }
            //退款日期允许范围
            long value = 0L;
            if (StringUtils.isNotEmpty(config.getRefundDateRange())) {
                value = Long.parseLong(config.getRefundDateRange());
            }
            canRefund = ((gmtModified + value * 24 * 60 * 60 * 1000) - currentTime) >= 0;
        }
        return canRefund;
    }

    /**
     * 校验是否配置了 虚拟券 bizTYpe=6 可以退款
     *
     * @param partnerId
     * @param bizType
     * @param orderState
     * @param wxAppId
     * @param createTime
     * @return
     */
    public boolean checkRefundButtionBizTypeIs6(String partnerId, Integer bizType, Integer orderState, String wxAppId, Date createTime, Integer orderType) {
        if (bizType.compareTo(BizTypeEnum.SALE_COUPON.getBizType()) != 0 || orderState.compareTo(OrderStatusV1.COMPLETE.getCode()) != 0) {
            return false;
        }
        String redisKey = MessageFormat.format(OrderRedisKeyConstant.ORDER_REFUND_CONFIG, partnerId, wxAppId);
        // 这里默认是 EAT_IN , 为了兼容后期可能会有改动
        String hashKey = OrderTypeV1.TAKE_OUT.getCode().equals(orderType)
                ? OrderRedisKeyConstant.HashKeyForOrderRefundConfig.TAKE_OUT
                : OrderRedisKeyConstant.HashKeyForOrderRefundConfig.EAT_IN;
        String configStr = redisCache.hashGet(redisKey, hashKey);
        if (StringUtils.isNotEmpty(configStr)) {
            OrderRefundConfigEntity config = JSON.parseObject(configStr, OrderRefundConfigEntity.class);
            Integer couponOrderRefundDayLimit = config.getCouponOrderRefundDayLimit();
            // 必须配置了, 而且创建时间 不大于 这个时间
            if (couponOrderRefundDayLimit != null && couponOrderRefundDayLimit.compareTo(0) > 0) {
                Date date = DateUtil.addDays(createTime, couponOrderRefundDayLimit);
                // 当前时间在 配置时间前面 才可以申请退款
                if (new Date().before(date)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 预约时间
     * @param gmtExpect
     * @return true 可退  false不可操作
     */
    public boolean checkAdvanceOrder(Long gmtExpect) {
        if (Objects.isNull(gmtExpect)) {
            throw new ServiceException(ResponseResult.PARAMETER_MISSING, "gmtExpect参数有异常");
        }
        // 只有在 预约时间当天不可取消订单
        Date expectDate = DateUtil.convert2Date(new Date(gmtExpect), DateUtil.FORMAT_YMD);
        return new Date().before(expectDate);
    }

    public List<OrderAccountVo> convent2OrderAccountVo(List<OrderSettlementResp> orderSettlements) {
        List<OrderAccountVo> orderAccountVos = new ArrayList<>();
        if (CollectionUtils.isEmpty(orderSettlements)) {
            return orderAccountVos;
        }
        //过滤订单级别优惠
        orderSettlements = orderSettlements.stream().filter(orderSettlement -> ("0".equals(orderSettlement.getProductId()) || orderSettlement.getProductId() == null)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(orderSettlements)) {
            return orderAccountVos;
        }
        List<Integer> list = Arrays.asList(OrderSettlementType.FULL_REDUCTION.getIndex(), OrderSettlementType.CASH_COUPON.getIndex(),
                OrderSettlementType.PRODUCT_COUPON.getIndex(), OrderSettlementType.DISCOUNT_COUPON.getIndex(), OrderSettlementType.POINTS.getIndex(), OrderSettlementType.FREIGHT_COUPON.getIndex());
        for (OrderSettlementResp orderSettlement : orderSettlements) {
            if (list.contains(orderSettlement.getSettlementType())) {
                OrderAccountVo accountVo = new OrderAccountVo();
                Integer type = orderSettlement.getSettlementType();
                accountVo.setType(type);
                if (type.compareTo(OrderSettlementType.PRODUCT_COUPON.getIndex()) == 0
                        || type.compareTo(OrderSettlementType.CASH_COUPON.getIndex()) == 0
                        || type.compareTo(OrderSettlementType.DISCOUNT_COUPON.getIndex()) == 0 ){
                    // fisherman ->修改成券名称
                    accountVo.setTypeName(StringUtils.isEmpty(orderSettlement.getNote()) ? "优惠券" : orderSettlement.getNote());
                } else if (type.compareTo(OrderSettlementType.FULL_REDUCTION.getIndex())==0) {
                    accountVo.setTypeName("满减");
                } else if (type.compareTo(OrderSettlementType.POINTS.getIndex())==0) {
                    accountVo.setTypeName("积分抵扣");
                } else if (type.compareTo(OrderSettlementType.FREIGHT_COUPON.getIndex())==0) {
                    accountVo.setTypeName("配送券");
                }else {
                    accountVo.setTypeName("参与活动");
                }
                int value = orderSettlement.getSettlementAmount().intValue();
                accountVo.setDiscountAmount(value < 0 ? -value : value);
                orderAccountVos.add(accountVo);
            }
        }

        return orderAccountVos;
    }

    public void convent2ProductVos(List<ProductBeanV1> productBeans, QueryOrderResponseVo responseVo, String partnerId) {
        if (CollectionUtils.isEmpty(productBeans)) {
            return;
        }
        List<ProductVo> productVos = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(productBeans)) {
            for (ProductBeanV1 productBean : productBeans) {
                ProductVo productVo = convent2ProductVo(productBean);
                // 套餐商品设置子商品节点
                if (ObjectUtils.equals(ProductTypeEnum.SETMEAL_PRODUCT.getCode(), productBean.getProductType()) || ObjectUtils.equals(ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode(), productBean.getProductType())) {
                    if (mcCafePartnerId.equals(partnerId)) {
                        productVo.setOriginalPrice(productBean.getSalePrice() + productBean.getProductSharePrice().longValue());
                    }
                    List<ProductVo> setMealProducts = new ArrayList<>();
                    productBean.getComboProduct().forEach(product -> {
                        if (!"无".equals(product.getSpecificationName())) {
                            ProductVo comboProduct = convent2ProductVo(product);
                            setMealProducts.add(comboProduct);
                            if (ObjectUtils.equals(ProductTypeEnum.MATERIAL_PRODUCT.getCode(), comboProduct.getProductType()) && CollectionUtils.isNotEmpty(product.getMaterialProduct())) {
                                List<ProductVo> setMaterialProducts = new ArrayList<>();
                                product.getMaterialProduct().forEach(materialProduct -> {
                                    ProductVo material = convent2ProductVo(materialProduct);
                                    material.setOriginalTotalAmount(new BigDecimal(material.getOriginalPrice()).multiply(new BigDecimal(productVo.getQty())).longValue());
                                    material.setSaleTotalAmount(new BigDecimal(material.getFinalPrice()).multiply(new BigDecimal(productVo.getQty())).longValue());
                                    setMaterialProducts.add(material);
                                    productVo.setOriginalPrice(new BigDecimal(productVo.getOriginalPrice()).add(new BigDecimal(material.getOriginalPrice())).longValue());
                                    productVo.setFinalPrice(new BigDecimal(productVo.getFinalPrice()).add(new BigDecimal(material.getFinalPrice())).longValue());
                                    productVo.setOriginalTotalAmount(new BigDecimal(productVo.getOriginalTotalAmount()).add(new BigDecimal(material.getOriginalTotalAmount())).longValue());
                                    productVo.setSaleTotalAmount(new BigDecimal(productVo.getSaleTotalAmount()).add(new BigDecimal(material.getSaleTotalAmount())).longValue());
                                });
                                comboProduct.setSetMaterialProducts(setMaterialProducts);
                            }
                        }
                    });
                    productVo.setSetMealProducts(setMealProducts);
                }
                if (ObjectUtils.equals(ProductTypeEnum.MATERIAL_PRODUCT.getCode(), productBean.getProductType())) {
                    List<ProductVo> setMaterialProducts = new ArrayList<>();
                    if (mcCafePartnerId.equals(partnerId)) {
                        productBean.getMaterialProduct().forEach(product -> {
                            ProductVo material = convent2ProductVo(product);
                            setMaterialProducts.add(material);
                            material.setOriginalTotalAmount(new BigDecimal(material.getOriginalPrice()).multiply(new BigDecimal(productVo.getQty())).longValue());
                            material.setSaleTotalAmount(new BigDecimal(material.getFinalPrice()).multiply(new BigDecimal(productVo.getQty())).longValue());
                            productVo.setOriginalPrice(new BigDecimal(productVo.getOriginalPrice()).add(new BigDecimal(material.getOriginalPrice())).longValue());
                            productVo.setFinalPrice(new BigDecimal(productVo.getFinalPrice()).add(new BigDecimal(material.getFinalPrice())).longValue());
                            productVo.setOriginalTotalAmount(new BigDecimal(productVo.getOriginalTotalAmount()).add(new BigDecimal(material.getOriginalTotalAmount())).longValue());
                            productVo.setSaleTotalAmount(new BigDecimal(productVo.getSaleTotalAmount()).add(new BigDecimal(material.getSaleTotalAmount())).longValue());
                        });
                    } else {
                        productBean.getMaterialProduct().forEach(product -> {
                            ProductVo material = convent2ProductVo(product);
                            setMaterialProducts.add(material);
                            productVo.setOriginalPrice(new BigDecimal(productVo.getOriginalPrice()).subtract(new BigDecimal(material.getOriginalPrice())).longValue());
                            productVo.setFinalPrice(new BigDecimal(productVo.getFinalPrice()).subtract(new BigDecimal(material.getFinalPrice())).longValue());
                            productVo.setOriginalTotalAmount(new BigDecimal(productVo.getOriginalTotalAmount()).subtract(new BigDecimal(material.getOriginalTotalAmount())).longValue());
                            productVo.setSaleTotalAmount(new BigDecimal(productVo.getSaleTotalAmount()).subtract(new BigDecimal(product.getSettlementPrice())).longValue());
                        });
                    }
                    productVo.setSetMaterialProducts(setMaterialProducts);
                }
                productVos.add(productVo);
            }
            productVos.sort(Comparator.comparing(ProductVo::getSequence));
            responseVo.setProducts(productVos);
            responseVo.setProductNum(productVos.stream().mapToInt(ProductVo::getQty).sum());
            responseVo.setOrderUserNum(productVos.stream().filter(product -> StringUtils.isNotEmpty(product.getUserId())).map(ProductVo::getUserId).distinct().count());
        }
    }

    public ProductVo convent2ProductVo(ProductBeanV1 productBean) {
        ProductVo productVo = new ProductVo();
        productVo.setId(productBean.getId());
        productVo.setPid(StringUtils.isBlank(productBean.getSpecification()) ? productBean.getProductId() : productBean.getSpecification());
        String productName = StringUtils.isBlank(productBean.getSpecificationName()) ? productBean.getProductName() : productBean.getSpecificationName();
        String foreignProductName = StringUtils.isBlank(productBean.getSpecificationForeignName()) ? productBean.getProductForeignName() : productBean.getSpecificationForeignName();
        OrderProductAddInfoDto extInfo = JSON.parseObject(productBean.getExtInfo(), OrderProductAddInfoDto.class);
        if (null != extInfo && CollectionUtils.isNotEmpty(extInfo.getSpecialAttrs())) {
            String attr = "";
            String attrEng = "";
            for (OrderSpecialExtraAttrRequest special : extInfo.getSpecialAttrs()) {
                if (Objects.nonNull(special.getAttributeName()) && special.getAttributeName().indexOf("冰") >= 0) {
                    attr = special.getAttributeName();
                    attrEng = special.getAttributeForeignName();
                    break;
                }
            }
            if (StringUtils.isNotBlank(attr)) {
                productName += "(" + attr + ")";
            }
            //英文名处理
            if (StringUtils.isNotBlank(attrEng)) {
                foreignProductName += "(" + attrEng + ")";
            }
        }
        if (CollectionUtils.isNotEmpty(productBean.getMaterialProduct())) {
            for (ProductBeanV1 material : productBean.getMaterialProduct()) {
                productName += "/" + material.getSpecificationName();
                foreignProductName += "/" + material.getSpecificationForeignName();
            }
        }

        productVo.setName(productName);
        productVo.setSpuName(productBean.getProductName());
        productVo.setForeignName(foreignProductName);
        productVo.setSpuForeignName(productBean.getProductForeignName());
        productVo.setPicture(productBean.getPicture());
        productVo.setSequence(productBean.getSequence());
        productVo.setQty(productBean.getNumber());
        productVo.setSpecification("");
        productVo.setUserId(productBean.getUserId());
        productVo.setOpenId(productBean.getOpenId());
        productVo.setNickName(productBean.getNickName());
        productVo.setPhotoUrl(productBean.getPhotoUrl());
        productVo.setPackPrice(productBean.getPackPrice());
        List<InventedParentActivityVo> inventedParentActivityVos = new ArrayList<>();
        String attributeNames = "";
        if (StringUtils.isNotBlank(productBean.getAddInfo()) && productBean.getAddInfo().contains("attributeNames")) {
            OrderProductAddInfo orderProductAddInfo = gson.fromJson(productBean.getAddInfo(), OrderProductAddInfo.class);
            attributeNames = orderProductAddInfo.getAttributeNames();
            productVo.setAttributeNames(attributeNames);
            productVo.setSpecification(attributeNames);
        }
        if (StringUtils.isNotBlank(productBean.getExtInfo())) {
            OrderProductAddInfoDto orderProductAddInfoDto = gson.fromJson(productBean.getExtInfo(), OrderProductAddInfoDto.class);
            if (CollectionUtils.isNotEmpty(orderProductAddInfoDto.getProductBindingCoupons())) {
                for (ProductBindingCouponType productBindingCouponType : orderProductAddInfoDto.getProductBindingCoupons()) {
                    InventedParentActivityVo inventedParentActivityVo = new InventedParentActivityVo();
//                    inventedParentActivityVo.setActivityCode(productBindingCouponType.getActivityCode());
                    inventedParentActivityVo.setActivityName(productBindingCouponType.getActivityName());
                    inventedParentActivityVo.setNum(productBindingCouponType.getNum());
                    inventedParentActivityVos.add(inventedParentActivityVo);
                }
                productVo.setInventedParentActivitiesVo(inventedParentActivityVos);
            }
            productVo.setScore(orderProductAddInfoDto.getScore());
            // 购物车行id
            productVo.setCid(orderProductAddInfoDto.getCartGoodsUid());
            // 购物车行父id
            productVo.setOcid(orderProductAddInfoDto.getOriginalGoodsUid());
            if (StringUtils.isNotBlank(orderProductAddInfoDto.getSplitIndex())) {
                productVo.setSplitIndex(orderProductAddInfoDto.getSplitIndex());
            }
            if (null != orderProductAddInfoDto.getIsSendGoods() && orderProductAddInfoDto.getIsSendGoods()) {
                productVo.setIsSendGoods(1);
            }
        }
        productVo.setOriginalPrice(productBean.getPrice());
        productVo.setFinalPrice(productBean.getSalePrice());
        productVo.setExtras(shoppingCartAdapter.getExtraName(productBean.getSpecificationName(), attributeNames));
        productVo.setForeignExtras(shoppingCartAdapter.getForeignExtras(productBean.getSpecificationForeignName(), productBean.getProductForeignProperty()));
        productVo.setAttributeNamesEn(productBean.getProductForeignProperty());
        //计算商品原总金额=商品原价格 * 商品数量
        Long originalTotalAmount = productBean.getPrice() * productBean.getNumber();
        if (ProductTypeEnum.WEIGHT_PRODUCT.getCode().equals(productBean.getProductType())) {
            Double weight = (productBean.getWeight() == null || new BigDecimal("0.00").compareTo(productBean.getWeight()) <= 0) ? 0 : productBean.getWeight().doubleValue();
            Double weightPrice = weight * productBean.getPrice();
            originalTotalAmount = weightPrice.longValue();
        }
        //商品实际销售总金额 商品原总金额-（商品实际优惠总金额，不包括满减）
        Long discountTotalAmount = 0L;
        //判断当前商品内是否包含商品券商品 如果包含，商品名称改为商品券名称
        Boolean hasProductCoupon = false;
        Long couponDiscount = 0L;
        Long fullReduction = 0L;
        Integer activityType = 0;
        if (CollectionUtils.isNotEmpty(productBean.getDiscountList())) {
            for (ProductDiscountV1 productDiscount : productBean.getDiscountList()) {
                if (productDiscount.getDiscountType() == null || productDiscount.getDiscountType() == 0) {
                    continue;
                }
                discountTotalAmount = discountTotalAmount + productDiscount.getDiscountAmount() * productDiscount.getDiscountQty();
                if (OrderAccountType.PRODUCT_COUPON.getCode().equals(productDiscount.getDiscountType()) || OldOrderAccountType.EVM_PRODUCT_COUPON.getCode().equals(productDiscount.getDiscountType())) {
                    hasProductCoupon = true;
                    if (StringUtils.isNotBlank(productDiscount.getExtInfo())) {
                        JSONObject productDiscountExtInfo = JSON.parseObject(productDiscount.getExtInfo());
                        Integer extendType = productDiscountExtInfo.getInteger("extendType");
                        if (null == extendType || extendType != 12) {
                            productVo.setCouponName(productDiscount.getDiscountDesc());
                        } else {
                            productVo.setFinalPrice(productVo.getOriginalPrice());
                        }
                        if (null != extendType && extendType == 7) {
                            productVo.setIsB3S1CouponGoods(1);
                        }
                    }
                }
                if (OrderAccountType.BUYM_SENDN.getCode().equals(productDiscount.getDiscountType())) {
                    activityType = ActivityTypeEnum.TYPE_61.getCode();
                }
                if (OrderAccountType.BUYM_SENDN_230.getCode().equals(productDiscount.getDiscountType())) {
                    activityType = ActivityTypeEnum.TYPE_230.getCode();
                }
                if (OrderAccountType.PRODUCT_COUPON.getCode().equals(productDiscount.getDiscountType())) {
                    activityType = ActivityTypeEnum.TYPE_32.getCode();
                    couponDiscount = productDiscount.getDiscountAmount();
                }
                if (OrderAccountType.DISCOUNT_COUPON.getCode().equals(productDiscount.getDiscountType())) {
                    couponDiscount = productDiscount.getDiscountAmount();
                }
                if (OrderAccountType.COUPON.getCode().equals(productDiscount.getDiscountType())) {
                    couponDiscount = productDiscount.getDiscountAmount();
                }
                if (OrderAccountType.BUY_DISCOUNT.getCode().equals(productDiscount.getDiscountType())) {
                    fullReduction = productDiscount.getDiscountAmount();
                }
                if (OldOrderAccountType.B3S1_COUPON.getCode().equals(productDiscount.getDiscountType())) {
                    productVo.setIsB3S1CouponGoods(1);
                }
            }
        }
        //优惠券满减总优惠
        Long couponFull = couponDiscount + fullReduction;
        productVo.setOriginalTotalAmount(originalTotalAmount);
        Long saleTotalAmount = productBean.getSettlementPrice() + couponFull;
        productVo.setSaleTotalAmount(saleTotalAmount);
        productVo.setHasProductCoupon(hasProductCoupon);
        productVo.setActivityType(activityType);
        //套餐
        productVo.setParentProductId(productBean.getParentProductId());
        productVo.setProductType(productBean.getProductType());
        if (ProductTypeEnum.TABLEWARE_PRODUCT.getCode().equals(productBean.getProductType())) {
            productVo.setIsTableware(true);
        }
        productVo.setUnit(productBean.getUnit());
        productVo.setWeight(productBean.getWeight() != null ? productBean.getWeight().doubleValue() : 0);
        return productVo;
    }


    public PayRefundRequestDto getOrderPayRefundRequest(OrderBeanV1 orderBean, Long refundId, String fatherOrderId) {
        PayRefundRequestDto orderPayRefundRequest = new PayRefundRequestDto();
        orderPayRefundRequest.setOrgTransId(fatherOrderId);
        orderPayRefundRequest.setPartnerId(orderBean.getCompanyId());
        orderPayRefundRequest.setStoreId(orderBean.getShopId());
        orderPayRefundRequest.setOrgPayFmId(orderBean.getPayVoucher());
        orderPayRefundRequest.setRefundAmount(orderBean.getAmount());
        orderPayRefundRequest.setRefundId(refundId.toString());
        OrderExtInfoDto orderExtInfoDTO = gson.fromJson(orderBean.getExtInfo(), OrderExtInfoDto.class);
        orderPayRefundRequest.setOpenid(orderExtInfoDTO != null ? orderExtInfoDTO.getOpenid() : "");
        orderPayRefundRequest.setAppId(orderExtInfoDTO != null ? orderExtInfoDTO.getAppid() : "");
        orderPayRefundRequest.setNotifyUrl(refundNotifyCallback);
        return orderPayRefundRequest;
    }

    public MultiOrderRefundRequest getMultiOrderPayRefundRequest(OrderBeanV1 orderBean, Long refundId) {
        MultiOrderRefundRequest multiQueryRequest = new MultiOrderRefundRequest();
        multiQueryRequest.setStationId("1");
        multiQueryRequest.setPartnerId(orderBean.getCompanyId());
        multiQueryRequest.setStoreId(orderBean.getShopId());
        multiQueryRequest.setFmId("");
        multiQueryRequest.setRefundAmount(orderBean.getAmount());
        multiQueryRequest.setRefundTradeNo(String.valueOf(refundId));
        multiQueryRequest.setStoreId(orderBean.getShopId());
        multiQueryRequest.setNotifyUrl(refundNotifyCallback);
        multiQueryRequest.setVer("V1");
        multiQueryRequest.setVer3(false);
        multiQueryRequest.setOutOrderNo(orderBean.getOid());
        return multiQueryRequest;
    }

    public CancelOrderRequest convent2CancelOrderRequest(String orderId, String partnerId, AfterSalesType afterSalesType,
                                                         String reason, String trackingNo, String refundId) {
        CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
        cancelOrderRequest.setOrderId(orderId);
        cancelOrderRequest.setPartnerId(partnerId);
        cancelOrderRequest.setAfterSalesType(afterSalesType);
        if (StringUtils.isNotBlank(reason) && reason.length() > 50) {
            reason = reason.substring(0, 50);
        }
        cancelOrderRequest.setReason(reason);
        cancelOrderRequest.setTrackingNo(trackingNo);
        cancelOrderRequest.setRefundSerialNo(refundId);
        //操作来源客户端 1:POS插件 2:小助手 3:开放平台 4:自动任务 5:用户端 6:系统 7:万象 8:太一
        cancelOrderRequest.setOperationClient(5);
        if (AfterSalesType.SYSTEM_CANCEL.getIndex().equals(afterSalesType.getIndex())) {
            cancelOrderRequest.setOperator("admin");
            cancelOrderRequest.setOperationClient(6);
        }
        //若为4，默认做【创建】+【同意并退款完成】，售后单状态为【完成】
        cancelOrderRequest.setCreateEvent(4);
        return cancelOrderRequest;
    }

    public OrderPrintDto convert2OrderPrintDto(OrderBeanV1 orderBean) {
        OrderPrintDto orderPrintDto = new OrderPrintDto();
        orderPrintDto.setPartnerId(orderBean.getCompanyId());
        orderPrintDto.setStoreId(orderBean.getShopId());
        //确定日订单序号
        orderPrintDto.setType(orderBean.getOrderType());
        orderPrintDto.setOid(orderBean.getOid());
        orderPrintDto.setUserName(orderBean.getUserName());
        orderPrintDto.setDaySeq(orderBean.getDaySeq() == null ? "" : orderBean.getDaySeq().toString());
        orderPrintDto.setPhone(orderBean.getPhone());
        orderPrintDto.setAddress(orderBean.getAddress());
        orderPrintDto.setGmtExpect(orderBean.getGmtExpect() == null ? "立即送出" : (DateUtil.convert2String(new Date(orderBean.getGmtExpect()),
                DateUtil.FORMAT_YYYY_MM_DD_HHMMSS)));
        if (orderBean.getAddInfo() != null && StringUtils.isNotBlank(orderBean.getAddInfo().getDeliveryType())) {
            orderPrintDto.setDeliveryTypeDesc("第三方配送");
            if (StringUtils.isNotBlank(orderBean.getAddInfo().getExpress())) {
                orderPrintDto.setDeliveryTypeDesc(orderBean.getAddInfo().getExpress());
            }
        } else {
            orderPrintDto.setDeliveryTypeDesc("自配送");
        }
        orderPrintDto.setRemark(orderBean.getRemark());
        Integer count = orderBean.getProductList().stream().map(ProductBeanV1::getNumber).reduce(Integer::sum).get();
        orderPrintDto.setProductTotalAmount(count);
        Long productAmount = orderBean.getProductList().stream().map(p -> p.getPrice() * p.getNumber()).reduce(Long::sum).get();
        Long packageFee = 0L;
        Long sendFee = 0L;
        Long discountFee = 0L;
        if (CollectionUtils.isNotEmpty(orderBean.getAccountList())) {
            for (AccountBeanV1 accountBean : orderBean.getAccountList()) {
                if (OrderAccountType.PACK_AMOUNT.getCode().equals(accountBean.getType())) {
                    packageFee = accountBean.getPrice() * accountBean.getNumber();
                }
                if (OrderAccountType.DELIVERY_AMOUNT.getCode().equals(accountBean.getType())) {
                    sendFee = accountBean.getPrice() * accountBean.getNumber();
                }
                //非包装费和配送费都是优惠
                if (!(OrderAccountType.PACK_AMOUNT.getCode().equals(accountBean.getType())
                        || OrderAccountType.DELIVERY_AMOUNT.getCode().equals(accountBean.getType()))) {
                    discountFee = discountFee + (accountBean.getPrice() < 0 ? 0 - accountBean.getPrice() : accountBean.getPrice());
                }
            }
        }
        orderPrintDto.setPackageFee(packageFee);
        orderPrintDto.setProductAmount(productAmount + packageFee);
        orderPrintDto.setSendFee(sendFee);
        orderPrintDto.setDiscountFee(discountFee);
        orderPrintDto.setUserFee(orderBean.getAmount());
        orderPrintDto.setGmtCreate(DateUtil.convert2String(new Date(orderBean.getGmtCreate()), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        orderPrintDto.setShopName(orderBean.getShopName());
        orderPrintDto.setOtherCode(orderBean.getOtherCode());
        List<OrderPrintDto.ProductsBean> productsBeans = getProducts(orderBean.getProductList());
        orderPrintDto.setProducts(productsBeans);
        orderPrintDto.setBarCounter(orderBean.getBarCounter());
        return orderPrintDto;
    }

    public List<OrderPrintDto.ProductsBean> getProducts(List<ProductBeanV1> productBeans) {
        if (CollectionUtils.isEmpty(productBeans)) {
            return Collections.emptyList();
        }
        List<OrderPrintDto.ProductsBean> products = Lists.newArrayList();
        for (ProductBeanV1 productBean : productBeans) {
            OrderPrintDto.ProductsBean productVO = getProductBean(productBean);
            List<OrderPrintDto.ProductsBean> comboProductVOs = new ArrayList<>();
            List<OrderPrintDto.ProductsBean> materialProductVOs = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(productBean.getComboProduct())) {
                for (ProductBeanV1 comboProduct : productBean.getComboProduct()) {
                    OrderPrintDto.ProductsBean sonProductVO = getProductBean(comboProduct);
                    comboProductVOs.add(sonProductVO);
                }
            }
            if (CollectionUtils.isNotEmpty(productBean.getMaterialProduct())) {
                for (ProductBeanV1 materialProduct : productBean.getMaterialProduct()) {
                    OrderPrintDto.ProductsBean materialProductVO = getProductBean(materialProduct);
                    materialProductVOs.add(materialProductVO);
                }
            }
            productVO.setSonProducts(comboProductVOs);
            productVO.setMaterialProducts(materialProductVOs);
            products.add(productVO);
        }
        return products;
    }

    private OrderPrintDto.ProductsBean getProductBean(ProductBeanV1 productBean) {
        OrderPrintDto.ProductsBean productBean1 = new OrderPrintDto.ProductsBean();
        productBean1.setParentProductId(productBean.getParentProductId());
        productBean1.setSequence(productBean.getSequence());
        productBean1.setProductId(productBean.getSpecification() == null ? productBean.getProductId() : productBean.getSpecification());
        productBean1.setProductName(StringUtils.isNotBlank(productBean.getSpecificationName()) ?
                productBean.getSpecificationName() : productBean.getProductName());
        productBean1.setNumber(productBean.getNumber());
        String extraName = "";
        if (productBean.getAddInfo().contains("attributeNames")) {
            OrderProductAddInfo addInfo = gson.fromJson(productBean.getAddInfo(), OrderProductAddInfo.class);
            extraName = addInfo.getAttributeNames();
        }
        if ((ObjectUtils.equals(ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode(), productBean.getProductType())
                || ObjectUtils.equals(ProductTypeEnum.SETMEAL_PRODUCT.getCode(), productBean.getProductType())) &&
                StringUtils.isBlank(productBean.getParentProductId())) {
            productBean1.setPrice(productBean.getSalePrice());
        } else {
            productBean1.setPrice(productBean.getPrice());
        }
        productBean1.setProductOtherInfo(extraName);
        productBean1.setParentType(productBean.getProductType());
        productBean1.setSonProducts(new ArrayList<>());
        productBean1.setUnit(productBean.getUnit());
        return productBean1;
    }

    //申请
    public void setApplyRefundDesc(OrderViewStatusDto orderViewStatusDto, OrderBeanV1 orderBean) {
        orderViewStatusDto.setOrderStatus(orderBean.getStatus());
        orderViewStatusDto.setOrderStatusDesc("退款中");
        orderViewStatusDto.setOrderStatusDescEn("Refund in progress");
        orderViewStatusDto.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
        orderViewStatusDto.setRefundStatusText("商家会处理退款申请，请稍后");
        orderViewStatusDto.setButtonContactPartner(true);
    }

    //同意
    public void setAgreeRefundDesc(OrderViewStatusDto orderViewStatusDto, OrderBeanV1 orderBean) {
        orderViewStatusDto.setOrderStatus(orderBean.getStatus());
        orderViewStatusDto.setOrderStatusDesc("退款中");
        orderViewStatusDto.setOrderStatusDescEn("Refund in progress");
        orderViewStatusDto.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
        orderViewStatusDto.setRefundStatusText("商家会处理退款申请，请稍后");
        orderViewStatusDto.setButtonContactPartner(true);
    }

    public CreateOrderProductRequest convent2OrderProduct(ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto) {
        CreateOrderProductRequest createOrderProductDemoDto = convent2OrderProductDemo(cartGoodsDetailDto);
        //套餐
        if (cartGoodsDetailDto.getProductType() != null && (cartGoodsDetailDto.getProductType() == ProductType.SETMEALPRODUCT.getCode() || cartGoodsDetailDto.getProductType() == ProductType.SETMEALPRODUCT_UPPRICE.getCode())) {
            List<CreateOrderProductRequest> comboProducts = new ArrayList<>();
            cartGoodsDetailDto.getComboProducts().forEach(product -> {
                product.setUserId(cartGoodsDetailDto.getUserId());
                product.setUserName(cartGoodsDetailDto.getUserName());
                product.setOpenId(cartGoodsDetailDto.getOpenId());
                product.setPhotoUrl(cartGoodsDetailDto.getPhotoUrl());
                comboProducts.add(convent2OrderProductDemo(product));
            });
            createOrderProductDemoDto.setComboProduct(comboProducts);
        }
        //加料商品
        if (cartGoodsDetailDto.getProductType() != null && (cartGoodsDetailDto.getProductType() == ProductType.MATERIALPRODUCT_UPPRICE.getCode())) {
            List<CreateOrderProductRequest> materialProducts = new ArrayList<>();
            cartGoodsDetailDto.getMaterialList().forEach(product -> {
                product.setUserId(cartGoodsDetailDto.getUserId());
                product.setUserName(cartGoodsDetailDto.getUserName());
                product.setOpenId(cartGoodsDetailDto.getOpenId());
                product.setPhotoUrl(cartGoodsDetailDto.getPhotoUrl());
                materialProducts.add(convent2OrderProductMaterial(product));
            });
            createOrderProductDemoDto.setMaterialProduct(materialProducts);
        }
        createOrderProductDemoDto.setProductType(cartGoodsDetailDto.getProductType());
        createOrderProductDemoDto.setOriginalProductType(cartGoodsDetailDto.getOriginalProductType());
        return createOrderProductDemoDto;
    }

    public CreateOrderProductRequest convent2MCCafeOrderProduct(ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto) {
        CreateOrderProductRequest createOrderProductDemoDto = convent2MCCafeOrderProductDemo(cartGoodsDetailDto, cartGoodsDetailDto.getProductType());
        if (cartGoodsDetailDto.getProductType() != null) {
            if (cartGoodsDetailDto.getProductType() == ProductType.SETMEALPRODUCT.getCode()
                    || cartGoodsDetailDto.getProductType() == ProductType.SETMEALPRODUCT_UPPRICE.getCode()) {
//                createOrderProductDemoDto.setPrice(0l);
                //套餐
                List<CreateOrderProductRequest> comboProducts = new ArrayList<>();
                cartGoodsDetailDto.getComboProducts().forEach(product -> {
                    CreateOrderProductRequest createOrderComboProduct = convent2MCCafeOrderProductDemo(product, product.getProductType());
//                    if(!product.getIsFixedProduct()) {
//                        createOrderProductDemoDto.setPrice(createOrderProductDemoDto.getPrice()+product.getOriginalPrice());
//                    }
                    comboProducts.add(createOrderComboProduct);
                    if (CollectionUtils.isNotEmpty(product.getMaterialList())) {
                        //加料商品
                        createOrderComboProduct.setProductType(ProductType.MATERIALPRODUCT_UPPRICE.getCode());
                        List<CreateOrderProductRequest> materialProducts = new ArrayList<>();
                        product.getMaterialList().forEach(cartMaterial -> {
                            materialProducts.add(convent2MCCafeOrderProductDemo(cartMaterial, ProductType.LITTLE_MATERIAL_PRODUCT.getCode()));
                        });
                        createOrderComboProduct.setMaterialProduct(materialProducts);
                    }
                });
                createOrderProductDemoDto.setComboProduct(comboProducts);
            } else if (ProductTypeEnum.VIRTUAL_PRODUCT.getCode().equals(cartGoodsDetailDto.getProductType())) {
                createOrderProductDemoDto.setIsMonthCard(cartGoodsDetailDto.getIsMonthCard());
                createOrderProductDemoDto.setIsB3S1Coupon(cartGoodsDetailDto.getIsB3S1Coupon());
                if (cartGoodsDetailDto.getIsMonthCard() == 1) {
                    createOrderProductDemoDto.setCardId(cartGoodsDetailDto.getMonthCardInfo().getCardNo());
                    createOrderProductDemoDto.setCardCode(cartGoodsDetailDto.getMonthCardInfo().getCardCode());
                } else if (cartGoodsDetailDto.getIsB3S1Coupon() == 1) {
                    createOrderProductDemoDto.setCardId(cartGoodsDetailDto.getB3S1CouponGoodsInfo().getCardNo());
                    createOrderProductDemoDto.setCardCode(cartGoodsDetailDto.getB3S1CouponGoodsInfo().getCardCode());
                }
            }
        }
        if (CollectionUtils.isNotEmpty(cartGoodsDetailDto.getMaterialList())) {
            //加料商品
            createOrderProductDemoDto.setProductType(ProductType.MATERIALPRODUCT_UPPRICE.getCode());
            List<CreateOrderProductRequest> materialProducts = new ArrayList<>();
            cartGoodsDetailDto.getMaterialList().forEach(product -> {
                materialProducts.add(convent2MCCafeOrderProductDemo(product, ProductType.LITTLE_MATERIAL_PRODUCT.getCode()));
            });
            createOrderProductDemoDto.setMaterialProduct(materialProducts);
        }
        return createOrderProductDemoDto;
    }

    private CreateOrderProductRequest convent2OrderProductMaterial(ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto) {
        CreateOrderProductRequest createOrderProductDemoDto = new CreateOrderProductRequest();
        createOrderProductDemoDto.setProductId(cartGoodsDetailDto.getSpuId());
        createOrderProductDemoDto.setProductName(cartGoodsDetailDto.getSpuName());
        createOrderProductDemoDto.setSpecification(cartGoodsDetailDto.getSkuId());
        createOrderProductDemoDto.setSpecificationName(cartGoodsDetailDto.getSkuName());
        createOrderProductDemoDto.setOriginalProductType(cartGoodsDetailDto.getOriginalProductType());
        createOrderProductDemoDto.setPrice(cartGoodsDetailDto.getOriginalPrice());
        createOrderProductDemoDto.setSalePrice(cartGoodsDetailDto.getOriginalPrice());
        createOrderProductDemoDto.setTotalDiscountAmount(cartGoodsDetailDto.getTotalDiscountAmount() == null ? 0 : cartGoodsDetailDto.getTotalDiscountAmount().longValue());
        createOrderProductDemoDto.setNumber(cartGoodsDetailDto.getQty());
        createOrderProductDemoDto.setPicture(cartGoodsDetailDto.getPicture());
        createOrderProductDemoDto.setAddInfo(cartGoodsDetailDto.getAttributeNames());
        createOrderProductDemoDto.setDiscountId(cartGoodsDetailDto.getCouponCode());
        createOrderProductDemoDto.setProductType(cartGoodsDetailDto.getProductType());
        createOrderProductDemoDto.setParentProductId(cartGoodsDetailDto.getParentProductId());
        createOrderProductDemoDto.setIsFixedProduct(cartGoodsDetailDto.getIsFixedProduct());
        createOrderProductDemoDto.setCustomerCode(cartGoodsDetailDto.getCustomerCode());
        //createOrderProductDemoDto.setProductCode(cartGoodsDetailDto.getProductCode());
        createOrderProductDemoDto.setHasStockProudct(cartGoodsDetailDto.isStockLimit());
        createOrderProductDemoDto.setWeight(cartGoodsDetailDto.getWeight());
        createOrderProductDemoDto.setUnit(cartGoodsDetailDto.getUnit());
        createOrderProductDemoDto.setStapleFood(0);
        createOrderProductDemoDto.setClassificationId(cartGoodsDetailDto.getClassificationId());
        createOrderProductDemoDto.setClassificationName(cartGoodsDetailDto.getClassificationName());
        if (CollectionUtils.isNotEmpty(cartGoodsDetailDto.getActivityDiscountsDtos())) {
            createOrderProductDemoDto.setAccounts(getMaterialAccounts(createOrderProductDemoDto, cartGoodsDetailDto));
        }
        return createOrderProductDemoDto;
    }

    public CreateOrderProductRequest convent2OrderProductDemo(ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto) {
        return this.conventCommonOrderProductDemo(cartGoodsDetailDto,null,0);
    }


    /**
     *  公共转换提取
     * @param cartGoodsDetailDto
     * @param productType
     * @param flag 0.平台普通订单 1.麦咖啡
     * @return
     */
    private CreateOrderProductRequest conventCommonOrderProductDemo(ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto, Integer productType, int flag){
        CreateOrderProductRequest createOrderProductDemoDto = new CreateOrderProductRequest();
        createOrderProductDemoDto.setProductId(StringUtils.isNotBlank(cartGoodsDetailDto.getSpuId()) ? cartGoodsDetailDto.getSpuId() : cartGoodsDetailDto.getSkuId());
        createOrderProductDemoDto.setProductName(cartGoodsDetailDto.getSpuName());
        createOrderProductDemoDto.setSpecification(cartGoodsDetailDto.getSkuId());
        createOrderProductDemoDto.setSpecificationName(cartGoodsDetailDto.getSkuName());
        createOrderProductDemoDto.setPrice(cartGoodsDetailDto.getOriginalPrice());
        createOrderProductDemoDto.setSalePrice(cartGoodsDetailDto.getOriginalPrice());
        createOrderProductDemoDto.setTotalDiscountAmount(cartGoodsDetailDto.getTotalDiscountAmount() == null ? 0 : cartGoodsDetailDto.getTotalDiscountAmount().longValue());
        createOrderProductDemoDto.setNumber(cartGoodsDetailDto.getQty());
        createOrderProductDemoDto.setPicture(cartGoodsDetailDto.getPicture());
        createOrderProductDemoDto.setAddInfo(cartGoodsDetailDto.getAttributeNames());
        createOrderProductDemoDto.setDiscountId(cartGoodsDetailDto.getCouponCode());
        createOrderProductDemoDto.setParentProductId(cartGoodsDetailDto.getParentProductId());
        createOrderProductDemoDto.setIsFixedProduct(cartGoodsDetailDto.getIsFixedProduct());
        createOrderProductDemoDto.setCustomerCode(cartGoodsDetailDto.getCustomerCode());
        createOrderProductDemoDto.setProductCode(cartGoodsDetailDto.getProductCode());
        createOrderProductDemoDto.setHasStockProudct(cartGoodsDetailDto.isStockLimit());
        createOrderProductDemoDto.setWeight(cartGoodsDetailDto.getWeight());
        createOrderProductDemoDto.setUnit(cartGoodsDetailDto.getUnit());
        createOrderProductDemoDto.setStapleFood(0);
        createOrderProductDemoDto.setCategory(cartGoodsDetailDto.getClassificationId());
        createOrderProductDemoDto.setTax(cartGoodsDetailDto.getTax());
        createOrderProductDemoDto.setTaxId(cartGoodsDetailDto.getTaxId());
        createOrderProductDemoDto.setClassificationId(cartGoodsDetailDto.getClassificationId());
        createOrderProductDemoDto.setClassificationName(cartGoodsDetailDto.getClassificationName());
        createOrderProductDemoDto.setIsSendGoods(cartGoodsDetailDto.getIsSendGoods());
        createOrderProductDemoDto.setLinkedId(cartGoodsDetailDto.getLinkedId());

        // 买咖啡的逻辑  代码提取
        if (flag == 1) {
            createOrderProductDemoDto.setProductId(cartGoodsDetailDto.getSpuId());
            if (cartGoodsDetailDto.getIsTableware() == 0) {
                createOrderProductDemoDto.setProductType(productType);
            } else {
                createOrderProductDemoDto.setProductType(ProductTypeEnum.TABLEWARE_PRODUCT.getCode());
            }

            createOrderProductDemoDto.setSplitIndex(cartGoodsDetailDto.getSplitIndex());
            createOrderProductDemoDto.setProductGroupId(cartGoodsDetailDto.getProductGroupId());
            if (CollectionUtils.isNotEmpty(cartGoodsDetailDto.getSpecialExtra())) {
                createOrderProductDemoDto.setSpecialAttrs(new ArrayList<>());
                cartGoodsDetailDto.getSpecialExtra().stream().forEach(o -> {
                    createOrderProductDemoDto.getSpecialAttrs().add(new OrderSpecialExtraAttrRequest(o.getAttributeId(), o.getAttributeName(), o.getAttributeForeignName(), o.getSpecialCode()));
                });
            }
        }else {
            createOrderProductDemoDto.setProductForeignName(cartGoodsDetailDto.getSpuForeignName());
            createOrderProductDemoDto.setOriginalProductType(cartGoodsDetailDto.getOriginalProductType());
            createOrderProductDemoDto.setSpecificationForeignName(cartGoodsDetailDto.getSkuForeignName());
            createOrderProductDemoDto.setProductType(cartGoodsDetailDto.getProductType());
            createOrderProductDemoDto.setUserId(cartGoodsDetailDto.getUserId());
            createOrderProductDemoDto.setOpenId(cartGoodsDetailDto.getOpenId());
            createOrderProductDemoDto.setNickName(cartGoodsDetailDto.getUserName());
            createOrderProductDemoDto.setPhotoUrl(cartGoodsDetailDto.getPhotoUrl());
            createOrderProductDemoDto.setPackPrice(cartGoodsDetailDto.getPackPrice());
            createOrderProductDemoDto.setCartGoodsUid(cartGoodsDetailDto.getCartGoodsUid());
            createOrderProductDemoDto.setOriginalGoodsUid(cartGoodsDetailDto.getOriginalGoodsUid());
            createOrderProductDemoDto.setScore(cartGoodsDetailDto.getScore());
            createOrderProductDemoDto.setExtInfo(cartGoodsDetailDto.getExtInfo());
        }

        return createOrderProductDemoDto;
    }

    public CreateOrderProductRequest convent2MCCafeOrderProductDemo(ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto, Integer productType) {
        return this.conventCommonOrderProductDemo(cartGoodsDetailDto,productType,1);
    }

    public CreateOrderProductRequest getMcCafeWithOrderVirtualProduct(ShoppingCartGoodsDto shoppingCartGoodsDto, CreateOrderVo createOrderVo) {
        CreateOrderProductRequest createOrderProductDemoDto = new CreateOrderProductRequest();
        createOrderProductDemoDto.setProductId(mccafeMonthCardGoodsId);
        createOrderProductDemoDto.setProductName("啡常月享卡");
        createOrderProductDemoDto.setSpecification(mccafeMonthCardGoodsId);
        createOrderProductDemoDto.setSpecificationName("啡常月享卡");
        createOrderProductDemoDto.setPrice(shoppingCartGoodsDto.getPayCardFee());
        createOrderProductDemoDto.setSalePrice(shoppingCartGoodsDto.getPayCardFee());
        createOrderProductDemoDto.setTotalDiscountAmount(0l);
        createOrderProductDemoDto.setNumber(1);
        createOrderProductDemoDto.setProductType(ProductTypeEnum.WITH_ORDER_VIRTUAL_PRODUCT.getCode());
        createOrderProductDemoDto.setParentProductId("0");
        createOrderProductDemoDto.setIsFixedProduct(null);
        createOrderProductDemoDto.setCustomerCode(createOrderVo.getCardKeyCode());
        createOrderProductDemoDto.setProductCode(createOrderVo.getCardKeyCode());
        createOrderProductDemoDto.setHasStockProudct(false);
        createOrderProductDemoDto.setWeight(0d);
        createOrderProductDemoDto.setStapleFood(0);
        createOrderProductDemoDto.setTax(0d);
        createOrderProductDemoDto.setTaxId("");
        createOrderProductDemoDto.setCardId(withOrderBuyCardId);
        createOrderProductDemoDto.setCardCode(withOrderBuyCouponCode);
        return createOrderProductDemoDto;
    }

    /**
     * 将促销的枚举 ActivityTypeEnum 和orderAccountType 关联映射
     */
    public OldOrderAccountType getOrderAccountType(Integer activityType) {
        if (ActivityTypeEnum.TYPE_1.getCode().equals(activityType) || ActivityTypeEnum.TYPE_11.getCode().equals(activityType) || ActivityTypeEnum.TYPE_12.getCode().equals(activityType) || ActivityTypeEnum.TYPE_13.getCode().equals(activityType)) {
            return OldOrderAccountType.BUY_DISCOUNT;
        }
        if (ActivityTypeEnum.TYPE_3.getCode().equals(activityType)) {
            return OldOrderAccountType.COUPON;
        }
        if (ActivityTypeEnum.TYPE_2.getCode().equals(activityType) || ActivityTypeEnum.TYPE_21.getCode().equals(activityType)) {
            return OldOrderAccountType.DISCOUNT_AMOUNT;
        }
        if (ActivityTypeEnum.TYPE_81.getCode().equals(activityType)) {
            return OldOrderAccountType.PREMIUM_EXCHANGE;
        }
        if (ActivityTypeEnum.TYPE_32.getCode().equals(activityType)) {
            return OldOrderAccountType.PRODUCT_COUPON;
        }
        if (ActivityTypeEnum.TYPE_35.getCode().equals(activityType)) {
            return OldOrderAccountType.PRODUCT_COUPON;
        }
        if (ActivityTypeEnum.TYPE_38.getCode().equals(activityType)) {
            return OldOrderAccountType.PRODUCT_COUPON;
        }
        if (ActivityTypeEnum.TYPE_37.getCode().equals(activityType)) {
            return OldOrderAccountType.SEED_PRODUCT_COUPON;
        }
        if (ActivityTypeEnum.TYPE_34.getCode().equals(activityType)) {
            return OldOrderAccountType.FREIGHT_COUPON;
        }
        if (ActivityTypeEnum.TYPE_31.getCode().equals(activityType)) {
            return OldOrderAccountType.DISCOUNT_COUPON;
        }
        if (ActivityTypeEnum.TYPE_39.getCode().equals(activityType)) {
            return OldOrderAccountType.EVM_PRODUCT_COUPON;
        }
        if (ActivityTypeEnum.TYPE_PACKAGE.getCode().equals(activityType)) {
            return OldOrderAccountType.PACK_AMOUNT;
        }
        if (ActivityTypeEnum.TYPE_DELIVERY.getCode().equals(activityType)) {
            return OldOrderAccountType.DELIVERY_AMOUNT;
        }
        if (ActivityTypeEnum.TYPE_61.getCode().equals(activityType)) {
            return OldOrderAccountType.BUYM_SENDN;
        }
        if (ActivityTypeEnum.TYPE_53.getCode().equals(activityType)) {
            return OldOrderAccountType.SECOND_DISCOUNT;
        }
        if (ActivityTypeEnum.TYPE_211.getCode().equals(activityType)) {
            return OldOrderAccountType.SET_MEAL;
        }
        if (ActivityTypeEnum.TYPE_104.getCode().equals(activityType)) {
            return OldOrderAccountType.XY_DISCOUNT;
        }
        if (ActivityTypeEnum.TYPE_14.getCode().equals(activityType)) {
            return OldOrderAccountType.FULL_DISTRIBUTION_FEE;
        }
        if (ActivityTypeEnum.TYPE_320.getCode().equals(activityType)) {
            return OldOrderAccountType.MEMBER_PRICE_DISCOUNT;
        }
        if (ActivityTypeEnum.TYPE_27.getCode().equals(activityType)) {
            return OldOrderAccountType.MEMBER_PRICE_DISCOUNT;
        }
        if (ActivityTypeEnum.TYPE_23.getCode().equals(activityType)) {
            return OldOrderAccountType.SUPER_PURCHASE;
        }
        if (ActivityTypeEnum.TYPE_221.getCode().equals(activityType)) {
            return OldOrderAccountType.GATHER_SPOT;
        }
        if (ActivityTypeEnum.TYPE_22.getCode().equals(activityType)) {
            return OldOrderAccountType.SINGLE_PRODUCT_REDUCTION;
        }

        // coco商品代金券
        if (ActivityTypeEnum.TYPE_36.getCode().equals(activityType)) {
            return OldOrderAccountType.COCO_PRODUCT_CASH_COUPON;
        }
        if (ActivityTypeEnum.TYPE_230.getCode().equals(activityType)) {
            return OldOrderAccountType.FULL_BUYM_SENDN;
        }
        if (ActivityTypeEnum.TYPE_231.getCode().equals(activityType)) {
            return OldOrderAccountType.MONTH_CARD_TOTAL_DISCOUNT;
        }
        if (ActivityTypeEnum.TYPE_83.getCode().equals(activityType)) {
            return OldOrderAccountType.FULL_M_COUNT_N_FOLD;
        }
        if (ActivityTypeEnum.TYPE_28.getCode().equals(activityType)) {
            return OldOrderAccountType.SCORE_PRODUCT_ACTIVITY;
        }
        return OldOrderAccountType.BUYM_SENDN;
    }


    /**
     * 获取订单类型转换后 枚举
     *
     * @param oldOrderType
     * @return
     */
//    public OrderTypeV1 convent2OrderTypeEnum(Integer oldOrderType) {
//
//        if (OrderTypeV1.TAKE_OUT.getCode().equals(oldOrderType)) {
//            return OrderTypeV1.TAKE_OUT;
//        }
//        if (OrderTypeV1.COLLECT_GOODS.getCode().equals(oldOrderType)) {
//            return OrderTypeV1.COLLECT_GOODS;
//        }
//        if (OrderTypeV1.EAT_IN.getCode().equals(oldOrderType)) {
//            return OrderTypeV1.EAT_IN;
//        }
//        return null;
//    }

    /**
     * 获取聚合订单活动类型
     */
    public QueryOrderAccountType getQueryOrderAccountType(OldOrderAccountType oldOrderAccountType) {
        return QueryOrderAccountType.getByCode(oldOrderAccountType.getMessage());
    }



    public UnifiedOrderRequest convent2UnifiedOrderRequest(OrderBeanV1 orderBean, PaymentRequest paymentRequest, Long amount, Integer cardAmount, String transId) {
        return convent2UnifiedOrderRequest(new UnifiedOrderCom(orderBean, paymentRequest, amount, cardAmount, transId, null));
    }

    /**
     * 支付信息转换
     */
    public UnifiedOrderRequest convent2UnifiedOrderRequest(UnifiedOrderCom com) {
        OrderBeanV1 orderBean = com.getOrderBean();
        PaymentRequest paymentRequest =com.getPaymentRequest();
        Long amount = com.getAmount();
        Integer cardAmount = com.getCardAmount();
        String transId =com.getTransId();
        String partnerPayOvertime = com.getPartnerPayOvertime();


        UnifiedOrderRequest orderPayDto = new UnifiedOrderRequest();
        orderPayDto.setPartnerId(orderBean.getCompanyId());
        orderPayDto.setBody(paymentRequest.getPrincipalName());
        orderPayDto.setNotifyUrl(paymentRequest.getReverseNotifyiDcUrl());
        orderPayDto.setStoreId(orderBean.getShopId());
        orderPayDto.setTransId(transId);
        orderPayDto.setOpenId(paymentRequest.getOpenId());
        String businessDate = DateUtil.convert2String(new Date(), "yyyyMMdd");
        orderPayDto.setBusinessDate(businessDate);
        orderPayDto.setAmount(amount);
        orderPayDto.setUndisAmount(1L);
        orderPayDto.setVipAmount(Long.valueOf(cardAmount));
        orderPayDto.setAppId(paymentRequest.getWxAppId());
        orderPayDto.setPayTimeOutTime(StringUtils.defaultIfBlank(partnerPayOvertime, "30"));
        List<PayProductDto> productBeans = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orderBean.getProductList())) {
            orderBean.getProductList().forEach(orderProductBean -> {
                PayProductDto productBean = new PayProductDto();
                productBean.setPid(orderProductBean.getProductId());
                productBean.setConsumeNum(orderProductBean.getNumber());
                productBean.setSeq(orderProductBean.getSequence());
                productBean.setSalesType("NORMAL");
                productBean.setPrice(orderProductBean.getPrice());
                productBean.setName(orderProductBean.getProductName());
                productBeans.add(productBean);
            });
        }
        orderPayDto.setProducts(productBeans);
        orderPayDto.setPayCode(paymentRequest.getPayCode());
        //抖音支付的payCode = 10066
        if (OrderClientType.TIKTOKPAY.getIndex().toString().equalsIgnoreCase(orderBean.getOrderClient())) {
            orderPayDto.setPayCode(PayChannelType.TIKTOKPAY.getEbcode());
        }
        orderPayDto.setFoodOrderType(getFoodOrderType(orderBean.getOrderType()));
//        orderPayDto.setMerchantDiscount(orderBean.getOriginalAmount().longValue()-orderBean.getAmount());

        return orderPayDto;
    }

    /**
     * 麦咖啡支付信息转换
     */
    public UnifiedOrderRequest convent2MCCafeUnifiedOrderRequest(OrderBeanV1 orderBean, PaymentRequest paymentRequest, Long amount, Integer cardAmount, String transId, String partnerPayOvertime) {
        UnifiedOrderRequest orderPayDto = new UnifiedOrderRequest();
        orderPayDto.setPartnerId(orderBean.getCompanyId());
        orderPayDto.setBody(paymentRequest.getPrincipalName());
        orderPayDto.setNotifyUrl(paymentRequest.getReverseNotifyiDcUrl());
        orderPayDto.setStoreId(orderBean.getShopId());
        orderPayDto.setTransId(transId);
        orderPayDto.setOpenId(paymentRequest.getOpenId());
        String businessDate = com.freemud.application.sdk.api.util.DateUtil.convert2String(new Date(), "yyyyMMdd");
        orderPayDto.setBusinessDate(businessDate);
        orderPayDto.setAmount(amount);
        orderPayDto.setUndisAmount(1L);
        orderPayDto.setVipAmount(Long.valueOf(cardAmount));
        orderPayDto.setAppId(paymentRequest.getWxAppId());
        orderPayDto.setPayTimeOutTime(StringUtils.defaultIfBlank(partnerPayOvertime, "30"));
        List<PayProductDto> productBeans = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orderBean.getProductList())) {
            orderBean.getProductList().forEach(orderProductBean -> {
                PayProductDto productBean = new PayProductDto();
                productBean.setPid(orderProductBean.getSpecification());
                productBean.setConsumeNum(orderProductBean.getNumber());
                productBean.setSeq(orderProductBean.getSequence());
                productBean.setSalesType("NORMAL");
                productBean.setPrice(orderProductBean.getPrice());
                productBean.setName(orderProductBean.getProductName());
                productBeans.add(productBean);
            });
        }
        orderPayDto.setProducts(productBeans);
        orderPayDto.setPayCode(paymentRequest.getPayCode());
        orderPayDto.setFoodOrderType(getFoodOrderType(orderBean.getOrderType()));
        return orderPayDto;
    }


    /**
     * 预支付接口获取类型
     *
     * @return
     */
    public String getFoodOrderType(Integer orderType) {
        //1=外卖 4=自提，5=堂食
        //qr_order（店内扫码点餐）,pre_order（预点到店自提）,home_delivery （外送到家）
        String foodOrderType;
        switch (orderType) {
            case 1:
                foodOrderType = "home_delivery";
                break;
            case 4:
                foodOrderType = "pre_order";
                break;
            case 5:
            default:
                foodOrderType = "qr_order";
                break;
        }
        return foodOrderType;
    }

    public OrderPayResponse getOrderPayResponse(String partnerId, PaymentRequest paymentRequest, String orderId, String fmId) {
        OrderPayResponse orderPayResponse = new OrderPayResponse();
        orderPayResponse.setWxAppid(paymentRequest.getWxAppId());
        orderPayResponse.setOpenId(paymentRequest.getOpenId());
        orderPayResponse.setPartnerId(partnerId);
        orderPayResponse.setOrderId(orderId);
        orderPayResponse.setFmId(fmId);
        orderPayResponse.setPayChannelType(PayChannelType.ZERO);
        return orderPayResponse;
    }

    /**
     * 父子订单转换前端支付需要的信息
     *
     * @param orderPayResponse
     * @param
     * @return
     */
    public CreateOrderResponseVo convent2CreateFatherSonOrderResponseVo(OrderPayResponse orderPayResponse, OrderBeanV1 orderBean) {
        CreateOrderResponseVo createOrderResponseVo = new CreateOrderResponseVo();
        createOrderResponseVo.setOid(orderBean.getOid());
        createOrderResponseVo.setWxappId(orderPayResponse.getWxAppid());
        createOrderResponseVo.setFmId(orderPayResponse.getFmId());
        createOrderResponseVo.setPayId(orderPayResponse.getPayId());
        OrderPayResponse.PayOrderBean payOrderBean = orderPayResponse.getPayOrder();
        //  腾讯有数数据上报 时间戳不能为空
        createOrderResponseVo.setTimestamp(payOrderBean == null ? Instant.now().getEpochSecond() + "" : payOrderBean.getTimestamp());
        createOrderResponseVo.setNonceStr(payOrderBean == null ? "" : payOrderBean.getNonceStr());
        createOrderResponseVo.setPackageX(payOrderBean == null ? "" : payOrderBean.getPackageX());
        createOrderResponseVo.setSignType(payOrderBean == null ? "" : payOrderBean.getSignType());
        createOrderResponseVo.setSign(payOrderBean == null ? "" : payOrderBean.getSign());
        //微信新版订阅消息判断新加字段
        if (orderBean != null && orderBean.getOrderType() != null) {
            createOrderResponseVo.setOrderType(getNewOrderType(orderBean.getOrderType(), orderBean.getGmtExpect()));
        }
        createOrderResponseVo.setOrderStr(payOrderBean == null ? "" : payOrderBean.getAliPayOrder());
        //抖音支付添加返回OrderInfo
        if (String.valueOf(PayChannelType.TIKTOKPAY.getIndex()).equals(orderBean.getPayChannelType())) {
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrder_id(orderPayResponse.getThirdOrderId());
            orderInfo.setOrder_token(orderPayResponse.getThirdOrderToken());
            createOrderResponseVo.setOrderInfo(orderInfo);
        }
        //createOrderResponseVo.setOutTradeNo(orderPayResponse.getEndTransId());
        // 随行付支付通道返回的endTransId无法满足一元捐插件，支付接口新增返回channelPayId字段作为商户单号使用
        createOrderResponseVo.setOutTradeNo(orderPayResponse.getChannelPayId());

        return createOrderResponseVo;
    }

    public CreateOrderResponseVo convent2CreateFatherSonOrderNoPayResponseVo(OrderBeanV1 orderBean) {
        CreateOrderResponseVo createOrderResponseVo = new CreateOrderResponseVo();
        createOrderResponseVo.setOid(orderBean.getOid());
        createOrderResponseVo.setWxappId("");
        createOrderResponseVo.setFmId("");
        createOrderResponseVo.setTimestamp("");
        createOrderResponseVo.setNonceStr("");
        createOrderResponseVo.setPackageX("");
        createOrderResponseVo.setSignType("");
        createOrderResponseVo.setSign("");
        //微信新版订阅消息判断新加字段
        if (orderBean != null && orderBean.getOrderType() != null) {
            createOrderResponseVo.setOrderType(getNewOrderType(orderBean.getOrderType(), orderBean.getGmtExpect()));
        }
        createOrderResponseVo.setOrderStr("");
        createOrderResponseVo.setPaySuccess(false);
        return createOrderResponseVo;
    }

//    public OrderPayResponse convent2OrderPayResponse(UnifiedOrderResponse unifiedOrderResponse) {
//        OrderPayResponse responseDto = new OrderPayResponse();
//        responseDto.setFmId(unifiedOrderResponse.getFmId());
//        responseDto.setMsg(unifiedOrderResponse.getMsg());
//        responseDto.setPayEbcode(unifiedOrderResponse.getPayEbcode());
//        responseDto.setPayId(unifiedOrderResponse.getPayId());
//        PayOrderDto payOrderBean = unifiedOrderResponse.getPayOrder();
//        if (null != payOrderBean) {
//            OrderPayResponse.PayOrderBean payBean = new OrderPayResponse.PayOrderBean();
//            payBean.setAppid(payOrderBean.getAppid());
//            payBean.setNonceStr(payOrderBean.getNonceStr());
//            payBean.setPackageX(payOrderBean.getPackageX());
//            payBean.setSign(payOrderBean.getPaySign());
//            payBean.setSignType(payOrderBean.getSignType());
//            payBean.setTimestamp(payOrderBean.getTimestamp());
//            payBean.setAliPayOrder(payOrderBean.getAliPayOrder());
//            responseDto.setPayOrder(payBean);
//            // coco 机场支付
//            try {
//                JSONObject jsonObject = JSONObject.parseObject(payOrderBean.getAliPayOrder());
//                responseDto.setSellerId(jsonObject.getString("sellerId"));
//                responseDto.setPayNotifyUrl(jsonObject.getString("payNotifyUrl"));
//                responseDto.setEbCode(jsonObject.getString("ebCode"));
//            } catch (Exception e) {
//
//            }
//        }
//        responseDto.setStatusCode(unifiedOrderResponse.getStatusCode());
//        responseDto.setPayTransId(unifiedOrderResponse.getPayTransId());
//        responseDto.setThirdOrderToken(unifiedOrderResponse.getOrderToken());
//        responseDto.setThirdOrderId(unifiedOrderResponse.getOrderId());
//        return responseDto;
//    }

    /**
     * 订单信息转换
     *
     * @param queryOrderResponseVo
     * @return
     */
    public PreviewOrderInfoVo conventQueryOrderByIdResponse(QueryOrderResponseVo queryOrderResponseVo) {
        PreviewOrderInfoVo previewOrderInfoVo = new PreviewOrderInfoVo();
        if (CollectionUtils.isNotEmpty(queryOrderResponseVo.getProducts())) {
            List<ProductVo> products = Optional.ofNullable(queryOrderResponseVo.getProducts().stream().filter(var -> ObjectUtils.notEqual(var.getProductType(), ProductTypeEnum.TABLEWARE_PRODUCT.getCode())).collect(Collectors.toList())).orElse(new ArrayList<>());

            //赋值商品是否称重
            products.stream().filter(var ->
                    (ProductTypeEnum.WEIGHT_PRODUCT.getCode().equals(var.getProductType())
                            && (var.getWeight() == null || var.getWeight() <= 0))).forEach(each -> {
                each.setWeightType(false);
                each.setOriginalTotalAmount(0L);
                each.setSaleTotalAmount(0L);
            });
            products.stream().filter(var ->
                    (ProductTypeEnum.SETMEAL_PRODUCT.getCode().equals(var.getProductType()) || ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode().equals(var.getProductType()))).forEach(each -> {
                if (CollectionUtils.isNotEmpty(each.getSetMealProducts())) {
                    each.getSetMealProducts().stream().filter(setMeal ->
                            (ProductTypeEnum.WEIGHT_PRODUCT.getCode().equals(setMeal.getProductType())
                                    && (setMeal.getWeight() == null || setMeal.getWeight() <= 0))).forEach(setMealProduct -> {
                        setMealProduct.setWeightType(false);
                        each.setWeightType(false);
                        setMealProduct.setSaleTotalAmount(0L);
                        setMealProduct.setOriginalTotalAmount(0L);
                        each.setOriginalTotalAmount(0L);
                        each.setSaleTotalAmount(0L);
                    });
                }
            });
            List<ProductVo> tableWareProducts = queryOrderResponseVo.getProducts().stream()
                    .filter(var -> ObjectUtils.equals(var.getProductType(), ProductTypeEnum.TABLEWARE_PRODUCT.getCode())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(tableWareProducts)) {
                Long warePrice = tableWareProducts.stream().mapToLong(var -> var.getFinalPrice()).sum();
                ProductVo wareProductVo = new ProductVo();
                wareProductVo.setName("餐具");
                wareProductVo.setForeignName("tableware");
                wareProductVo.setSpuName("餐具");
                wareProductVo.setSpuForeignName("tableware");
                wareProductVo.setProductType(ProductTypeEnum.TABLEWARE_PRODUCT.getCode());
                wareProductVo.setQty(tableWareProducts.get(0).getQty());
                wareProductVo.setSaleTotalAmount(warePrice * tableWareProducts.get(0).getQty());
                wareProductVo.setOriginalTotalAmount(tableWareProducts.stream().mapToLong(ProductVo::getOriginalPrice).sum());
                wareProductVo.setSequence(0);
                products.add(wareProductVo);
            }
            products.sort(Comparator.comparing(ProductVo::getSequence).reversed());
            previewOrderInfoVo.setProducts(products);
            previewOrderInfoVo.setProductNum(queryOrderResponseVo.getProducts().stream().mapToInt(ProductVo::getQty).sum());
        }
        previewOrderInfoVo.setOid(queryOrderResponseVo.getOid());
        previewOrderInfoVo.setTableNumber(queryOrderResponseVo.getTableNumber());
        previewOrderInfoVo.setAmount(queryOrderResponseVo.getAmount());
        previewOrderInfoVo.setItemAmount(queryOrderResponseVo.getItemAmount());
        previewOrderInfoVo.setDiscountTotalAmount(queryOrderResponseVo.getDiscountTotalAmount());
        previewOrderInfoVo.setOrderStatus(queryOrderResponseVo.getOrderStatus());
        previewOrderInfoVo.setOrderStatusDesc(queryOrderResponseVo.getOrderStatusDesc());
        previewOrderInfoVo.setOrderStatusDescEn(queryOrderResponseVo.getOrderStatusDescEn());
        previewOrderInfoVo.setPayStatus(queryOrderResponseVo.getPayStatus());
        previewOrderInfoVo.setPayStatusDesc(queryOrderResponseVo.getPayStatusDesc());
        previewOrderInfoVo.setPayStatusDescEn(queryOrderResponseVo.getPayStatusDescEn());
        previewOrderInfoVo.setShopName(queryOrderResponseVo.getShopName());
        previewOrderInfoVo.setShopNameEn(queryOrderResponseVo.getShopNameEn());

        previewOrderInfoVo.setFullDiscount(queryOrderResponseVo.getFullDiscountAmount());
        previewOrderInfoVo.setCustomerScoreAmount(queryOrderResponseVo.getCustomerScoreAmount());
        if (queryOrderResponseVo.getCouponInfo() != null) {
            previewOrderInfoVo.setCouponDiscount(queryOrderResponseVo.getCouponInfo().getCouponAmount());
        }
        return previewOrderInfoVo;
    }

    /**
     * 购物车信息转换
     */
    public AssortmentSdkUpdateOrderProductInfoRequest conventShoppingCartGoodsDtoByUpdate(ShoppingCartGoodsDto shoppingCartGoodsDto,
                                                                                          AssortmentCustomerInfoVo assortmentCustomerInfoVo, String orderId, Integer dinersNumber, String nickName, boolean isUpdateAccounts) {
        AssortmentSdkUpdateOrderProductInfoRequest orderProductInfoRequest = new AssortmentSdkUpdateOrderProductInfoRequest();
        orderProductInfoRequest.setPartnerId(assortmentCustomerInfoVo.getPartnerId());
        orderProductInfoRequest.setStoreId(assortmentCustomerInfoVo.getStoreId());
        orderProductInfoRequest.setOrderClient(OrderClientType.WAI_MEAL.getIndex());
        orderProductInfoRequest.setOrderCode(orderId);
        orderProductInfoRequest.setDinersNumber(dinersNumber);
        orderProductInfoRequest.setOpUpdateOrderItemEnum(AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.update);
        List<CreateOrderProductRequest> createOrderProductRequests = new ArrayList<>();
        List<ShoppingCartGoodsDto.CartGoodsDetailDto> cartGoodsDetailDtos = CollectionUtils.isNotEmpty(shoppingCartGoodsDto.getProducts()) ? shoppingCartGoodsDto.getProducts() : new ArrayList<>();
        for (ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto : cartGoodsDetailDtos) {
            Integer qty = cartGoodsDetailDto.getQty();
            if (qty > 0) {
                // 当存在sku是取sku,不取spu
                if (StringUtils.isNotEmpty(cartGoodsDetailDto.getSkuId())) {
                    cartGoodsDetailDto.setSpuId(cartGoodsDetailDto.getSkuId());
                }
                CreateOrderProductRequest createOrderProductDto = convent2OrderProduct(cartGoodsDetailDto);
                createOrderProductDto.setIgnoreProductPrice(1);
                createOrderProductRequests.add(createOrderProductDto);
            }
        }
        orderProductInfoRequest.setOrderItemList(createOrderProductRequests);
        orderProductInfoRequest.setOperator(nickName);
        orderProductInfoRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        orderProductInfoRequest.setUpdateAccounts(isUpdateAccounts);
        return orderProductInfoRequest;
    }

    /**
     * 转换促销信息--修改订单及商品金额
     *
     * @param shoppingCartGoodsResponse
     * @param queryOrderByIdResponse
     * @return
     */
    public AssortmentSdkUpdateOrderProductInfoRequest conventShoppingPromotionInfo(ShoppingCartGoodsResponse shoppingCartGoodsResponse, QueryOrderByIdResponse queryOrderByIdResponse,
                                                                                   AssortmentCustomerInfoVo assortmentCustomerInfoVo, boolean isUpdateAccounts, CreateReserveOrderVo createReserveOrderVo, Boolean prePayLock) {
        AssortmentSdkUpdateOrderProductInfoRequest sdkUpdateOrderProductInfoRequest = new AssortmentSdkUpdateOrderProductInfoRequest();
        sdkUpdateOrderProductInfoRequest.setStoreId(queryOrderByIdResponse.getData().getShopId());
        sdkUpdateOrderProductInfoRequest.setPartnerId(queryOrderByIdResponse.getData().getCompanyId());
        sdkUpdateOrderProductInfoRequest.setOrderCode(queryOrderByIdResponse.getData().getOid());
        sdkUpdateOrderProductInfoRequest.setOrderClient(OrderClientType.WAI_MEAL.getIndex());
        if (prePayLock) {
            sdkUpdateOrderProductInfoRequest.setOpUpdateOrderItemEnum(AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.updatePrePayPriceTwo);
        } else {
            sdkUpdateOrderProductInfoRequest.setOpUpdateOrderItemEnum(AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.updatePrePayPrice);
        }
        sdkUpdateOrderProductInfoRequest.setThirdOrderCode(queryOrderByIdResponse.getData().getThirdOrderCode());
        if (shoppingCartGoodsResponse != null) {
            sdkUpdateOrderProductInfoRequest.setActualPayAmount(shoppingCartGoodsResponse.getTotalAmount());
            sdkUpdateOrderProductInfoRequest.setOriginalAmount(shoppingCartGoodsResponse.getOriginalTotalAmount());
            sdkUpdateOrderProductInfoRequest.setSettlementAmount(shoppingCartGoodsResponse.getTotalAmount());
        }
        sdkUpdateOrderProductInfoRequest.setUserId(assortmentCustomerInfoVo.getMemberId());
        sdkUpdateOrderProductInfoRequest.setUserName(assortmentCustomerInfoVo.getNickName());
        sdkUpdateOrderProductInfoRequest.setOperator(assortmentCustomerInfoVo.getNickName());
        sdkUpdateOrderProductInfoRequest.setAccounts(new ArrayList<>());
        sdkUpdateOrderProductInfoRequest.setUpdateAccounts(isUpdateAccounts);
        sdkUpdateOrderProductInfoRequest.setMenuType(BusinessTypeEnum.SAAS_WC.getCode());
        if (StringUtils.isNotBlank(createReserveOrderVo.getCardCode())) {
            sdkUpdateOrderProductInfoRequest.setPayChannel("10102");
            sdkUpdateOrderProductInfoRequest.setPayChannelName("储值卡支付");
        }
        //支付类型，1：线上支付，2：线下支付
        sdkUpdateOrderProductInfoRequest.setPayType(1);

        //商品信息
        List<CreateOrderProductRequest> createOrderProductRequests = new ArrayList<>();
        if (shoppingCartGoodsResponse != null && CollectionUtils.isNotEmpty(shoppingCartGoodsResponse.getProducts())) {
            queryOrderByIdResponse.getData().getProductList().forEach(each -> {
                shoppingCartGoodsResponse.getProducts().forEach(carEach -> {
                    if (ObjectUtils.equals(each.getProductId(), carEach.getProductId()) && each.getSequence() == carEach.getSequence()) {
                        createOrderProductRequests.add(this.conventOrderInfoAndCarInfoByUpdate(each, carEach));
                    }
                });
            });
        }
        sdkUpdateOrderProductInfoRequest.setOrderItemList(createOrderProductRequests);

        // 解析购物车信息
        List<ShoppingCartGoodsResponse.CartGoodsDetailDto> cartGoodsDetailDtos = (shoppingCartGoodsResponse == null || CollectionUtils.isEmpty(shoppingCartGoodsResponse.getProducts()))
                ? new ArrayList<>() : shoppingCartGoodsResponse.getProducts();
        List<ActivityDiscountsDto> activityDiscountsDtos = (shoppingCartGoodsResponse == null || CollectionUtils.isEmpty(shoppingCartGoodsResponse.getActivityDiscountsDtos()))
                ? new ArrayList<>() : shoppingCartGoodsResponse.getActivityDiscountsDtos();
        // 根据购物车商品信息获取优惠信息
        int orderAccountIndex = 0;
        for (ShoppingCartGoodsResponse.CartGoodsDetailDto cartGoodsDetailDto : cartGoodsDetailDtos) {
            Integer qty = cartGoodsDetailDto.getQty();
            if (qty > 0) {
                CreateOrderProductRequest createOrderProductRequest = createOrderProductRequests.stream().filter(t -> Objects.equals(t.getProductId(), cartGoodsDetailDto.getProductId()) && Objects.equals(t.getSequence(), cartGoodsDetailDto.getSequence())).findFirst().orElse(null);
                if (createOrderProductRequest != null) {
                    createOrderProductRequest.setIgnoreProductPrice(1);
                }
                if (CollectionUtils.isNotEmpty(cartGoodsDetailDto.getActivityDiscountsDtos()) && createOrderProductRequest != null) {
                    createOrderProductRequest.setAccounts(getAccounts(createOrderProductRequest, cartGoodsDetailDto.getActivityDiscountsDtos()));
                }
            }
        }
        for (ActivityDiscountsDto activityDiscountsDto : activityDiscountsDtos) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId(activityDiscountsDto.getActivityCode())
                    .name(activityDiscountsDto.getActivityName())
                    .price(activityDiscountsDto.getDiscountAmount().longValue())
                    .accountType(getQueryOrderAccountType(getOrderAccountType(activityDiscountsDto.getActivityType())))
                    .sequence(orderAccountIndex++)
                    .build();
            sdkUpdateOrderProductInfoRequest.getAccounts().add(createOrderAccountDto);
        }


        if (shoppingCartGoodsResponse != null) {
            Long scoreReduceAmount = shoppingCartGoodsResponse.getScoreReduceAmount() != null ? shoppingCartGoodsResponse.getScoreReduceAmount() : 0;
            if (scoreReduceAmount > 0 && CustomerScoreConstant.SUBSTRACT.getValue().equals(createReserveOrderVo.getUseCustomerScore())) {
                Integer reduceScore = shoppingCartGoodsResponse.getReduceScore() != null ? shoppingCartGoodsResponse.getReduceScore().intValue() : 0;
                CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                        .accountId("")
                        .name("积分扣减")
                        .price(0 - scoreReduceAmount)
                        .accountType(getQueryOrderAccountType(OldOrderAccountType.getByCode(OrderAccountType.CUSTOMER_SUB.getCode())))
                        .sequence(orderAccountIndex++)
                        .build();
                sdkUpdateOrderProductInfoRequest.getAccounts().add(createOrderAccountDto);
            }
        }
        // update by miaohui 20201030 for 【ID1018638】【C端服务端】活动库存接口调整对接
        ActivityUpdateStockRequest activityUpdateStockRequest = this.initActivityUpdateStockRequest(activityDiscountsDtos);


        //设置库存扣减
        List<SubtractStockVO> stocks = this.getStocks(shoppingCartGoodsResponse.getStocks());
        activityUpdateStockRequest.setStock(stocks);
        sdkUpdateOrderProductInfoRequest.setActivityUpdateStockRequest(activityUpdateStockRequest);
        return sdkUpdateOrderProductInfoRequest;
    }

    private CreateOrderProductRequest conventOrderInfoAndCarInfoByUpdate(ProductBeanV1 productBean, ShoppingCartGoodsResponse.CartGoodsDetailDto cartGoodsDetailDto) {
        CreateOrderProductRequest createOrderProductRequest = new CreateOrderProductRequest();
        createOrderProductRequest.setId(productBean.getId());
        createOrderProductRequest.setProductId(productBean.getProductId());
        createOrderProductRequest.setProductName(productBean.getProductName());
        createOrderProductRequest.setSpecification(productBean.getSpecification());
        createOrderProductRequest.setSequence(productBean.getSequence());
        createOrderProductRequest.setSpecificationName(productBean.getSpecificationName());
        createOrderProductRequest.setNumber(productBean.getNumber());
        createOrderProductRequest.setPrice(productBean.getPrice());
        createOrderProductRequest.setTotalDiscountAmount(cartGoodsDetailDto.getTotalDiscountAmount().longValue());
        createOrderProductRequest.setSalePrice((productBean.getPrice() * productBean.getNumber()) - cartGoodsDetailDto.getTotalDiscountAmount());
        if (CollectionUtils.isNotEmpty(productBean.getComboProduct()) && CollectionUtils.isNotEmpty(cartGoodsDetailDto.getComboList())) {
            List<CreateOrderProductRequest> createOrderComProductRequests = new ArrayList<>();
            productBean.getComboProduct().forEach(comEach -> {
                cartGoodsDetailDto.getComboList().forEach(comCarEach -> {
                    if (ObjectUtils.equals(comEach.getProductId(), comCarEach.getProductId()) && comEach.getSequence() == comCarEach.getSequence()) {
                        createOrderComProductRequests.add(this.conventOrderInfoAndCarInfoByUpdate(comEach, comCarEach));
                    }
                });
            });
            createOrderProductRequest.setComboProduct(createOrderComProductRequests);
        }
        return createOrderProductRequest;
    }

    /**
     * 订单详细信息转换
     *
     * @return
     */
    public QueryTableStatusReponseVo conventTableStatusInfoByOrderInfo(QueryOrderByIdResponse queryOrderByIdResponse) {
        QueryTableStatusReponseVo queryTableStatusReponseVo = new QueryTableStatusReponseVo();
        queryTableStatusReponseVo.setOid(queryOrderByIdResponse.getData().getOid());
        queryTableStatusReponseVo.setTableNumber(queryOrderByIdResponse.getData().getBarCounter());
        queryTableStatusReponseVo.setProductNum(queryOrderByIdResponse.getData().getProductList().stream().mapToInt(ProductBeanV1::getNumber).sum());
        queryTableStatusReponseVo.setPayStatus(queryOrderByIdResponse.getData().getPayStatus());
        queryTableStatusReponseVo.setCreateOrderTime(yyyyMMddHHmmss.format(new Date(queryOrderByIdResponse.getData().getGmtCreate())));
        queryTableStatusReponseVo.setStoreId(queryOrderByIdResponse.getData().getShopId());
        return queryTableStatusReponseVo;
    }

    /**
     * 转换促销数据
     *
     * @param orderBean
     * @return
     */
    public OrderBeanRequest conventOrderBeanRequest(OrderBeanV1 orderBean, AssortmentCustomerInfoVo assortmentCustomerInfoVo, CreateReserveOrderVo createReserveOrderVo) {
        OrderBeanRequest orderBeanRequest = new OrderBeanRequest();
        orderBeanRequest.setCompanyId(orderBean.getCompanyId());
        orderBeanRequest.setShopId(orderBean.getShopId());
        orderBeanRequest.setAmount(orderBean.getAmount());
        orderBeanRequest.setUserId(assortmentCustomerInfoVo.getMemberId());
        orderBeanRequest.setAppId(assortmentCustomerInfoVo.getWxAppId());
        orderBeanRequest.setOrderType(orderBean.getOrderType());
        orderBeanRequest.setPartnerId(assortmentCustomerInfoVo.getPartnerId());
        orderBeanRequest.setUseCustomerScore(createReserveOrderVo.getUseCustomerScore());

        List<OrderBeanRequest.ProductBean> list = new ArrayList<>();
        orderBean.getProductList().forEach(var -> {
            OrderBeanRequest.ProductBean productBean = new OrderBeanRequest.ProductBean();
            productBean.setAddInfo(var.getAddInfo());
            productBean.setCustomerCode(var.getCustomerCode());
            productBean.setNumber(var.getNumber());
            productBean.setOrderId(var.getOrderId());
            productBean.setParentProductId(var.getParentProductId());
            productBean.setPicture(var.getPicture());
            productBean.setPrice(var.getPrice());
            productBean.setProductCode(var.getProductCode());
            productBean.setProductId(var.getProductId());
            productBean.setProductName(var.getProductName());
            productBean.setProductType(var.getProductType());
            productBean.setSalePrice(var.getSalePrice());
            productBean.setSequence(var.getSequence());
            productBean.setSpecification(var.getSpecification());
            productBean.setSpecificationName(var.getSpecificationName());
            productBean.setSettlementPrice(var.getSettlementPrice());
            productBean.setProductSharePrice(var.getProductSharePrice());
            productBean.setUnit(var.getUnit());
            productBean.setWeight(var.getWeight());
            if (CollectionUtils.isNotEmpty(var.getComboProduct())) {
                List<OrderBeanRequest.ProductBean> comProducts = new ArrayList<>();
                var.getComboProduct().forEach(comPro -> {
                    OrderBeanRequest.ProductBean comProductBean = new OrderBeanRequest.ProductBean();
                    comProductBean.setAddInfo(comPro.getAddInfo());
                    comProductBean.setCustomerCode(comPro.getCustomerCode());
                    comProductBean.setNumber(comPro.getNumber());
                    comProductBean.setOrderId(comPro.getOrderId());
                    comProductBean.setParentProductId(comPro.getParentProductId());
                    comProductBean.setPicture(comPro.getPicture());
                    comProductBean.setPrice(comPro.getPrice());
                    comProductBean.setProductCode(comPro.getProductCode());
                    comProductBean.setProductId(comPro.getProductId());
                    comProductBean.setProductName(comPro.getProductName());
                    comProductBean.setProductType(comPro.getProductType());
                    comProductBean.setSalePrice(comPro.getSalePrice());
                    comProductBean.setSequence(comPro.getSequence());
                    comProductBean.setSpecification(comPro.getSpecification());
                    comProductBean.setSpecificationName(comPro.getSpecificationName());
                    comProductBean.setSettlementPrice(comPro.getSettlementPrice());
                    comProductBean.setProductSharePrice(comPro.getProductSharePrice());
                    comProductBean.setUnit(comPro.getUnit());
                    comProductBean.setWeight(comPro.getWeight());

                    OrderProductAddInfoDto extInfo = JSONObject.parseObject(comPro.getExtInfo(), OrderProductAddInfoDto.class);
                    if (extInfo != null && extInfo.getIsFixedProduct() != null) {
                        comProductBean.setIsFixedProduct(extInfo.getIsFixedProduct());
                    } else {
                        comProductBean.setIsFixedProduct(true);
                    }
                    comProducts.add(comProductBean);
                });
                productBean.setComboProduct(comProducts);
            }
            list.add(productBean);

        });
        orderBeanRequest.setProductList(list);
        return orderBeanRequest;
    }


    /**
     * 门店渠道信息保存
     *
     * @return
     */
    public OrderExtendedReq saveStoreInfo(StoreResponseDto storeResponseDto) {
        OrderExtendedReq orderExtended = new OrderExtendedReq();
        orderExtended.setOrderClientGroupCode(storeResponseDto.getParentCode());
        orderExtended.setOrderClientGroup(storeResponseDto.getParentName());
        return orderExtended;
    }

    /**
     * 新老订单类型转换
     *
     * @return
     */
    public Integer getNewOrderType(Integer orderType, Long gmtExpect) {
        //老订单服务订单类型 1=外卖 4=自提，5=堂食
        //新订单服务订单类型 1=常规堂食，2=预约堂食，3=常规外送，4=预约外送，5=常规自取，6=预约自取
        Integer type = 0;
        switch (orderType) {
            case 1:
                if (gmtExpect == null || gmtExpect == 0L) {
                    type = 3;
                } else {
                    type = 4;
                }
                break;
            case 4:
                if (gmtExpect == null || gmtExpect == 0L) {
                    type = 5;
                } else {
                    type = 6;
                }
                break;
            case 5:
                if (gmtExpect == null || gmtExpect == 0L) {
                    type = 1;
                } else {
                    type = 2;
                }
                break;
            default:
                break;
        }

        return type;
    }

    public CreatePrepayRequestDto convertToCreatePrepayRequestDto(String partnerId, String wxAppId, String openId,
                                                                  String faceCode, String cardCode, String payCode, OrderBeanV1 fatherOrderBean,
                                                                  OrderBeanV1 productOrderBean, long totalAmount, int cardAmount, OrderExtInfoDto orderExtInfoDTO,
                                                                  String transId, OrderClientType orderClient) {
        return convertToCreatePrepayRequestDto(partnerId, wxAppId, openId, faceCode, cardCode, payCode, fatherOrderBean,
                productOrderBean, totalAmount, cardAmount, orderExtInfoDTO, transId, orderClient, null);
    }

    public CreatePrepayRequestDto convertToCreatePrepayRequestDto(String partnerId, String wxAppId, String openId,
                                                                  String faceCode, String cardCode, String payCode, OrderBeanV1 fatherOrderBean,
                                                                  OrderBeanV1 productOrderBean, long totalAmount, int cardAmount, OrderExtInfoDto orderExtInfoDTO,
                                                                  String transId, OrderClientType orderClient, CreateOrderUnionPayCardVo unionPayCard) {
        CreatePrepayRequestDto requestDto = new CreatePrepayRequestDto();
        requestDto.setPartnerId(partnerId);
        requestDto.setWxAppId(wxAppId);
        requestDto.setOpenId(openId);
        requestDto.setFaceCode(faceCode);
        requestDto.setCardCode(cardCode);
        requestDto.setPayCode(payCode);
        requestDto.setFatherOrderBean(fatherOrderBean);
        requestDto.setProductOrderBean(productOrderBean);
        requestDto.setTotalAmount(totalAmount);
        requestDto.setCardAmount(0);
        requestDto.setOrderExtInfoDTO(orderExtInfoDTO);
        requestDto.setTransId(transId);
        requestDto.setOrderClient(orderClient);
        requestDto.setUnionPayCard(unionPayCard);
        return requestDto;
    }

    public CreatePrepayRequestDto convertToCreatePrepayRequestDto(CreateOrderBONew createOrderBO,CreateOrderOperateDto createOrderOperateDto) {

        AssortmentCustomerInfoVo userLoginInfoDto = createOrderBO.getUserLoginInfoDto();
        CreateOrderVo createOrderVo =createOrderBO.getCreateOrderVo();
        OrderExtInfoDto orderExtInfoDTO = createOrderBO.getExtInfo();

        CreatePrepayRequestDto requestDto = new CreatePrepayRequestDto();
        requestDto.setPartnerId(createOrderVo.getPartnerId());
        requestDto.setWxAppId(userLoginInfoDto.getWxAppId());
        requestDto.setOpenId( userLoginInfoDto.getOpenId());
        requestDto.setFaceCode(createOrderVo.getFaceCode());
        requestDto.setCardCode(createOrderVo.getCardCode());
        requestDto.setCardCodes(createOrderVo.getCardCodes());
        requestDto.setPayCode(null);
        requestDto.setFatherOrderBean(createOrderOperateDto.getFatherOrderBean());
        requestDto.setProductOrderBean(createOrderOperateDto.getProductOrderBean());
        requestDto.setTotalAmount(createOrderOperateDto.getTotalAmount() == null ? 0 : createOrderOperateDto.getTotalAmount());
        requestDto.setCardAmount(0);
        requestDto.setOrderExtInfoDTO(orderExtInfoDTO);
        requestDto.setTransId(createOrderOperateDto.getFatherOrderBean().getOid());
        requestDto.setOrderClient(null);
        requestDto.setUnionPayCard(createOrderVo.getUnionPayCard());
//        requestDto.setStoreId(createOrderVo.getShopId());
        requestDto.setChannel(createOrderVo.getChannel() == null ? "" : createOrderVo.getChannel());
        return requestDto;
    }

    /**
     * 支付后通知失败返回信息
     */
    public String newSendPayFailedMessage() {
        Map<String, Object> map = Maps.newTreeMap();
        map.put("code", 102);
        map.put("message", "failed");
        return gson.toJson(map);
    }

    /**
     * 支付后触发锁返回信息
     */
    public String paySuccessLockedMessage() {
        Map<String, Object> map = Maps.newTreeMap();
        map.put("code", 101);
        map.put("message", "paySuccessLocked");
        return gson.toJson(map);
    }

    /**
     * 支付后通知确认返回信息
     */
    public String sendPaySuccessNoticeMessage() {
        Map<String, Object> map = Maps.newTreeMap();
        map.put("code", 0);
        map.put("message", "success");
        return gson.toJson(map);
    }

    /**
     * 是否储值卡支付
     * true-是
     */
    public static boolean isPayOfSVC(String payChannel) {
        return StringUtils.isNotBlank(payChannel) && OrderAdapter.PAY_CODE_10102.equalsIgnoreCase(payChannel);
    }


    public CombPayRequest convent2CombPayOrderRequest(String cardNo
            , OrderBeanV1 orderBean
            , PaymentRequest paymentRequest
            , String partnerPayOvertime
            , String orderClient
            , String channel
            , Integer totalAmount) {
        CombPayRequest orderPayDto = new CombPayRequest();
        orderPayDto.setEbCode(paymentRequest.getPayCode());
        orderPayDto.setPartner_id(orderBean.getCompanyId());
        orderPayDto.setBody(paymentRequest.getPrincipalName());
        orderPayDto.setNotify_url(paymentRequest.getReverseNotifyiDcUrl());
        orderPayDto.setStore_id(orderBean.getShopId());
        orderPayDto.setOpen_id(paymentRequest.getOpenId());
        String businessDate = com.freemud.application.sdk.api.util.DateUtil.convert2String(new Date(), "yyyyMMdd");
        orderPayDto.setBusiness_date(businessDate);
        orderPayDto.setAmount(totalAmount.longValue());
        orderPayDto.setVip_amount(0L);
        orderPayDto.setAppId(paymentRequest.getWxAppId());
        orderPayDto.setPayCode(paymentRequest.getPayCode());
        orderPayDto.setVer("V1");
        orderPayDto.setStoreName(orderBean.getShopName());
        orderPayDto.setPayTimeOutTime(StringUtils.defaultIfBlank(partnerPayOvertime, "30"));
        List<ProductVO> productVOS = new ArrayList<ProductVO>();
        if (CollectionUtils.isNotEmpty(orderBean.getProductList())) {
            for (ProductBeanV1 product : orderBean.getProductList()) {
                ProductVO productBean = new ProductVO();
                productBean.setId(product.getProductId());
                productBean.setQuantity(product.getNumber());
                productBean.setSeq(product.getSequence());
                productBean.setSalesType("NORMAL");
                productBean.setPrice(product.getPrice());
                productBean.setName(product.getProductName());
                productVOS.add(productBean);
            }
        }
        orderPayDto.setMerchantDiscount(orderBean.getOriginalAmount().longValue() - orderBean.getAmount());
        orderPayDto.setProducts(productVOS);
        List<PayPlatformVO> platforms = new ArrayList<>();
        PayPlatformVO payPlatformVO = new PayPlatformVO();
        payPlatformVO.setClientCode(PayChannelType.SVC.getEbcode());
        payPlatformVO.setEbcode(PayChannelType.SVC.getEbcode());
        payPlatformVO.setAmount(0L);
        platforms.add(payPlatformVO);

        String ebcode = PayChannelType.getByIndex(Byte.parseByte(channel)).getEbcode();
        payPlatformVO = new PayPlatformVO();
        payPlatformVO.setAmount(0L);
        payPlatformVO.setClientCode(orderClient);
        payPlatformVO.setEbcode(ebcode);
        platforms.add(payPlatformVO);

        orderPayDto.setPlatforms(platforms);
        orderPayDto.setOut_order_no(orderBean.getOid());
        orderPayDto.setCardCode(cardNo);
        orderPayDto.setApplicationType(getPayApplicationType(orderBean.getOrderClient()));
        orderPayDto.setSubAppid(orderBean.getAppId());
        orderPayDto.setPayTypeCode(convertPayTypeCode(orderBean.getOrderClient()));
        return orderPayDto;

    }

    /**
     * 初始化扣减活动库存请求对象
     * add by miaohui 20201030 for 【ID1018638】【C端服务端】活动库存接口调整对接
     *
     * @return
     */
    private ActivityUpdateStockRequest initActivityUpdateStockRequest(List<ActivityDiscountsDto> activityDiscountsDtos) {
        // 原逻辑只检测扣减库存不为空时调用，现改为扣减库存不为空或参加活动不为空时调用
        ActivityUpdateStockRequest activityUpdateStockRequest = new ActivityUpdateStockRequest();
        List<String> activityList = new ArrayList<>();
        // 只记录订单级别的活动ID
        if (CollectionUtils.isNotEmpty(activityDiscountsDtos)) {
            activityList.addAll(activityDiscountsDtos.stream().filter(ad -> StringUtils.isNotBlank(ad.getActivityCode())).map(ActivityDiscountsDto::getActivityCode).distinct().collect(Collectors.toList()));
        }
        //设置活动编号
        activityUpdateStockRequest.setActivityList(CollectionUtils.isNotEmpty(activityList) ? activityList : null);
        return activityUpdateStockRequest;
    }

    public OrderConditionsReq convent2QueryOrdersDtoES(OrderConditionsReq query, String memberId, String channelType, Integer queryOrderStatus, Integer queryOrderType, Integer queryPayStatus) {
        OrderConditionsReq queryOrdersDto = new OrderConditionsReq();
        queryOrdersDto.setUserId(memberId);
        queryOrdersDto.setPartnerId(query.getPartnerId());
        queryOrdersDto.setPageSize(query.getPageSize() != null ? query.getPageSize() : 10);
        queryOrdersDto.setPageNum(query.getPageNum() != null ? query.getPageNum() : 1);
        queryOrdersDto.setStartTimestamp(query.getStartTimestamp());
        queryOrdersDto.setEndTimestamp(query.getEndTimestamp());
        if (query.getMarketingType() != null) {
            queryOrdersDto.setMarketingType(query.getMarketingType());
        }
        List<Integer> orderClients = new ArrayList<>();
        if (OrderChannelType.IWC.getCode().equals(channelType)) {
            orderClients.add(OrderClientType.WAI_MEAL.getIndex());
            orderClients.add(OrderClientType.ALIPAY.getIndex());
//        } else if (OrderChannelType.SAASMALL.getCode().equals(channelType)) {
//            orderClients.add(OrderClientType.SAASMALL.getIndex());
        } else if (OrderChannelType.APP.getCode().equals(channelType)) {
            orderClients.add(OrderClientType.APP.getIndex());
            orderClients.add(OrderClientType.ALIPAY.getIndex());
//        } else if (OrderChannelType.BEAUTIFUL.getCode().equals(channelType)) {// 美业新加
//            orderClients.add(OrderClientType.BEAUTIFUL.getIndex());
//            orderClients.add(OrderClientType.ALIPAY.getIndex());
//        } else if (OrderChannelType.CASHIER.getCode().equals(channelType)) {
//            orderClients.add(OrderClientType.CASHIER.getIndex());
        } else {
            orderClients.add(OrderClientType.SAAS.getIndex());
            orderClients.add(OrderClientType.ALIPAY.getIndex());
        }
        orderClients.add(OrderClientType.TIKTOKPAY.getIndex());
        queryOrdersDto.setOrderClients(orderClients);

        List<Integer> payStatus = new ArrayList<>();
        if (queryPayStatus == null) {
            payStatus = Arrays.asList(PayStatus.HAVE_PAID.getCode(), PayStatus.HAVE_REFUND.getCode(), PayStatus.COMPLETE.getCode());
            queryOrdersDto.setPayStatuses(payStatus);
        } else {
            payStatus = Arrays.asList(queryPayStatus);
            queryOrdersDto.setPayStatuses(payStatus);
        }

        //queryOrdersDto.setPayStatus((Integer[]) payStatus.toArray());
        //TODO 查询退款的待确定
        if (queryOrderStatus != null) {
            if (QueryOrderStatus.ALL_BILL.getCode().equals(queryOrderStatus)) {
                List<Integer> orderStatuses = new ArrayList<>();
                Collections.addAll(orderStatuses, OrderStatusV1.getAllCodes());
                queryOrdersDto.setOrderStatuses(orderStatuses);
                //queryOrdersDto.setStatus(OrderStatus.getAllCodes());
                if (Objects.equals(MarketTypeEnum.GROUPB.getIndex(), query.getMarketingType())) {
                    orderStatuses.add(QueryOrderStatus.FINISH.getCode());
                    orderStatuses.add(QueryOrderStatus.TAKE_MEAL.getCode());
                    orderStatuses.add(QueryOrderStatus.REFUND_BILL.getCode());
                    orderStatuses.add(QueryOrderStatus.NO_PAY.getCode());
                    queryOrdersDto.setOrderStatuses(orderStatuses);
                }
            }
            if (QueryOrderStatus.TAKE_MEAL.getCode().equals(queryOrderStatus)) {
                Integer[] statuses = new Integer[]{OrderStatusV1.TAKE_ORDER.getCode(), OrderStatusV1.RECEIPT.getCode(),
                        OrderStatusV1.DISTRIBUTION.getCode(), OrderStatusV1.COMPLETE_MAKE.getCode()};
                List<Integer> orderStatuses = new ArrayList<>();
                Collections.addAll(orderStatuses, statuses);
                queryOrdersDto.setOrderStatuses(orderStatuses);
                //queryOrdersDto.setStatus(statuses);
            }
            if (QueryOrderStatus.FINISH.getCode().equals(queryOrderStatus)) {
                List<Integer> orderStatuses = new ArrayList<>();
                orderStatuses.add(OrderStatusV1.COMPLETE.getCode());
                queryOrdersDto.setOrderStatuses(orderStatuses);
                //queryOrdersDto.setStatus(new Integer[]{OrderStatus.COMPLETE.getCode()});
            }
            if (QueryOrderStatus.REFUND_BILL.getCode().equals(queryOrderStatus)) {
                // 目前只有美业在用
                payStatus = Arrays.asList(PayStatus.HAVE_REFUND.getCode());
                queryOrdersDto.setPayStatuses(payStatus);
                //Integer[] statuses = new Integer[]{RefundStatus.APPLY_REFUND.getCode(), RefundStatus.AGREE_REFUND.getCode(), RefundStatus.COMPLETE_REFUND.getCode()};
                //queryOrdersDto.setRefundStatus(statuses);
            }
            if (QueryOrderStatus.NO_PAY.getCode().equals(queryOrderStatus)) {
                List<Integer> payStatuses = new ArrayList<>();
                payStatuses.add(PayStatus.NOT_PAY.getCode());
                queryOrdersDto.setPayStatuses(payStatuses);
                //queryOrdersDto.setPayStatus(new Integer[]{PayStatus.NOT_PAY.getCode()});
            }
            if (QueryOrderStatus.ORDER_CANCEL.getCode().equals(queryOrderStatus)) {
                List<Integer> orderStatuses = new ArrayList<>();
                orderStatuses.add(OrderStatusV1.CANCEL.getCode());
                queryOrdersDto.setOrderStatuses(orderStatuses);
                //queryOrdersDto.setStatus(new Integer[]{OrderStatus.CALCEL.getCode()});
            }
            if (QueryOrderStatus.ORDER_CANCEL_MIXUE.getCode().equals(queryOrderStatus)) {
                List<Integer> orderStatuses = new ArrayList<>();
                orderStatuses.add(OrderStatusV1.CANCEL.getCode());
                queryOrdersDto.setOrderStatuses(orderStatuses);
                //queryOrdersDto.setStatus(new Integer[]{OrderStatus.CALCEL.getCode()});
                List<Integer> payStatuses = new ArrayList<>();
                payStatuses.add(PayStatus.NOT_PAY.getCode());
                queryOrdersDto.setPayStatuses(payStatuses);
                //queryOrdersDto.setPayStatus(new Integer[]{PayStatus.NOT_PAY.getCode()});
            }
            if (QueryOrderStatus.WAIT_USE.getCode().equals(queryOrderStatus)) {
                List<Integer> orderStatuses = Arrays.asList(OrderStatusV1.RECEIPT.getCode(), OrderStatusV1.TAKE_ORDER.getCode());
                queryOrdersDto.setOrderStatuses(orderStatuses);
            }
        }

        // 兼容历史版本，如果传参是4 查询拆程4和5
        List<Integer> orderTypes = new ArrayList<>();
        if (queryOrderType != null) {
            if (Objects.equals(queryOrderType, OrderTypeV1.COLLECT_GOODS.getCode())) {
                orderTypes.add(OrderTypeV1.COLLECT_GOODS.getCode());
                orderTypes.add(OrderTypeV1.EAT_IN.getCode());
                //queryOrdersDto.setType(new Integer[]{OrderType.COLLECT_GOODS.getCode(), OrderType.EAT_IN.getCode()});
            } else {
                orderTypes.add(queryOrderType);
                //queryOrdersDto.setType(new Integer[]{queryOrderDto.getQueryOrderType()});
            }
        }
        queryOrdersDto.setOrderTypes(orderTypes);

        if (OrderChannelType.IWC.getCode().equals(channelType)) {
            Integer[] statuses = new Integer[]{OrderStatusV1.COMPLETE.getCode(), OrderStatusV1.CANCEL.getCode(), OrderStatusV1.WAIT_PAY.getCode()};
            List<Integer> orderStatuses = new ArrayList<>();
            Collections.addAll(orderStatuses, statuses);
            queryOrdersDto.setOrderStatuses(orderStatuses);
            //queryOrdersDto.setStatus(statuses);

            Integer[] payWCStatus = new Integer[]{PayStatus.NOT_PAY.getCode(), PayStatus.HAVE_PAID.getCode(), PayStatus.HAVE_REFUND.getCode(), PayStatus.COMPLETE.getCode()};
            List<Integer> payStatuses = new ArrayList<>();
            Collections.addAll(payStatuses, payWCStatus);
            queryOrdersDto.setPayStatuses(payStatuses);
            //queryOrdersDto.setPayStatus(payWCStatus);
        }

        if (OrderChannelType.SAASMALL.getCode().equals(channelType)) {
//            Integer[] statuses = new Integer[]{OrderStatus.COMPLETE.getCode(), OrderStatus.CALCEL.getCode()};
//            queryOrdersDto.setStatus(statuses);
//            queryOrdersDto.setType(new Integer[]{});
        }
        //商品订单和卖券订单
        queryOrdersDto.setBizTypes(Arrays.asList(BizTypeEnum.ORDINARY.getBizType(),
                BizTypeEnum.SALE_COUPON.getBizType(),
                BizTypeEnum.ADVANCE_ORDER.getBizType()));

        // 新老兼容
        if (queryOrdersDto.getOrderStatuses() != null && !queryOrdersDto.getOrderStatuses().isEmpty()) {
            List<Integer> orderStatus = new ArrayList<>();
            for (Integer orderStatuses : queryOrdersDto.getOrderStatuses()) {
                orderStatus.add(OrderStatusV1.getNewCode(orderStatuses));
            }
            queryOrdersDto.setOrderStatuses(orderStatus);
        }

        if (queryOrdersDto.getOrderTypes() != null && !queryOrdersDto.getOrderTypes().isEmpty()) {
            List<Integer> orderType = new ArrayList<>();
            for (Integer type : queryOrdersDto.getOrderTypes()) {
                //订单服务订单类型 1=外卖 4=自提，5=堂食
                //外卖平台订单类型 1=常规堂食，2=预约堂食，3=常规外送，4=预约外送，5=常规自取，6=预约自取
                if (type.intValue() == 1) {
                    orderType.add(3);
                    orderType.add(4);
                }
                if (type.intValue() == 4) {
                    orderType.add(5);
                    orderType.add(6);
                }
                if (type.intValue() == 5) {
                    orderType.add(1);
                    orderType.add(2);
                }
                if (type.intValue() == 6) {
                    orderType.add(6);
                    orderType.add(1);
                }
            }
            queryOrdersDto.setOrderTypes(orderType);
        }


        return queryOrdersDto;
    }

    public QueryOrdersResponse conventEs2queryOrderResponse(BaseDownLoadResponse<List<OrderInfoReqs>> response) {
        QueryOrdersResponse queryOrdersResponse = new QueryOrdersResponse();
        if (null == response || null == response.getResult()) {
            queryOrdersResponse.setErrcode(ResponseCodeConstant.RESPONSE_SUCCESS);
            queryOrdersResponse.setErrmsg(ResponseResultEnum.ORDER_DATA_NOT_EXIST.getMessage());
            return queryOrdersResponse;
        }
        List<OrderInfoReqs> result = response.getResult();

        QueryOrdersResponse.DataBean dataBean = new QueryOrdersResponse.DataBean();

        List<OrderBeanV1> orders = new ArrayList<>();
        if (null != result && result.size() > 0) {
            for (OrderInfoReqs reqs : result) {
                OrderBeanV1 data = orderCenterSdkAdapter.convent2NEWOrderInfo(reqs);
                orders.add(data);
            }
        }

        dataBean.setOrders(orders);
        dataBean.setCount(response.getTotalNum());
        queryOrdersResponse.setData(dataBean);

        queryOrdersResponse.setErrcode(ResponseCodeConstant.RESPONSE_SUCCESS);

        return queryOrdersResponse;
    }


    /**
     * 转换制作中的文案，美业用待使用，其他用制作中
     *
     * @param orderBean
     * @return
     */
    public String conventProduceString(OrderBeanV1 orderBean) {
//        if (String.valueOf(OrderClientType.BEAUTIFUL.getIndex()).equals(orderBean.getOrderClient())) {
//            return "待使用";
//        } else
        if (BizTypeEnum.MALL.getBizType() == orderBean.getBizType()) {
            return "待发货";
        }
        return "制作中";
    }

    /**
     * 转换待使用的文案，美业用待使用，其他用制作中
     *
     * @param orderBean
     * @return
     */
    public String conventCreateOrderString(OrderBeanV1 orderBean) {
//        if (String.valueOf(OrderClientType.BEAUTIFUL.getIndex()).equals(orderBean.getOrderClient())) {
//            return "待使用";
//        }
        return "下单成功";
    }

    /**
     * 获取是否支持订单退款
     */
    public String getPayTurnoffRefund() {
        try {
            AssortmentOpenPlatformPartnerConfig assortmentOpenPlatformPartnerConfig = assortmentOpenPlatformPartnerConfigManager.selectPartnerConfigByPartnerKey(payTurnoffRefundPartnerId, RedisKeyConstant.PARTNER_PAY_TURNOFF_REFUND, 1);
            if (null != assortmentOpenPlatformPartnerConfig) {
                payTurnoffRefund = assortmentOpenPlatformPartnerConfig.getPartnerValue();
            }
        } catch (Exception e) {
            AppLogUtil.errorLog("getPayTurnoffRefund",null,null, e);
        }
        return payTurnoffRefund;
    }

    public BatchOrderRefundV2Request getBatchOrderRefundV2Request(List<OrderBeanV1> orderBeans, String partnerId, String storeId) {
        BatchOrderRefundV2Request orderPayRefundRequest = new BatchOrderRefundV2Request();
        // 请自行过滤金额为0的订单
        List<BatchOrderRefundV2Request.BatchOrderRefundItem> items = orderBeans.stream().map(orderBean -> {
            BatchOrderRefundV2Request.BatchOrderRefundItem item = new BatchOrderRefundV2Request.BatchOrderRefundItem();
            item.setFmId(orderBean.getPayVoucher());
            // TODO 暂时不考虑第三方订单
            item.setFrontTransId(orderBean.getOid());
            item.setRefundAmount(orderBean.getAmount());
            return item;
        }).collect(Collectors.toList());

        orderPayRefundRequest.setBatchSubRefundRequest(items);
        orderPayRefundRequest.setPartnerId(partnerId);
        orderPayRefundRequest.setStoreId(storeId);
        orderPayRefundRequest.setVer("2");
        orderPayRefundRequest.setStationId("001");
        orderPayRefundRequest.setNotifyUrl(refundNotifyCallback);
        return orderPayRefundRequest;
    }

    private String getRefundStatusDesc(RefundBeanV1 refundBean, OrderBeanV1 orderBean) {
        String refundStatusDesc = "";
        if (BizTypeEnum.MALL.getBizType() == orderBean.getBizType()) {
            if (refundBean.getStatus() == RefundStatus.AGREE_REFUND.getCode()) {
                refundStatusDesc = "退款中";
            } else if (refundBean.getStatus() == RefundStatus.COMPLETE_REFUND.getCode()) {
                return "同意退款";
            } else {
                return Optional.ofNullable(RefundStatus.getByCode(refundBean.getStatus())).map(RefundStatus::getDesc).orElse("");
            }
        } else {
            refundStatusDesc = Optional.ofNullable(RefundStatus.getByCode(refundBean.getStatus())).map(RefundStatus::getDesc).orElse("");
        }
        return refundStatusDesc;
    }

    private boolean getRefundButtonDisable(OrderBeanV1 orderBean) {
        boolean refundButtonDisable = true;
        //订单状态为 2：已支付 3：已接单 4：已发货 5：已收货/已完成(C端展示的订单状态)，这些状态订单展示申请退款按钮(未有售后单或者售后单已经取消)
        // 正常订单，未发生售后单的订单，以发货的时间节点为基准，30天后，关闭C端申请退款入口(未有售后单或者售后单已经取消)
        //以最新的发起售后单的时间节点为基准（售后单最后申请的时间，同意申请不会更新申请的时间），30天后，关闭订单状态为已完成，退款状态为未处理的退款单，B端不展示退款处理按钮
        //未发货订单，申请退款商家未处理，以售后单发起时间+30天后，自动退款。

        //校验有没有售后单,一笔订单只会存在一笔售后单,售后单展示为取消展示申请退款按钮
        AfterSalesOrderResp afterSalesOrderResp = orderBean.getAfterSalesOrderResp();
        List<Integer> newOrderStatusList = Arrays.asList(OrderStatusV1.WAIT_PAY.getV2Code(), OrderStatusV1.RECEIPT.getV2Code(), OrderStatusV1.DISTRIBUTION.getV2Code(), OrderStatusV1.COMPLETE.getV2Code());
        List<Integer> afterSaleStatusList = Arrays.asList(AfterSalesStatus.PENDING.getIndex(), AfterSalesStatus.RETURNING.getIndex(), AfterSalesStatus.GOODS_RETURNED.getIndex(), AfterSalesStatus.REJECTED.getIndex(), AfterSalesStatus.COMPLETE.getIndex());
        //已发货
        if (null != orderBean.getGmtDelivery()) {
            if (newOrderStatusList.contains(orderBean.getStatusV2()) && (null == afterSalesOrderResp || (AfterSalesStatus.CANCEL.getIndex() == afterSalesOrderResp.getAfterSalesStatus()))) {
                refundButtonDisable = true;
            }
            if (null == orderBean.getAfterSalesOrderResp() && null != orderBean.getGmtDelivery() && (DateUtil.addDays(new Date(orderBean.getGmtDelivery()), 30)).compareTo(new Date()) == -1) {
                refundButtonDisable = false;
            }
            if (null != orderBean.getAfterSalesOrderResp() && afterSaleStatusList.contains(orderBean.getAfterSalesOrderResp().getAfterSalesStatus())) {
                refundButtonDisable = false;
            }
            if (null == orderBean.getAfterSalesOrderResp() && (DateUtil.addDays(new Date(orderBean.getGmtDelivery()), 30)).compareTo(new Date()) == -1) {
                refundButtonDisable = false;
            }
        } else {
            List<Integer> noDeliveryAfterSalesStatus = Arrays.asList(AfterSalesStatus.PENDING.getIndex(), AfterSalesStatus.COMPLETE.getIndex());
            if (newOrderStatusList.contains(orderBean.getStatusV2()) && (null == afterSalesOrderResp || (AfterSalesStatus.CANCEL.getIndex() == afterSalesOrderResp.getAfterSalesStatus()))) {
                refundButtonDisable = true;
            }
            if (null != orderBean.getAfterSalesOrderResp() && noDeliveryAfterSalesStatus.contains(orderBean.getAfterSalesOrderResp().getAfterSalesStatus())) {
                refundButtonDisable = false;
            }
        }
        return refundButtonDisable;
    }

    private boolean getOrderCompareAfterSaleOrder(OrderBeanV1 orderBean) {
        boolean orderCompareAfterSaleOrder = false;
        List<Integer> newOrderStatusList = Arrays.asList(OrderStatusV1.RECEIPT.getV2Code(), OrderStatusV1.DISTRIBUTION.getV2Code(), OrderStatusV1.COMPLETE.getV2Code());
        //是否忽略售后单状态”呀，大部分情况都是false；只有拒绝退款后继续发货状态并行时新赠的“是否忽略售后单状态”字段为true
        AfterSalesOrderResp afterSalesOrderResp = orderBean.getAfterSalesOrderResp();
        if (null != afterSalesOrderResp && ((Objects.equals(AfterSalesStatus.CANCEL.getIndex(), afterSalesOrderResp.getAfterSalesStatus()) && (Objects.equals(OrderStatusV1.DISTRIBUTION.getV2Code(), orderBean.getStatusV2()) || Objects.equals(OrderStatusV1.COMPLETE.getV2Code(), orderBean.getStatusV2()))) ||
                (Objects.equals(AfterSalesStatus.REJECTED.getIndex(), afterSalesOrderResp.getAfterSalesStatus()) && (newOrderStatusList.contains(orderBean.getStatusV2()))))) {
            orderCompareAfterSaleOrder = true;
        }
        return orderCompareAfterSaleOrder;
    }


    /**
     * 获取订单信息
     */
    public String getOrderStatusValue(Integer newOrderStatus) {
        String name = "";
        switch (newOrderStatus) {
            case 1: {
                name = "待审核";
                break;
            }
            case 6: {
                name = "审核通过";
                break;
            }
            case 7: {
                name = "审核未通过";
                break;
            }
            case 8: {
                name = "撤单";
                break;
            }
        }
        return name;
    }

    /**
     * 支付类型编码 TWX:微信 TZFB:支付宝
     */
    public String convertPayTypeCode(String orderClient) {
        String payTypeCode = "";
        switch (orderClient) {
            case "2":
                payTypeCode = "TWX";
                break;
            case "3":
                payTypeCode = "TZFB";
                break;
            default:
                break;
        }
        return payTypeCode;
    }

    /**
     * 礼品卡支付参数转化
     */
    public Integer getPayApplicationType(String orderClient) {
        Integer applicationType = PayApplicationTypeEnum.WECHAT.getType();
        switch (orderClient) {
            case "2":
                applicationType = PayApplicationTypeEnum.WECHAT.getType();
                break;
            case "3":
                applicationType = PayApplicationTypeEnum.ALIPAY.getType();
                break;
            case "27":
                applicationType = PayApplicationTypeEnum.BYTE_DANCE.getType();
                break;
            default:
                break;
        }
        return applicationType;
    }

    /**
     * 设置创建订单的　extInfo字段
     * @return
     */
    public OrderExtInfoDto setOrderExtInfo(AssortmentCustomerInfoVo userLoginInfoDto, StoreResponseDto storeResponseDto,
                                            CreateOrderVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto) {

        Integer serviceTime = storeResponseDto.getServiceTime();
        String sessionId = createOrderVo.getSessionId();
        String version = createOrderVo.getVersion();
//        CreateOrderVo.BuyMemberCard memberCard = createOrderVo.getBuyMemberCard();

        String deliveryHoursDayStart = "";
        String deliveryHoursDayEnd = "";
        if (StringUtils.isNotBlank(storeResponseDto.getDeliveryHoursDay())) {
            String[] days = storeResponseDto.getDeliveryHoursDay().split("-");
            if (days.length == 2) {
                deliveryHoursDayStart = DateUtil.convert2String(new Date(), DateUtil.FORMAT_yyyyMMdd_date) + " " + days[0] + ":00";
//                deliveryHoursDayEnd = DateUtil.convert2String(new Date(), DateUtil.FORMAT_yyyyMMdd_date) + " " + days[1] + ":00";
            }
        }

        OrderExtInfoDto orderExtInfoDto = new OrderExtInfoDto();
        orderExtInfoDto.setDeliveryHoursDayStart(deliveryHoursDayStart);
        orderExtInfoDto.setDeliveryHoursDayEnd(deliveryHoursDayEnd);
        orderExtInfoDto.setOpenid(userLoginInfoDto.getOpenId());
        //todo 字段多余，订单对象已有该字段
        orderExtInfoDto.setAppid(userLoginInfoDto.getWxAppId());
        orderExtInfoDto.setSessionId(sessionId);
        if (Objects.equals(serviceTime, null)) {
            serviceTime = 50;
        }
        orderExtInfoDto.setServiceTime(serviceTime);
        orderExtInfoDto.setPushOrderTime(0);
        orderExtInfoDto.setVersion(version);
//        if (memberCard != null && memberCard.getRuleId() != null) {
//            orderExtInfoDto.setRuleId(memberCard.getRuleId());
//        }
        // 扩展字段中存储 sessionKey
        orderExtInfoDto.setSessionKey(createOrderVo.getSessionKey());
        orderExtInfoDto.setFormId(createOrderVo.getFormId());
        //todo　多余字段
        orderExtInfoDto.setFromAppId(userLoginInfoDto.getWxAppId());
        if (StringUtils.isNotBlank(createOrderVo.getScene())) {
            orderExtInfoDto.setScene(createOrderVo.getScene());
        }
        if (null != shoppingCartGoodsDto && null != shoppingCartGoodsDto.getSendPoint()) {
            ShoppingCartGoodsDto.SendPoint sendPoint = shoppingCartGoodsDto.getSendPoint();
            orderExtInfoDto.setSendPointValidityDateDays(sendPoint.getValidityDateDays());
            orderExtInfoDto.setSendPointMaxNum(sendPoint.getMaxNum());
            orderExtInfoDto.setSendPointActivityCode(sendPoint.getActivityCode());
            orderExtInfoDto.setSendPointEndTime(sendPoint.getEndTime().getTime() + "");
            orderExtInfoDto.setSendPointSendPoint(sendPoint.getSendPoint());
            orderExtInfoDto.setSendPointStoreLevel(sendPoint.getStoreLevel());
            orderExtInfoDto.setIsContinueExchange(sendPoint.getIsContinueExchange());
        }
        if (null != shoppingCartGoodsDto && null != shoppingCartGoodsDto.getTotalScore()) {
            orderExtInfoDto.setTotalScore(shoppingCartGoodsDto.getTotalScore());
        }
        if (null != shoppingCartGoodsDto && null != shoppingCartGoodsDto.getPackageAmountCollectType()) {
            orderExtInfoDto.setPackageAmountCollectType(shoppingCartGoodsDto.getPackageAmountCollectType());
        }

//        orderExtInfoDto.setUnDistribution(createOrderVo.getUnDistribution());
        return orderExtInfoDto;
    }

    /**
     * 查询订单商品详情中是否有称重菜未称重
     * @return
     */
    public boolean queryExistWeightNoNum(OrderBeanV1 orderBean){
        for(ProductBeanV1 productBean : orderBean.getProductList()){
            if(ProductTypeEnum.WEIGHT_PRODUCT.getCode().equals(productBean.getProductType()) && (productBean.getWeight() == null || new BigDecimal("0.00").compareTo(productBean.getWeight()) >=  0)){
                return false;
            }
            if(ProductTypeEnum.SETMEAL_PRODUCT.getCode().equals(productBean.getProductType()) || ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode().equals(productBean.getProductType())){
                if(CollectionUtils.isNotEmpty(productBean.getComboProduct())){
                    for(ProductBeanV1 productBeanSon : productBean.getComboProduct()){
                        if(ProductTypeEnum.WEIGHT_PRODUCT.getCode().equals(productBeanSon.getProductType()) && (productBeanSon.getWeight() == null || new BigDecimal("0.00").compareTo(productBeanSon.getWeight()) >= 0)){
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }


    public OrderType getNewOrderType(OrderTypeV1 orderType, String gmtExpect, Integer bizType) {
        //订单服务订单类型 1=外卖 4=自提，5=堂食
        //外卖平台订单类型 1=常规堂食，2=预约堂食，3=常规外送，4=预约外送，5=常规自取，6=预约自取
        boolean isAdvance = bizType != null && bizType.compareTo(BizTypeEnum.ADVANCE_ORDER.getBizType()) == 0;
        OrderType type = null;
        // 预定单 是额外的逻辑 --> 需要走实时单
        if (isAdvance) {
            switch (orderType) {
                case TAKE_OUT:
                    type = OrderType.GENERAL_EXPRESS;
                    break;
                case COLLECT_GOODS:
                    type = OrderType.GENERAL_SELF_PICKUP;
                    break;
                case EAT_IN:
                    type = OrderType.GENERAL_DINE_IN;
                    break;
                default:
                    break;
            }
            return type;
        }

        switch (orderType) {
            case TAKE_OUT:
                if (StringUtils.isEmpty(gmtExpect)) {
                    type = OrderType.GENERAL_EXPRESS;
                } else {
                    type = OrderType.RESERVED_EXPRESS;
                }
                break;
            case COLLECT_GOODS:
                if (StringUtils.isEmpty(gmtExpect)) {
                    type = OrderType.GENERAL_SELF_PICKUP;
                } else {
                    type = OrderType.RESERVED_SELF_PICKUP;
                }
                break;
            case EAT_IN:
                if (StringUtils.isEmpty(gmtExpect)) {
                    type = OrderType.GENERAL_DINE_IN;
                } else {
                    type = OrderType.RESERVED_DINE_IN;
                }
                break;
            default:
                break;
        }

        return type;
    }

    public List<SvcPayItem> convertSvcPayItem(UnifiedPayResponseDto codePayResponse,String cardCode){
        List<SvcPayItem> payItems = new ArrayList<>();
        SvcPayItem payItem = new SvcPayItem();
        payItem.setCardCode(cardCode);
        payItem.setSvcTransId(codePayResponse.getPayTransId());
        payItem.setTransId(codePayResponse.getFmId());
        payItems.add(payItem);
        return payItems;
    }

    public MultiPayRequest convent2MultiPayOrderRequest(List<String> cardCodes
            , OrderBeanV1 orderBean
            , PaymentRequest paymentRequest
            , String partnerPayOvertime
            , String orderClient
            , String channel
            , Integer totalAmount) {
        MultiPayRequest orderPayDto = new MultiPayRequest();
        orderPayDto.setEbCode(paymentRequest.getPayCode());
        orderPayDto.setPartner_id(orderBean.getCompanyId());
        orderPayDto.setBody(paymentRequest.getPrincipalName());
        orderPayDto.setNotify_url(paymentRequest.getReverseNotifyiDcUrl());
        orderPayDto.setStore_id(orderBean.getShopId());
        orderPayDto.setOpen_id(paymentRequest.getOpenId());
        String businessDate = com.freemud.application.sdk.api.util.DateUtil.convert2String(new Date(), "yyyyMMdd");
        orderPayDto.setBusiness_date(businessDate);
        orderPayDto.setAmount(totalAmount.longValue());
        orderPayDto.setVip_amount(0L);
        orderPayDto.setAppId(paymentRequest.getWxAppId());
        orderPayDto.setPayCode(paymentRequest.getPayCode());
        orderPayDto.setVer("V1");
        orderPayDto.setStoreName(orderBean.getShopName());
        orderPayDto.setPayTimeOutTime(StringUtils.defaultIfBlank(partnerPayOvertime, "30"));
        List<ProductVO> productVOS = new ArrayList<ProductVO>();
        if (CollectionUtils.isNotEmpty(orderBean.getProductList())) {
            for (ProductBeanV1 product : orderBean.getProductList()) {
                ProductVO productBean = new ProductVO();
                productBean.setId(product.getProductId());
                productBean.setQuantity(product.getNumber());
                productBean.setSeq(product.getSequence());
                productBean.setSalesType("NORMAL");
                productBean.setPrice(product.getPrice());
                productBean.setName(product.getProductName());
                productVOS.add(productBean);
            }
        }
        orderPayDto.setMerchantDiscount(orderBean.getOriginalAmount().longValue() - orderBean.getAmount());
        orderPayDto.setProducts(productVOS);
        List<PayPlatformVO> platforms = new ArrayList<>();
        PayPlatformVO payPlatformVO = new PayPlatformVO();
        payPlatformVO.setClientCode(PayChannelType.SVC.getEbcode());
        payPlatformVO.setEbcode(PayChannelType.SVC.getEbcode());
        payPlatformVO.setAmount(0L);
        platforms.add(payPlatformVO);

        String ebcode = PayChannelType.getByIndex(Byte.parseByte(channel)).getEbcode();
        payPlatformVO = new PayPlatformVO();
        payPlatformVO.setAmount(0L);
        payPlatformVO.setClientCode(orderClient);
        payPlatformVO.setEbcode(ebcode);
        platforms.add(payPlatformVO);

        orderPayDto.setPlatforms(platforms);
        orderPayDto.setOut_order_no(orderBean.getOid());
        orderPayDto.setCardItems(cardCodes);//多卡支付
        orderPayDto.setApplicationType(getPayApplicationType(orderBean.getOrderClient()));
        orderPayDto.setSubAppid(orderBean.getAppId());
        orderPayDto.setPayTypeCode(convertPayTypeCode(orderBean.getOrderClient()));
        return orderPayDto;

    }
}
