/**
 * 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.dto.*;
import cn.freemud.entities.dto.activity.ShareDiscountActivityDto;
import cn.freemud.entities.dto.order.CreateOrderAccountDto;
import cn.freemud.entities.dto.order.CreateOrderProductDto;
import cn.freemud.entities.dto.order.*;
import cn.freemud.entities.dto.pay.CombPayResponse;
import cn.freemud.entities.dto.pay.OrderPayResponse;
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.enums.ActivityTypeEnum;
import cn.freemud.enums.OrderChannelType;
import cn.freemud.enums.OrderSourceType;
import cn.freemud.enums.OrderType;
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.redis.RedisCache;
import cn.freemud.request.wechat.dto.SignMessageBuilder;
import cn.freemud.service.impl.OrderCommonService;
import cn.freemud.utils.*;
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.db.AssortmentOpenPlatformPartnerWxappConfig;
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.api.assortment.datamanager.manager.cache.CacheOpenPlatformPartnerWxappConfigManager;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.entities.v1.*;
import com.freemud.application.sdk.api.ordercenter.enums.*;
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.OrderPayItemResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderSettlementResp;
import com.freemud.application.sdk.api.promotioncenter.dto.promotion.GoodsStockDTO;
import com.freemud.application.sdk.api.promotioncenter.request.promotion.ActivityUpdateStockRequest;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.sdk.api.assortment.order.adapter.OrderSdkAdapter;
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.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.PayPlatformVO;
import com.freemud.sdk.api.assortment.order.request.payment.ProductVO;
import com.freemud.sdk.api.assortment.order.response.order.CreateOrderFlowResponse;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrderByIdResponse;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse;
import com.freemud.sdk.api.assortment.payment.request.UnifiedOrderRequest;
import com.freemud.sdk.api.assortment.payment.response.UnifiedOrderResponse;
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.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.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
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;

//import com.freemud.application.sdk.api.log.LogThreadLocal;

@Component
public class OrderAdapter {
    private static FastDateFormat yyyyMMddHHmmss = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss", Locale.CHINA);

    private static String SPMCHID = "1237482502";
//    private static String SPWXAPPID = "wx8244c7c48c7d45de";
//    private static String ENTRYPAGE = "pages/storeListShop";
    private static String SERIALNO = "3425DD6C131D637D7316076C4A44E1CBEFE3DB55";
    private static String privatekey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDO+3Q6YX6843Qo5Okhum74yG7zpJ8NbWk9EugJwxW9AZuZI3fziAW5+EblEkx0ZeXYX/GvztjRUZ+MA4eHAXnAdzhiTO46LOePtjQXXqPVOHKEhkfa/5qvJSzJ1Ei8ICrA1hQOGF0sqxMmFNpWaXJkHZ7rJ4KRir8osVeWEF8l8xWEktpXVzspT1PGt7T9i9cQO/lMFYP9nq4qr0pZ4rGgpjURjuZHam5E9l6IFP0VVBvyYP96c/9rUgDeLtPqRDCfQC3WYUtA34XudM/HaGCSPvg5ui5Q2sWob10YFP2F8iTCBHDE3rR1s+inYjS4oXd/TCWQ7+C/O7L9h5AKEFAZAgMBAAECggEAGNFJpF5gReG34ddgpKyn9aiCtS/96iw+PBZyQAlmJ91zfK8mCMs8dInyZjEFfcdiAcmvPvc8RAzXZoBd1bA1mwAwgIjc35jWwwKDyHGOj1hPUtiO8RFIyMtaTXDor7Xjqm+AxBfjxCFXEG/bphTKpHpwvZ1lKHJMbWKmL9YSsof1zK12FC5nFxA0mrPlpYHWFmbeMLu7ngDTGEA5AepKv+BZcqMEJGQvAgskGHdsLSd2NoadUQoFz0ZOrXAXlqNQpODUqRTm3besq2ClBaa2JNEG/KxGqZGM11jsTaduH5WhUubb53OJ8pbkw3ROept9fW25QX/k3ORJ3Xmq+g4gAQKBgQDqbRE1mrfEYW0yjnb6FKx+0jHcU/RNuqflCCoWaEzzNJbMzTxuYvyyR7bhT07B26Qji2ic3T/qUokMXpavadZItH8QegTf3eCtDWU1a6RdPkS+NvRT3NaJstbPnGEEavcbS4y45phE9637rhn7WpaWCmw4ggaawNH/lo7kOBCqGQKBgQDiB9PpW7gumtFlNqw6HVcdl/1SvIOWPujvzYNnFkp3ZWDf/hF7XWno3+w27kA/ox9X7A7ejZZgPsR1+QVgbAGCRDs7qVM77r0XddXtKatCnENWsIER11+SAHwXNI+OzVJyivxqc8MqKVt/TdIIRlOXmrDtBLWXrKtJ6+fpRZ2WAQKBgG1T2EbLlRB871Q4pLwUkC3FEYPTk4f8mPhzSk2Q7vItgHaa8Kf6eica0utY9T3rlS0OgwdFF93MCCZApr2/+jOGGgwxG7zb2UBbkuvK+6iQtbaQInpJ77PgN9Yy8/v/dqbAISzKPhFMAVPy6iMTKE9pJPdljHb3nfg42wMMMplhAoGAYV2r3F9FNNY+E1J82D/hUf8yAZzxNhx9bSdjTlnc1BfYpkSktTalM8qZz4PMK12SV+Z49UeamnUPXh5aQZHlCH9p4KZtE2khDWUWNSZ4/qWfoE1CHDRhl9wbmEds+7/YnzzdxOF/Fb9hCbK1IhlhUvIw+rjHnMGlu58idGsnmgECgYAk+2mWAoGUaQdgPHc0Ts8AiZ1CB2HcWEakFD4yYfVYL107OkxfSXd7dlaVklCHbHaMUYuT4euIfJzXfaTjEnImqQu2hs9u1yTyJHKwjj9gyWHYfcr4byiXjKnbwMkNCrrHWMXCKZ3/F0FQWRE9lsIHZYkFUUUoZYmSorbBf815HQ==";

    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.reverseNotifyiDcUrl}")
    private String reverseNotifyiDcUrl;
    @Value("${saas.refund.notify.callback}")
    private String refundNotifyCallback;
    @Value("${program.backorders_change_order_status_consumer_queue}")
    private String backOrdersChangeOrderStatusConsumerQueue;
    @Value("${program.backorders_notify_activity_exchange}")
    private String backOrdersNotifyActivityExchange;
    @Autowired
    private ShoppingCartAdapter shoppingCartAdapter;
    @Autowired
    private CacheOpenPlatformPartnerWxappConfigManager cacheWxappConfigManager;
//    @Autowired
//    private RedisCache redisCache;
    @Autowired
    private OrderCommonService orderCommonService;

    private static Gson gson = new Gson();

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private OrderSdkAdapter orderSdkAdapter;

    @Autowired
    private AssortmentOpenPlatformPartnerConfigManager assortmentOpenPlatformPartnerConfigManager;

    /**
     * @param createOrderVo
     * @param shoppingCartGoodsDto
     * @return
     */
    public BaseCreateOrderRequest convent2CreateOrderDto(CreateOrderVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto, StoreResponse.BizVO 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));
        }

//        Set<String> withOrderBuyCouponCodeSet = new HashSet<>();
//        withOrderBuyCouponCodeSet.add(withOrderBuyCouponCode);
//        cartGoodsDetailDtos.stream().filter(o -> ProductTypeEnum.getVirtualProductType().contains(o.getProductType())).map(o -> withOrderBuyCouponCodeSet.add(o.getMonthCardInfo().getCardCode()));

        // 根据购物车商品信息获取优惠信息
        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);

        //设置库存扣减
        if (CollectionUtils.isNotEmpty(shoppingCartGoodsDto.getStocks())) {
            List<ActivityUpdateStockRequest.StockBeanDto> stocks = new ArrayList<>();
            for (SubtractStockVO stockVO : shoppingCartGoodsDto.getStocks()) {
                ActivityUpdateStockRequest.StockBeanDto stockBeanDto = new ActivityUpdateStockRequest.StockBeanDto();
                stockBeanDto.setActivityCode(stockVO.getActivityCode());
                stockBeanDto.setActivityStock(stockVO.getActivityStock() == null ? 1 : stockVO.getActivityStock());
                if (CollectionUtils.isNotEmpty(stockVO.getGoodsStock())) {
                    List<GoodsStockDTO> goodsStockDTOS = new ArrayList<>();
                    stockVO.getGoodsStock().forEach(goods -> {
                        GoodsStockDTO goodsStockDTO = new GoodsStockDTO();
                        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);
                }
                stocks.add(stockBeanDto);
            }

            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 BaseCreateOrderRequest.OrderOtherInfo getOrderOtherInfo(ShoppingCartGoodsDto shoppingCartGoodsDto) {
        BaseCreateOrderRequest.SendPoint sendPoint = new BaseCreateOrderRequest.SendPoint();
        if (sendPoint != null) {
            BeanUtil.convertBean(shoppingCartGoodsDto.getSendPoint(), sendPoint);
        }
        BaseCreateOrderRequest.OrderOtherInfo orderOtherInfo = new BaseCreateOrderRequest.OrderOtherInfo();
        orderOtherInfo.setPoint(sendPoint);
        return orderOtherInfo;
    }

    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 CreateFatherSonOrderRequest convertFatherSonOrderRequest(CreateOrderVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto,
                                                                    OrderExtendedReq orderExtendedReq, StoreResponse.BizVO storeResponseDto,
                                                                    String appId) {
        CreateFatherSonOrderRequest createFatherSonOrderRequest = new CreateFatherSonOrderRequest();
        createFatherSonOrderRequest.setPartnerId(createOrderVo.getPartnerId());
        createFatherSonOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        createFatherSonOrderRequest.setMenuType(createOrderVo.getMenuType());
        UserDeliveryInfoDto deliveryInfoDto = createOrderVo.getUserDeliveryInfoDto();
        List<CreateFatherSonOrderRequest.OrderInfo> orderInfoList = new ArrayList<>();
        CreateFatherSonOrderRequest.OrderInfo productOrderInfo = convertProductOrderInfo(createOrderVo, deliveryInfoDto, shoppingCartGoodsDto);
        productOrderInfo.setOrderExtended(orderExtendedReq);
        productOrderInfo.setAppId(appId);
        CreateFatherSonOrderRequest.OrderInfo memberOrderInfo = convertMemberOrderInfo(createOrderVo, shoppingCartGoodsDto, productOrderInfo.getOrderType());
        CreateFatherSonOrderRequest.OrderInfo fatherOrderInfo = convertFatherOrderInfo(createOrderVo, shoppingCartGoodsDto, deliveryInfoDto, productOrderInfo.getOrderType());

        orderInfoList.add(productOrderInfo);
        orderInfoList.add(memberOrderInfo);
        createFatherSonOrderRequest.setOrderInfoList(orderInfoList);
        createFatherSonOrderRequest.setParentOrder(fatherOrderInfo);
        return createFatherSonOrderRequest;
    }

    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 storeDeliveryInfoDto 门店配送信息
     * @param userLongitude        用户地址经度
     * @param userLatitude         用户地址维度
     * @return
     */
    public Long getUserRealDeliveryAmount(StoreDeliveryInfoDto storeDeliveryInfoDto, String userLongitude, String userLatitude) {
        if (!checkUserEnableDelivery(storeDeliveryInfoDto, userLongitude, userLatitude)) {
            return 0L;
        }
        // TODO 用户收货地址距离门店距离 单位米 如果门店没有设置阶层配送费，配送费默认=基础配送费
        if (storeDeliveryInfoDto.getAddRangeCount() == null || storeDeliveryInfoDto.getAddRangeCount() <= 0) {
            return storeDeliveryInfoDto.getDeliveryAmount();
        }
        if (storeDeliveryInfoDto.getAddRangeAmount() == null || storeDeliveryInfoDto.getAddRangeAmount() <= 0) {
            return storeDeliveryInfoDto.getDeliveryAmount();
        }
        double distance = getDistance(storeDeliveryInfoDto.getLongitude(), storeDeliveryInfoDto.getLatitude(),
                userLongitude, userLatitude);
        Long defaultDeliveryRange = storeDeliveryInfoDto.getDefaultDeliveryRange();
        Long deliveryAmount = storeDeliveryInfoDto.getDeliveryAmount();
        Long addRangeCount = storeDeliveryInfoDto.getAddRangeCount();
        Long addRangeAmount = storeDeliveryInfoDto.getAddRangeAmount();
        if (new BigDecimal(distance).compareTo(new BigDecimal(defaultDeliveryRange)) <= 0) {
            return deliveryAmount;
        } else {
            //计算实际配送费
            BigDecimal extraAmount = (new BigDecimal(distance).subtract(new BigDecimal(defaultDeliveryRange)))
                    .divide(new BigDecimal(addRangeCount), 0, BigDecimal.ROUND_UP)
                    .multiply(new BigDecimal(addRangeAmount));
            BigDecimal realAmount = new BigDecimal(deliveryAmount).add(extraAmount);
            return realAmount.longValue();
        }
    }

    /**
     * 获取两个点的距离 单位米
     *
     * @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);
    }

    public List<ShareDiscountActivityDto.ApportionGood> getApportionGoodsBySkuId(CreateOrderProductDemoDto createOrderProductDemoDto, List<ShareDiscountActivityDto> newShareDiscountActivityDtos) {
        List<ShareDiscountActivityDto.ApportionGood> list = Lists.newArrayList();
        if (CollectionUtils.isEmpty(newShareDiscountActivityDtos)) {
            return list;
        }
        String skuId = createOrderProductDemoDto.getSpecification();
        boolean hasProductCoupon = createOrderProductDemoDto.getHasProductCoupon();
        Iterator<ShareDiscountActivityDto> iterator = newShareDiscountActivityDtos.iterator();
        while (iterator.hasNext()) {
            ShareDiscountActivityDto shareDiscountActivityDto = iterator.next();
            if (skuId.equals(shareDiscountActivityDto.getGoodsId()) && shareDiscountActivityDto.getHasProductCoupon().equals(hasProductCoupon)) {
                list = shareDiscountActivityDto.getApportionGoods();
                iterator.remove();
                break;
            }
        }
        return list;
    }

    public List<ShareDiscountActivityDto.ApportionGood> getApportionGoodsBySkuIdNew(CreateOrderProductRequest createOrderProductDemoDto, List<ShareDiscountActivityDto> newShareDiscountActivityDtos, Boolean hasProductCoupon) {
        List<ShareDiscountActivityDto.ApportionGood> list = Lists.newArrayList();
        if (CollectionUtils.isEmpty(newShareDiscountActivityDtos)) {
            return list;
        }
        String skuId = createOrderProductDemoDto.getSpecification();
        Iterator<ShareDiscountActivityDto> iterator = newShareDiscountActivityDtos.iterator();
        while (iterator.hasNext()) {
            ShareDiscountActivityDto shareDiscountActivityDto = iterator.next();
            if (skuId.equals(shareDiscountActivityDto.getGoodsId()) && shareDiscountActivityDto.getHasProductCoupon().equals(hasProductCoupon)) {
                list = shareDiscountActivityDto.getApportionGoods();
                iterator.remove();
                break;
            }
        }
        return list;
    }

    /**
     * 统计参与优惠的商品
     */
    public List<CreateAccountProductDto> getAccountProducts(CreateOrderAccountDto createOrderAccountDto, List<CreateOrderProductDto> createOrderProductDtos) {
        Map<String, CreateAccountProductDto> productDtoMap = Maps.newTreeMap();
        createOrderProductDtos.forEach(createOrderProductDto -> {
            if (CollectionUtils.isNotEmpty(createOrderProductDto.getDiscountList())) {
                createOrderProductDto.getDiscountList().forEach(productDiscount -> {
                    if (createOrderAccountDto.getOldOrderAccountType().equals(productDiscount.getOldOrderAccountType())) {
                        if (!productDtoMap.containsKey(productDiscount.getProductId())) {
                            CreateAccountProductDto createAccountProductDto = CreateAccountProductDto.builder()
                                    .productId(productDiscount.getProductId())
                                    .discountQty(productDiscount.getDiscountQty())
                                    .build();
                            productDtoMap.put(productDiscount.getProductId(), createAccountProductDto);
                        } else {
                            CreateAccountProductDto oldCreateAccountProductDto = productDtoMap.get(productDiscount.getProductId());
                            oldCreateAccountProductDto.setDiscountQty(oldCreateAccountProductDto.getDiscountQty() + productDiscount.getDiscountQty());
                            productDtoMap.put(productDiscount.getProductId(), oldCreateAccountProductDto);
                        }
                    }
                });
            }
        });
        return new ArrayList<>(productDtoMap.values());
    }

    /**
     * 通过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);
//        log.debug("getCreateOrderDto sessionId:{},createOrderVo:{}",createOrderVo.getSessionId(),JSON.toJSONString(createOrderVo));
        Integer orderType;
        String receiveAddress = createOrderVo.getStoreAddress();
        // fisherman -> 爱马哥 orderType落库的类型处理
        if (Objects.equals(createOrderVo.getOrderType(), CreateOrderType.TAKE_OUT.getCode())) {
            orderType = OrderType.TAKE_OUT.getCode();
            receiveAddress = (userDeliveryInfoDto != null ? userDeliveryInfoDto.getReceiveOfficeName() + "," + userDeliveryInfoDto.getReceiveAddress() : "");
        } else if (Objects.equals(createOrderVo.getOrderType(), CreateOrderType.COLLECT_GOODS.getCode())) {
            if (Objects.equals(createOrderVo.getReachStoreType(), OrderType.EAT_IN.getCode())) {
                orderType = OrderType.EAT_IN.getCode();
            } else {
                orderType = OrderType.COLLECT_GOODS.getCode();
            }
        } else if (Objects.equals(createOrderVo.getOrderType(), OrderType.MALL.getCode())) {
            orderType = OrderType.MALL.getCode();
            receiveAddress = (userDeliveryInfoDto != null ? userDeliveryInfoDto.getReceiveProvince() + userDeliveryInfoDto.getReceiveCity() + userDeliveryInfoDto.getReceiveRegion() + userDeliveryInfoDto.getReceiveAddress() : "");
            createOrderVo.setMobile(userDeliveryInfoDto.getReceiveMobile());
            createOrderVo.setContactsName(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.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.setSource(OrderSourceType.SAAS.getCode());
        createOrderDto.setSourceName(OrderSourceType.SAAS.getDesc());
        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.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;
    }

    public CreateFatherSonOrderRequest.OrderInfo convertProductOrderInfo(CreateOrderVo createOrderVo
            , UserDeliveryInfoDto userDeliveryInfoDto, ShoppingCartGoodsDto shoppingCartGoodsDto) {
        String deliveryType = userDeliveryInfoDto != null && userDeliveryInfoDto.getStoreDeliveryInfoDto() != null
                ? userDeliveryInfoDto.getStoreDeliveryInfoDto().getDeliveryType() : "";
        QueryOrderType orderType;
        String receiveAddress = createOrderVo.getStoreAddress();
        if (Objects.equals(createOrderVo.getOrderType(), CreateOrderType.TAKE_OUT.getCode())) {
            orderType = QueryOrderType.TAKE_OUT;
            receiveAddress = (userDeliveryInfoDto != null ? userDeliveryInfoDto.getReceiveOfficeName() + "," + userDeliveryInfoDto.getReceiveAddress() : "");
        } else if (Objects.equals(createOrderVo.getOrderType(), CreateOrderType.COLLECT_GOODS.getCode())) {
            if (Objects.equals(createOrderVo.getReachStoreType(), OrderType.EAT_IN.getCode())) {
                orderType = QueryOrderType.EAT_IN;
            } else {
                orderType = QueryOrderType.COLLECT_GOODS;
            }
        } 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() : "";
        CreateFatherSonOrderRequest.OrderInfo productOrderInfo = new CreateFatherSonOrderRequest.OrderInfo();
        productOrderInfo.setPartnerId(createOrderVo.getPartnerId());
        productOrderInfo.setShopId(createOrderVo.getShopId());
        productOrderInfo.setShopName(createOrderVo.getStoreName());
        productOrderInfo.setUserId(createOrderVo.getUserId());
        productOrderInfo.setUserName(createOrderVo.getUserName());
        productOrderInfo.setIsParent(false);
        productOrderInfo.setPhone(createOrderVo.getMobile());
        productOrderInfo.setAddress(receiveAddress);
        productOrderInfo.setLatitude(latitude);
        productOrderInfo.setLongitude(longitude);
        productOrderInfo.setBizType(1);
        productOrderInfo.setOrderType(orderType);
        productOrderInfo.setPayType(QueryPayType.ONLINE_PAY);
        if (Objects.nonNull(createOrderVo.getUnionPayCard())) {
            productOrderInfo.setPayChannel(PayChannel.USVCP.getCode());
            productOrderInfo.setPayChannelName(PayChannel.USVCP.getDesc());
        } else if (StringUtils.isNotBlank(createOrderVo.getCardCode())) {
            productOrderInfo.setPayChannel("10102");
            productOrderInfo.setPayChannelName("储值卡支付");
        }
        productOrderInfo.setSource(OrderSourceType.SAAS.getCode());
        productOrderInfo.setSourceName(OrderSourceType.SAAS.getDesc());
        productOrderInfo.setRemark(remark);
        productOrderInfo.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));
        productOrderInfo.setAddInfo(deliveryTypeInfo);
        productOrderInfo.setAmount(0L);
        productOrderInfo.setBarCounter(createOrderVo.getTableNumber());
        productOrderInfo.setOrderClient(OrderClientType.SAAS.getIndex());
        ArrayList<CreateOrderAccountRequest> orderAccountDtos = new ArrayList<>();
        long deliveryAmount = 0;
        long discountDeliveryAmount = 0;
        if (createOrderVo.getMenuType().equals(BusinessTypeEnum.SAAS_DELIVERY.getCode())) {
            deliveryAmount = shoppingCartGoodsDto.getDeliveryAmount();
            discountDeliveryAmount = shoppingCartGoodsDto.getDeliveryAmount();
            if (shoppingCartGoodsDto.getIsDiscountDelivery() && deliveryAmount > shoppingCartGoodsDto.getDiscountDeliveryAmount()) {
                discountDeliveryAmount = shoppingCartGoodsDto.getDiscountDeliveryAmount();
            }

        }
        Long cardDiscountAmount = shoppingCartGoodsDto.getCardDiscountAmount() != null ? shoppingCartGoodsDto.getCardDiscountAmount() : 0L;
        Long packageAmount = shoppingCartGoodsDto.getPackageAmount() == null ? 0L : shoppingCartGoodsDto.getPackageAmount();
        productOrderInfo.setAmount(shoppingCartGoodsDto.getTotalAmount() + discountDeliveryAmount + packageAmount
                - shoppingCartGoodsDto.getCardOriginalAmount() + cardDiscountAmount);
        // 解析购物车信息
        List<ShoppingCartGoodsDto.CartGoodsDetailDto> cartGoodsDetailDtos = shoppingCartGoodsDto.getProducts();
        List<ActivityDiscountsDto> activityDiscountsDtos = shoppingCartGoodsDto.getActivityDiscountsDtos();
        List<CreateOrderProductRequest> products = new ArrayList<>();
        // 根据购物车商品信息获取优惠信息
        for (ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto : cartGoodsDetailDtos) {
            Integer qty = cartGoodsDetailDto.getQty();
            if (qty > 0) {
                CreateOrderProductRequest createOrderProductDto = convent2OrderProduct(cartGoodsDetailDto);
                createOrderProductDto.setIgnoreProductPrice(1);
                products.add(createOrderProductDto);
                if (CollectionUtils.isNotEmpty(cartGoodsDetailDto.getActivityDiscountsDtos())) {
                    createOrderProductDto.setAccounts(getAccounts(createOrderProductDto, cartGoodsDetailDto.getActivityDiscountsDtos()));
                }
            }
        }
        productOrderInfo.setProducts(products);

        int orderAccountIndex = 0;

        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();
            orderAccountDtos.add(createOrderAccountDto);
        }
        if (deliveryAmount > 0) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId("")
                    .name("配送费")
                    .price(deliveryAmount)
                    .accountType(QueryOrderAccountType.DELIVERY_AMOUNT)
                    .sequence(orderAccountIndex++)
                    .actualPrice(discountDeliveryAmount)
                    .build();
            orderAccountDtos.add(createOrderAccountDto);
        }
        if (packageAmount > 0) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId("")
                    .name("包装费")
                    .price(packageAmount)
                    .accountType(QueryOrderAccountType.PACK_AMOUNT)
                    .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(QueryOrderAccountType.CUSTOMER_SCORE)
                    .sequence(orderAccountIndex++)
                    .build();
            orderAccountDtos.add(createOrderAccountDto);
        }
        productOrderInfo.setAccounts(CollectionUtils.isNotEmpty(orderAccountDtos) ? orderAccountDtos : Collections.emptyList());

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

        //设置库存扣减
        if (CollectionUtils.isNotEmpty(shoppingCartGoodsDto.getStocks())) {
            List<ActivityUpdateStockRequest.StockBeanDto> stocks = new ArrayList<>();
            for (SubtractStockVO stockVO : shoppingCartGoodsDto.getStocks()) {
                ActivityUpdateStockRequest.StockBeanDto stockBeanDto = new ActivityUpdateStockRequest.StockBeanDto();
                stockBeanDto.setActivityCode(stockVO.getActivityCode());
                stockBeanDto.setActivityStock(stockVO.getActivityStock() == null ? 1 : stockVO.getActivityStock());
                if (CollectionUtils.isNotEmpty(stockVO.getGoodsStock())) {
                    List<GoodsStockDTO> goodsStockDTOS = new ArrayList<>();
                    stockVO.getGoodsStock().forEach(goods -> {
                        GoodsStockDTO goodsStockDTO = new GoodsStockDTO();
                        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);
                }
                stocks.add(stockBeanDto);
            }
            activityUpdateStockRequest.setStock(stocks);
        }
        productOrderInfo.setActivityUpdateStockRequest(activityUpdateStockRequest);
        return productOrderInfo;
    }

    public CreateFatherSonOrderRequest.OrderInfo convertMemberOrderInfo(CreateOrderVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto, QueryOrderType orderType) {
        CreateFatherSonOrderRequest.OrderInfo memberOrderInfo = new CreateFatherSonOrderRequest.OrderInfo();
        memberOrderInfo.setPartnerId(createOrderVo.getPartnerId());
        memberOrderInfo.setBizType(3);
        memberOrderInfo.setShopId(createOrderVo.getShopId());
        memberOrderInfo.setShopName(createOrderVo.getStoreName());
        memberOrderInfo.setOrderType(orderType);
        memberOrderInfo.setIsParent(false);
        memberOrderInfo.setOrderClient(OrderClientType.I_MEMBER.getIndex());
        if (Objects.nonNull(createOrderVo.getUnionPayCard())) {
            memberOrderInfo.setPayChannel(PayChannel.USVCP.getCode());
            memberOrderInfo.setPayChannelName(PayChannel.USVCP.getDesc());
        } else if (StringUtils.isNotBlank(createOrderVo.getCardCode())) {
            memberOrderInfo.setPayChannel("10102");
            memberOrderInfo.setPayChannelName("储值卡支付");
        }
        Long cardOriginalAmount = shoppingCartGoodsDto.getCardOriginalAmount() != null ? shoppingCartGoodsDto.getCardOriginalAmount() : 0L;
        ArrayList<CreateOrderAccountRequest> orderAccountDtos = new ArrayList();
        if (cardOriginalAmount > 0) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId("")
                    .name("会员卡原价")
                    .price(cardOriginalAmount)
                    .accountType(QueryOrderAccountType.CARD_ORIGINAL_AMOUNT)
                    .sequence(1)
                    .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(QueryOrderAccountType.CARD_DISCOUNT_AMOUNT)
                    .sequence(2)
                    .build();
            orderAccountDtos.add(createOrderAccountDto);
        }
        memberOrderInfo.setAccounts(orderAccountDtos);
        return memberOrderInfo;
    }

    public CreateFatherSonOrderRequest.OrderInfo convertFatherOrderInfo(CreateOrderVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto, UserDeliveryInfoDto userDeliveryInfoDto, QueryOrderType orderType) {
        CreateFatherSonOrderRequest.OrderInfo fatherOrderInfo = new CreateFatherSonOrderRequest.OrderInfo();
        fatherOrderInfo.setPartnerId(createOrderVo.getPartnerId());
        //虚拟订单
        fatherOrderInfo.setBizType(2);
        //是父订单
        fatherOrderInfo.setIsParent(true);
        fatherOrderInfo.setOrderClient(OrderClientType.SAAS.getIndex());
        fatherOrderInfo.setOrderType(orderType);
        if (Objects.nonNull(createOrderVo.getUnionPayCard())) {
            fatherOrderInfo.setPayChannel(PayChannel.USVCP.getCode());
            fatherOrderInfo.setPayChannelName(PayChannel.USVCP.getDesc());
        } else if (StringUtils.isNotBlank(createOrderVo.getCardCode())) {
            fatherOrderInfo.setPayChannel("10102");
            fatherOrderInfo.setPayChannelName("储值卡支付");
        }
        /**
         long deliveryAmount = 0;
         if (userDeliveryInfoDto != null) {
         deliveryAmount = getUserRealDeliveryAmount(userDeliveryInfoDto.getStoreDeliveryInfoDto(), userDeliveryInfoDto.getUserLongitude(), userDeliveryInfoDto.getUserLatitude());
         }*/

        long discountDeliveryAmount = 0;
        if (BusinessTypeEnum.SAAS_DELIVERY.getCode().equals(createOrderVo.getMenuType())) {
            long deliveryAmount = shoppingCartGoodsDto.getDeliveryAmount();
            discountDeliveryAmount = shoppingCartGoodsDto.getDeliveryAmount();
            if (shoppingCartGoodsDto.getIsDiscountDelivery() && deliveryAmount > shoppingCartGoodsDto.getDiscountDeliveryAmount()) {
                discountDeliveryAmount = shoppingCartGoodsDto.getDiscountDeliveryAmount();
            }
        }

        Long packageAmount = shoppingCartGoodsDto.getPackageAmount() == null ? 0 : shoppingCartGoodsDto.getPackageAmount();
        fatherOrderInfo.setAmount(shoppingCartGoodsDto.getTotalAmount() + discountDeliveryAmount + packageAmount);
        return fatherOrderInfo;
    }


    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 QueryOrdersDto convent2QueryOrdersDto(QueryOrderDto queryOrderDto, String memberId, String channelType) {
        QueryOrdersDto queryOrdersDto = new QueryOrdersDto();
        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);

        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 if (OrderChannelType.BEAUTIFUL.getCode().equals(channelType)) {
            queryOrdersDto.setSource(new String[]{"beautiful"});
        } else if (OrderChannelType.CASHIER.getCode().equals(channelType)) {
            queryOrdersDto.setSource(new String[]{"cashier"});
        } 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());
        //TODO 查询退款的待确定
        if (queryOrderDto.getQueryOrderStatus() != null) {
            if (QueryOrderStatus.ALL_BILL.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                queryOrdersDto.setStatus(OrderStatus.getAllCodes());

                if (Objects.equals(queryOrderDto.getMarketingType(), (int) OrderMarketType.GROUPB.getIndex())) {
                    Integer[] statuses = new Integer[]{OrderStatus.TAKE_ORDER.getCode(), OrderStatus.WAIT_PAY.getCode(), OrderStatus.RECEIPT.getCode(),
                            OrderStatus.DISTRIBUTION.getCode(), OrderStatus.COMPLETE.getCode()};
                    queryOrdersDto.setStatus(statuses);
                }
            }
            if (QueryOrderStatus.TAKE_MEAL.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                Integer[] statuses = new Integer[]{OrderStatus.TAKE_ORDER.getCode(), OrderStatus.RECEIPT.getCode(),
                        OrderStatus.DISTRIBUTION.getCode(), OrderStatus.COMPLETE_MAKE.getCode()};
                queryOrdersDto.setStatus(statuses);
            }
            if (QueryOrderStatus.FINISH.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                queryOrdersDto.setStatus(new Integer[]{OrderStatus.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[]{OrderStatus.CALCEL.getCode()});
            }
            if (QueryOrderStatus.ORDER_CANCEL_MIXUE.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                queryOrdersDto.setStatus(new Integer[]{OrderStatus.CALCEL.getCode()});
                queryOrdersDto.setPayStatus(new Integer[]{PayStatus.NOT_PAY.getCode()});
            }

        }

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

        if (OrderChannelType.IWC.getCode().equals(channelType)) {
            Integer[] statuses = new Integer[]{OrderStatus.COMPLETE.getCode(), OrderStatus.CALCEL.getCode(), OrderStatus.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);
        }

        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()));

        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(OrderStatus.getAllCodes());
                setStatus.addAll(integers);
            }
            if (queryOrderDto.getQueryOrderStatus().contains(QueryOrderStatus.TAKE_MEAL.getCode())) {
                Integer[] statuses = new Integer[]{OrderStatus.TAKE_ORDER.getCode(), OrderStatus.RECEIPT.getCode(),
                        OrderStatus.DISTRIBUTION.getCode(), OrderStatus.COMPLETE_MAKE.getCode()};
                List<Integer> integers = Arrays.asList(statuses);
                setStatus.addAll(integers);
            }
            if (queryOrderDto.getQueryOrderStatus().contains(QueryOrderStatus.FINISH.getCode())) {
                setStatus.add(OrderStatus.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(OrderStatus.CALCEL.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(OrderType.COLLECT_GOODS.getCode())) {
                set.add(OrderType.COLLECT_GOODS.getCode());
                set.add(OrderType.EAT_IN.getCode());
            }
            if (queryOrderDto.getQueryOrderType().contains(OrderType.TAKE_OUT.getCode())) {
                set.add(OrderType.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 (OrderClientType.SAASMALL.getIndex().toString() == ordersBean.getOrderClient()) {
                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 (OrderType.TAKE_OUT.getCode() == ordersBean.getType().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 (OrderType.COLLECT_GOODS.getCode().equals(ordersBean.getType())) {
                responseVo.setTakeOut(1);
                responseVo.setTakeOutDesc("打包带走");
            } else if (OrderType.EAT_IN.getCode().equals(ordersBean.getType())) {
                responseVo.setTakeOut(0);
                responseVo.setTakeOutDesc("店内就餐");
            } else {
                responseVo.setTakeOut(0);
                responseVo.setTakeOutDesc("");
            }
            //配置麦咖啡文案
            if (OrderType.TAKE_OUT.getCode().equals(ordersBean.getType())) {
                responseVo.setMcCafeOrderTag(maCafeWaimaiTag);
            } else {
                responseVo.setMcCafeOrderTag(maCafePickTag);
            }
            responseVo.setTableNumber(ordersBean.getBarCounter());
            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 (OrderSourceType.ALIPAY.getCode().equals(ordersBean.getSource())) {
                    responseVo.setOrderPayType("支付宝支付");
                    responseVo.setOrderPayTypeDescEn(PayChannelType.ALIPAY.getNameEn());
                } else {
                    responseVo.setOrderPayType("微信支付");
                    responseVo.setOrderPayTypeDescEn(PayChannelType.WECHAT.getNameEn());
                }
//                else if(OrderSourceType.SAAS.getCode().equals(ordersBean.getSource())) {
//                    responseVo.setOrderPayType("微信支付");
//                }
//                else {
//                    responseVo.setOrderPayType("微信支付");
//                }
            }


            //取餐码用日订单序号代替- 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 (!orderCommonService.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 (OrderStatus.COMPLETE.getCode().equals(ordersBean.getStatus()) && 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(), OrderType.COLLECT_GOODS.getCode()) || Objects.equals(responseVo.getOrderType(), OrderType.EAT_IN.getCode()))
                    && !Objects.equals(responseVo.getOrderStatus(), OrderStatus.REFUSE.getCode())
                    && !Objects.equals(responseVo.getOrderStatus(), OrderStatus.CALCEL.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.getType());
            if (IappIdType.WC_XCX.getCode().equals(iAppId)) {
                responseVo.setOrderTypeDesc("围餐");
                responseVo.setOrderTypeDescEn("Round the table");
            } else if (OrderClientType.SAASMALL.getIndex().toString().equalsIgnoreCase(ordersBean.getOrderClient())) {
                responseVo.setOrderTypeDesc("商城订单");
            } else {
                responseVo.setOrderTypeDesc(Optional.ofNullable(OrderTypeGather.getByCode(ordersBean.getType())).map(OrderTypeGather::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 (OrderStatus.REFUSE.getCode().equals(ordersBean.getStatus())
                    || OrderStatus.CALCEL.getCode().equals(ordersBean.getStatus())
                    || OrderStatus.COMPLETE.getCode().equals(ordersBean.getStatus())) {
                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;
            if (CollectionUtils.isNotEmpty(ordersBean.getAccountList())) {
                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());
                        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());
                    }
                }
            }
            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 (OrderStatus.TAKE_ORDER.getCode().equals(ordersBean.getStatus()) && PayStatus.HAVE_PAID.getCode().equals(ordersBean.getPayStatus())) {
                responseVo.setEnableRefund(true);
            }
            responseVo.setBizType(ordersBean.getBizType());
            //6:卖券虚拟商品 暂不能申请退款
            if (ordersBean.getBizType() == 6) {
                responseVo.setButtonRefund(false);
            }
            List<Integer> enableRefundCodes = Lists.newArrayList(Arrays.asList(
                    OrderStatus.RECEIPT.getCode(), OrderStatus.COMPLETE_MAKE.getCode()));
            if (enableRefundCodes.contains(ordersBean.getStatus()) && 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.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 (OrderType.TAKE_OUT.getCode().equals(ordersBean.getType()) && 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 (OrderType.COLLECT_GOODS.getCode().equals(orderBean.getType()) || OrderType.EAT_IN.getCode().equals(orderBean.getType())) {
            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 (OrderStatus.TAKE_ORDER.getCode().equals(orderBean.getStatus())) {
                takeMealFlows.get(0).setActive(true);
            }
            if (OrderStatus.RECEIPT.getCode().equals(orderBean.getStatus())) {
                takeMealFlows.get(1).setActive(true);
            }
            if (OrderStatus.COMPLETE_MAKE.getCode().equals(orderBean.getStatus())) {
                takeMealFlows.get(2).setActive(true);
            }
        }
        if (OrderType.TAKE_OUT.getCode().equals(orderBean.getType())) {
            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 (OrderStatus.TAKE_ORDER.getCode().equals(orderBean.getStatus())) {
                takeMealFlows.get(0).setActive(true);
            }
            if (OrderStatus.RECEIPT.getCode().equals(orderBean.getStatus())) {
                takeMealFlows.get(1).setActive(true);
            }
            if (OrderStatus.DISTRIBUTION.getCode().equals(orderBean.getStatus())) {
                takeMealFlows.get(2).setActive(true);
            }
            if (OrderStatus.COMPLETE.getCode().equals(orderBean.getStatus())) {
                takeMealFlows.get(3).setActive(true);
            }
        }
        return takeMealFlows;
    }


    public OrderViewStatusDto getOrderViewStatusDesc(OrderBeanV1 orderBean, String wxAppId) {
        OrderViewStatusDto orderViewStatusDto = new OrderViewStatusDto();
        AppLogUtil.infoLog("getOrderStatusDesc start ", JSON.toJSONString(orderBean), "");
        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 (OrderType.COLLECT_GOODS.getCode().equals(orderBean.getType()) || OrderType.EAT_IN.getCode().equals(orderBean.getType())) {
            if (OrderStatus.WAIT_PAY.getCode().equals(orderBean.getStatus())) {
                orderViewStatusDto.setOrderStatus(OrderStatus.WAIT_PAY.getCode());
                orderViewStatusDto.setOrderStatusDesc(OrderStatus.WAIT_PAY.getDesc());
                orderViewStatusDto.setOrderStatusDescEn(OrderStatus.WAIT_PAY.getDescEn());
                orderViewStatusDto.setOrderStatusDescText("");
            }
            if (OrderStatus.CALCEL.getCode().equals(orderBean.getStatus())) {
                orderViewStatusDto.setOrderStatus(OrderStatus.CALCEL.getCode());
                orderViewStatusDto.setOrderStatusDesc(OrderStatus.CALCEL.getDesc());
                orderViewStatusDto.setOrderStatusDescEn(OrderStatus.CALCEL.getDescEn());
                orderViewStatusDto.setOrderStatusDescText("");
            }
            if (OrderStatus.TAKE_ORDER.getCode().equals(orderBean.getStatus())) {
                if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatus.TAKE_ORDER.getCode());
                    orderViewStatusDto.setOrderStatusDesc(conventCreateOrderString(orderBean));
//                  orderViewStatusDto.setOrderStatusDesc(OrderStatus.TAKE_ORDER.getDesc());
                    orderViewStatusDto.setOrderStatusDescEn(OrderStatus.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 (OrderStatus.RECEIPT.getCode().equals(orderBean.getStatus())) {
                if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatus.RECEIPT.getCode());
//                  orderViewStatusDto.setOrderStatusDesc(OrderStatus.RECEIPT.getDesc());
                    orderViewStatusDto.setOrderStatusDescEn(OrderStatus.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 (OrderStatus.COMPLETE_MAKE.getCode().equals(orderBean.getStatus())) {
                if (refundBean == null) {
                    orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                }
                if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatus.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 (OrderType.TAKE_OUT.getCode().equals(orderBean.getType())) {
            if (OrderClientType.SAASMALL.getIndex().toString().equalsIgnoreCase(orderBean.getOrderClient())) {
                if (OrderStatus.WAIT_PAY.getCode().equals(orderBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatus.WAIT_PAY.getCode());
                    orderViewStatusDto.setOrderStatusDesc("待支付");
                    orderViewStatusDto.setOrderStatusDescText("");
                }
                if (OrderStatus.TAKE_ORDER.getCode().equals(orderBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatus.WAIT_PAY.getCode());
                    orderViewStatusDto.setOrderStatusDesc("已支付");
                    orderViewStatusDto.setOrderStatusDescText("");
                }
                if (OrderStatus.RECEIPT.getCode().equals(orderBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatus.RECEIPT.getCode());
                    orderViewStatusDto.setOrderStatusDesc("待发货");
                    orderViewStatusDto.setOrderStatusDescText("请稍等片刻，商品即将发货哦~");
                    orderViewStatusDto.setRiderName("商品即将发货");
                    orderViewStatusDto.setRiderText("正在为您商品打包");
                    orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                    orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                    orderViewStatusDto.setButtonContactPartner(true);
                }
                if (OrderStatus.DISTRIBUTION.getCode().equals(orderBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatus.DISTRIBUTION.getCode());
                    orderViewStatusDto.setOrderStatusDesc("已发货");
                    orderViewStatusDto.setOrderStatusDescText("请稍等片刻，商品已经发货哦~");
                    orderViewStatusDto.setRiderName("商家自配送");
                    orderViewStatusDto.setRiderText("商品运输中");
                    orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                    orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                    orderViewStatusDto.setButtonContactPartner(true);
                }
                if (OrderStatus.COMPLETE.getCode().equals(orderBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatus.COMPLETE.getCode());
                    orderViewStatusDto.setOrderStatusDesc("已完成");
                    orderViewStatusDto.setOrderStatusDescText("订单已经完成，记得来评价一下哦~");
                    orderViewStatusDto.setRiderName("订单已完成");
                    orderViewStatusDto.setRiderText("订单已经完成，记得来评价一下哦");
                    orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                    orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                    orderViewStatusDto.setButtonContactPartner(true);
                }
                if (OrderStatus.CALCEL.getCode().equals(orderBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatus.CALCEL.getCode());
                    orderViewStatusDto.setOrderStatusDesc("已取消");
                    orderViewStatusDto.setOrderStatusDescText("订单已经取消~");
                    orderViewStatusDto.setRiderName("订单已取消");
                    orderViewStatusDto.setRiderText("订单已经取消");
                    orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                    orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
                    orderViewStatusDto.setButtonContactPartner(true);
                }
            } else {
                if (OrderStatus.WAIT_PAY.getCode().equals(orderBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatus.WAIT_PAY.getCode());
                    orderViewStatusDto.setOrderStatusDesc(OrderStatus.WAIT_PAY.getDesc());
                    orderViewStatusDto.setOrderStatusDescEn(OrderStatus.WAIT_PAY.getDescEn());
                    orderViewStatusDto.setOrderStatusDescText("");
                }
                if (OrderStatus.TAKE_ORDER.getCode().equals(orderBean.getStatus())) {
                    if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                        if (orderBean.getDeliverStatus() == null) {
                            orderViewStatusDto.setRiderName("商家自配送");
                        } else {
                            orderViewStatusDto.setRiderName("处理中");
                        }
                        orderViewStatusDto.setOrderStatus(OrderStatus.TAKE_ORDER.getCode());
                        orderViewStatusDto.setOrderStatusDesc(conventCreateOrderString(orderBean));
                        orderViewStatusDto.setOrderStatusDescEn(OrderStatus.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 (OrderStatus.RECEIPT.getCode().equals(orderBean.getStatus())) {
                    if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                        if (orderBean.getDeliverStatus() == null) {
                            orderViewStatusDto.setOrderStatus(OrderStatus.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(OrderStatus.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 (OrderStatus.COMPLETE_MAKE.getCode().equals(orderBean.getStatus())) {
                    if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                        if (orderBean.getDeliverStatus() == null) {
                            orderViewStatusDto.setOrderStatus(OrderStatus.COMPLETE_MAKE.getCode());
                            orderViewStatusDto.setOrderStatusDesc("配送中");
                            orderViewStatusDto.setOrderStatusDescText("请稍等片刻，美味即将到达哦~");
                            orderViewStatusDto.setRiderName("商家自配送");
                            orderViewStatusDto.setRiderText("配送员已送出");
                            orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                            orderViewStatusDto.setButtonContactPartner(true);
                        } else {
                            orderViewStatusDto.setOrderStatus(OrderStatus.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(OrderStatus.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 (OrderStatus.DISTRIBUTION.getCode().equals(orderBean.getStatus())) {
                    if (orderBean.getDeliverStatus() == null || DeliverStatus.OTHER.getCode().equals(orderBean.getDeliverStatus())
                            || DeliverStatus.DELIVER_OTHER.getCode().equals(orderBean.getDeliverStatus())) {
                        orderViewStatusDto.setOrderStatus(OrderStatus.DISTRIBUTION.getCode());
                        orderViewStatusDto.setOrderStatusDesc(OrderStatus.DISTRIBUTION.getDesc());
                        orderViewStatusDto.setOrderStatusDescEn(OrderStatus.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(OrderStatus.DISTRIBUTION.getDesc());
                            orderViewStatusDto.setOrderStatusDescEn(OrderStatus.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 (!OrderClientType.SAASMALL.getIndex().toString().equalsIgnoreCase(orderBean.getOrderClient())) {
            /**由于下方部分状态描述未找到枚举类，直接赋值英文字段**/
            if (refundBean != null && RefundStatus.AGREE_REFUND.getCode().equals(refundBean.getStatus())) {
                orderViewStatusDto.setOrderStatus(OrderStatus.CALCEL.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(OrderStatus.CALCEL.getCode());
                orderViewStatusDto.setOrderStatusDesc("退款中");
                orderViewStatusDto.setOrderStatusDescEn("Refund in progress");
                orderViewStatusDto.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
                orderViewStatusDto.setRefundStatusText("正在退款中，请稍等");
                orderViewStatusDto.setButtonContactPartner(true);
            }
            if (OrderStatus.REFUSE.getCode().equals(orderBean.getStatus())) {
                orderViewStatusDto.setOrderStatus(OrderStatus.REFUSE.getCode());
                orderViewStatusDto.setOrderStatusDesc(PayStatus.HAVE_REFUND.getDesc());
                orderViewStatusDto.setOrderStatusDescEn(PayStatus.HAVE_REFUND.getDescEn());
                orderViewStatusDto.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
                orderViewStatusDto.setRefundStatusText("订单金额已原路退还，请及时查看~");
                orderViewStatusDto.setButtonContactPartner(true);
            }
            if (PayStatus.HAVE_REFUND.getCode().equals(orderBean.getPayStatus())) {
                orderViewStatusDto.setOrderStatus(OrderStatus.REFUSE.getCode());
                orderViewStatusDto.setOrderStatusDesc(PayStatus.HAVE_REFUND.getDesc());
                orderViewStatusDto.setOrderStatusDescEn(PayStatus.HAVE_REFUND.getDescEn());
                orderViewStatusDto.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
                orderViewStatusDto.setRefundStatusText("订单金额已原路退还，请及时查看~");
                orderViewStatusDto.setButtonContactPartner(true);
            }

            if (OrderStatus.COMPLETE.getCode().equals(orderBean.getStatus())) {
                // 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(OrderStatus.COMPLETE.getCode());
                orderViewStatusDto.setOrderStatusDesc(OrderStatus.COMPLETE.getDesc());
                orderViewStatusDto.setOrderStatusDescEn(OrderStatus.COMPLETE.getDescEn());
                orderViewStatusDto.setOrderStatusDescText("订单已完成，记得来评价一下哦~");
                orderViewStatusDto.setButtonContactPartner(true);
                orderViewStatusDto.setButtonEvaluate(true);
                if (OrderType.TAKE_OUT.getCode().equals(orderBean.getType())) {
                    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());
                    }
                }
            }
        }
        return orderViewStatusDto;
    }

    /**
     * 是否支持退款
     *
     * @param orderBean 订单详情
     * @param wxAppId   wxappId
     * @return
     */
    public boolean checkRefundButton(OrderBeanV1 orderBean, String wxAppId) {
        OrderStatus status = OrderStatus.getByCode(orderBean.getStatus());
        if (Objects.isNull(status)) {
            return false;
        }
        // [华莱士20210410] 微商城订单判断
        if (Objects.equals(com.freemud.sdk.api.assortment.order.enums.OrderSourceType.SAASMALL.getCode(), orderBean.getSource())) {
            // 除 未支付 拒单 和 取消外，其他可退款
            return Stream.of(OrderStatus.WAIT_PAY, OrderStatus.REFUSE, OrderStatus.CALCEL).noneMatch(s -> Objects.equals(status, s));
        }
        // 爱马哥 预定单 付款之后 预定当天之前的时间都可退款
        if (orderBean.getBizType().compareTo(BizTypeEnum.ADVANCE_ORDER.getBizType()) == 0) {
           return this.checkAdvanceOrder(orderBean.getGmtExpect());
        }

        // 加价购选择虚拟商品券包，订单完成前可申请退款，完成之后不能申请退款
        if (OrderStatus.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 (OrderClientType.CASHIER.getIndex().toString().equals(orderBean.getOrderClient())) {
            //收银单，使用收银单的退款配置
            hashKey = OrderRedisKeyConstant.HashKeyForOrderRefundConfig.CASHIER;
        } else {
            hashKey = OrderType.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 (OrderClientType.CASHIER.getIndex().toString().equals(orderBean.getOrderClient())) {
            //收银单，使用收银单的退款配置 收银单只有完成的订单，直接判断是否可以退款就行
            orderRefund = config.getCashierOrderRefund();
        } else if (OrderType.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 (OrderStatus.COMPLETE.getCode().equals(status.getCode()) && canRefund) {
            long currentTime = System.currentTimeMillis();
            long gmtModified = orderBean.getGmtModified();
            // 因允许退款日期在外卖类型的value中，如果订单类型为堂食，则会取不到这个值
            if (!OrderType.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;
    }

    /**
     * 预约时间
     * @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 == OrderSettlementType.PRODUCT_COUPON.getIndex() || type == OrderSettlementType.CASH_COUPON.getIndex()
                        || type == OrderSettlementType.DISCOUNT_COUPON.getIndex()) {
                    accountVo.setTypeName("优惠券");
                } else if (type == OrderSettlementType.FULL_REDUCTION.getIndex()) {
                    accountVo.setTypeName("满减");
                } else if (type == OrderSettlementType.POINTS.getIndex()) {
                    accountVo.setTypeName("积分抵扣");
                } else if (type == OrderSettlementType.FREIGHT_COUPON.getIndex()) {
                    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 (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 com.freemud.sdk.api.assortment.payment.request.OrderRefundRequest getOrderPayRefundRequest(OrderBeanV1 orderBean, Long refundId, String fatherOrderId) {
        com.freemud.sdk.api.assortment.payment.request.OrderRefundRequest orderPayRefundRequest = new com.freemud.sdk.api.assortment.payment.request.OrderRefundRequest();
        orderPayRefundRequest.setOrgTransId(fatherOrderId);
        orderPayRefundRequest.setPartnerId(orderBean.getCompanyId());
        orderPayRefundRequest.setStoreId(orderBean.getShopId());
        orderPayRefundRequest.setOrgPayFmId(orderBean.getPayVoucher());
        orderPayRefundRequest.setRefundAmount(orderBean.getAmount());
        orderPayRefundRequest.setRefundId(refundId);
        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);
        if (AfterSalesType.SYSTEM_CANCEL.getIndex().equals(afterSalesType.getIndex())) {
            cancelOrderRequest.setOperator("admin");
        }
        //若为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.getType());
        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) {
        CreateOrderProductRequest createOrderProductDemoDto = new CreateOrderProductRequest();
        createOrderProductDemoDto.setProductId(StringUtils.isNotBlank(cartGoodsDetailDto.getSpuId()) ? cartGoodsDetailDto.getSpuId() : cartGoodsDetailDto.getSkuId());
        createOrderProductDemoDto.setProductName(cartGoodsDetailDto.getSpuName());
        createOrderProductDemoDto.setProductForeignName(cartGoodsDetailDto.getSpuForeignName());
        createOrderProductDemoDto.setOriginalProductType(cartGoodsDetailDto.getOriginalProductType());
        createOrderProductDemoDto.setSpecification(cartGoodsDetailDto.getSkuId());
        createOrderProductDemoDto.setSpecificationName(cartGoodsDetailDto.getSkuName());
        createOrderProductDemoDto.setSpecificationForeignName(cartGoodsDetailDto.getSkuForeignName());
        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.setCategory(cartGoodsDetailDto.getClassificationId());
        createOrderProductDemoDto.setTax(cartGoodsDetailDto.getTax());
        createOrderProductDemoDto.setTaxId(cartGoodsDetailDto.getTaxId());
        createOrderProductDemoDto.setClassificationId(cartGoodsDetailDto.getClassificationId());
        createOrderProductDemoDto.setClassificationName(cartGoodsDetailDto.getClassificationName());
        createOrderProductDemoDto.setUserId(cartGoodsDetailDto.getUserId());
        createOrderProductDemoDto.setOpenId(cartGoodsDetailDto.getOpenId());
        createOrderProductDemoDto.setNickName(cartGoodsDetailDto.getUserName());
        createOrderProductDemoDto.setPhotoUrl(cartGoodsDetailDto.getPhotoUrl());
        createOrderProductDemoDto.setPackPrice(cartGoodsDetailDto.getPackPrice());
        createOrderProductDemoDto.setIsSendGoods(cartGoodsDetailDto.getIsSendGoods());

        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) {
        CreateOrderProductRequest createOrderProductDemoDto = new CreateOrderProductRequest();
        createOrderProductDemoDto.setProductId(cartGoodsDetailDto.getSpuId());
        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());
        if (cartGoodsDetailDto.getIsTableware() == 0) {
            createOrderProductDemoDto.setProductType(productType);
        } else {
            createOrderProductDemoDto.setProductType(ProductTypeEnum.TABLEWARE_PRODUCT.getCode());
        }
        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.setSplitIndex(cartGoodsDetailDto.getSplitIndex());
        createOrderProductDemoDto.setProductGroupId(cartGoodsDetailDto.getProductGroupId());
        createOrderProductDemoDto.setIsSendGoods(cartGoodsDetailDto.getIsSendGoods());
        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()));
            });
        }
        return createOrderProductDemoDto;
    }

    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;
    }

//    public QueryOrderAccountType getQueryOrderAccountType(Integer activityType) {
//        if (ActivityTypeEnum.TYPE_11.getCode().equals(activityType) || ActivityTypeEnum.TYPE_12.getCode().equals(activityType)) {
//            return QueryOrderAccountType.BUY_DISCOUNT;
//        }
//        if (ActivityTypeEnum.TYPE_3.getCode().equals(activityType)) {
//            return QueryOrderAccountType.COUPON;
//        }
//        if (ActivityTypeEnum.TYPE_2.getCode().equals(activityType)) {
//            return QueryOrderAccountType.DISCOUNT_AMOUNT;
//        }
//        if (ActivityTypeEnum.TYPE_81.getCode().equals(activityType)) {
//            return QueryOrderAccountType.PREMIUM_EXCHANGE;
//        }
//        if (ActivityTypeEnum.TYPE_32.getCode().equals(activityType)) {
//            return QueryOrderAccountType.PRODUCT_COUPON;
//        }
//        if (ActivityTypeEnum.TYPE_31.getCode().equals(activityType)) {
//            return QueryOrderAccountType.DISCOUNT_COUPON;
//        }
//        if (ActivityTypeEnum.TYPE_PACKAGE.getCode().equals(activityType)) {
//            return QueryOrderAccountType.PACK_AMOUNT;
//        }
//        if (ActivityTypeEnum.TYPE_DELIVERY.getCode().equals(activityType)) {
//            return QueryOrderAccountType.DELIVERY_AMOUNT;
//        }
//        if (ActivityTypeEnum.TYPE_61.getCode().equals(activityType)) {
//            return QueryOrderAccountType.BUYM_SENDN;
//        }
//
//        return null;
//    }


//    public boolean isCouponType(Integer type) {
//        return type.equals(ActivityTypeEnum.TYPE_3.getCode()) || type.equals(ActivityTypeEnum.TYPE_31.getCode()) || type.equals(ActivityTypeEnum.TYPE_32.getCode());
//    }

//    public SyncStatusDto convent2SyncStatusDtoCreate(AssortmentOpenPlatformWxapp wxApp, UserLoginInfoDto userLoginInfoDto, CreateOrderDto createOrderDto, String oid) {
//        SyncStatusDto syncStatusDto = new SyncStatusDto();
//        syncStatusDto.setSp_mchid(SPMCHID);
//        syncStatusDto.setSub_mchid(wxApp.getMchId());
//        syncStatusDto.setSp_appid(SPWXAPPID);
//        syncStatusDto.setSub_appid(userLoginInfoDto.getWxAppId());
//        syncStatusDto.setOut_shop_no(createOrderDto.getShopId());
//        syncStatusDto.setOpenid(userLoginInfoDto.getOpenId());
//        syncStatusDto.setLogin_token(userLoginInfoDto.getSessionKey());
//        syncStatusDto.setOrder_entry(ENTRYPAGE);
//        syncStatusDto.setUser_amount(createOrderDto.getAmount().intValue());
//        syncStatusDto.setStatus(WechatSyncStatus.CREATE_DEAL.getCode());
//        syncStatusDto.setAction_time(Rfc3339Util.dateToRfc3339(new Date()));
//        syncStatusDto.setOut_order_no(oid);
//        List<CreateOrderProductDto> products = createOrderDto.getProducts();
//        List<SyncStatusDto.DishInfo> list = Lists.newArrayList();
//        int totalAmount = 0;
//        int discountAmount = 0;
//        for (CreateOrderProductDto productDto : products) {
//            SyncStatusDto.DishInfo dishInfo = new SyncStatusDto.DishInfo();
//            dishInfo.setOut_dish_no(productDto.getProductId());
//            dishInfo.setName(productDto.getProductName());
//            dishInfo.setPrice(productDto.getPrice().intValue());
//            dishInfo.setUnit(WechatUnitType.BY_SHARE.getCode());
//            dishInfo.setCount(productDto.getNumber().floatValue());
//            list.add(dishInfo);
//            totalAmount += productDto.getPrice().intValue() * productDto.getNumber();
//            discountAmount += productDto.getSalePrice().intValue() * productDto.getNumber();
//        }
//        syncStatusDto.setTotal_amount(totalAmount);
//        syncStatusDto.setDiscount_amount(discountAmount);
//        syncStatusDto.setDish_list(list);
//        return syncStatusDto;
//    }
//
//    public SyncStatusDto convent2SyncStatusDtPay(AssortmentOpenPlatformWxapp wxApp, QueryOrdersResponseDto.DataBean.OrderBean orderBean, String wxappid, String openid, String sessionKey, PaysuccessNoticeMessage message, OrderExtInfoDto orderExtInfoDto) {
//        SyncStatusDto syncStatusDto = new SyncStatusDto();
//        syncStatusDto.setSp_mchid(SPMCHID);
//        syncStatusDto.setSub_mchid(wxApp.getMchId());
//        syncStatusDto.setSp_appid(SPWXAPPID);
//        syncStatusDto.setSub_appid(wxappid);
//        syncStatusDto.setOut_shop_no(orderBean.getShopId());
//        syncStatusDto.setOpenid(openid);
//        syncStatusDto.setLogin_token(sessionKey);
//        syncStatusDto.setOrder_entry(ENTRYPAGE);
//        syncStatusDto.setUser_amount(orderBean.getAmount().intValue());
//        syncStatusDto.setStatus(WechatSyncStatus.PAY_SUCCESS.getCode());
//        syncStatusDto.setAction_time(Rfc3339Util.dateToRfc3339(new Date()));
//        syncStatusDto.setPay_time(Rfc3339Util.strToRfc3339(orderExtInfoDto.getPayDate()));
//        syncStatusDto.setTransaction_id(message.getPaid_no());
//        syncStatusDto.setOut_trade_no(message.getOut_trade_no());
//        syncStatusDto.setOut_order_no(message.getTrans_id());
//        List<SyncStatusDto.DishInfo> list = Lists.newArrayList();
//        int totalAmount = 0;
//        int discountAmount = 0;
//        List<QueryOrdersResponseDto.DataBean.OrderBean.ProductBean> productList = orderBean.getProductList();
//        for (QueryOrdersResponseDto.DataBean.OrderBean.ProductBean productDto : productList) {
//            SyncStatusDto.DishInfo dishInfo = new SyncStatusDto.DishInfo();
//            dishInfo.setOut_dish_no(productDto.getProductId());
//            dishInfo.setName(productDto.getProductName());
//            dishInfo.setPrice(productDto.getPrice().intValue());
//            dishInfo.setUnit(WechatUnitType.BY_SHARE.getCode());
//            dishInfo.setCount(productDto.getNumber());
//            list.add(dishInfo);
//            totalAmount += productDto.getPrice().intValue() * productDto.getNumber();
//            discountAmount += productDto.getSalePrice().intValue() * productDto.getNumber();
//        }
//        syncStatusDto.setTotal_amount(totalAmount);
//        syncStatusDto.setDiscount_amount(discountAmount);
//        syncStatusDto.setDish_list(list);
//        return syncStatusDto;
//    }
//
//    public String convent2Sign(SyncStatusDto syncStatusDto) {
//        String authorization = null;
//        try {
//            SignMessageBuilder signMessageBuilder = new SignMessageBuilder()
//                    .url(new URL("https://api.mch.weixin.qq.com/v3/catering/orders/sync-status"))
//                    .nonceStr(UUID.randomUUID().toString().replace("-", ""))
//                    .timestamp(System.currentTimeMillis() / 1000)
//                    .httpMethod("POST")
//                    .httpBody(gson.toJson(syncStatusDto));
//
//
//            authorization = getAuthorizationString(signMessageBuilder);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return authorization;
//    }

    /**
     * 获取Authorization串
     *
     * @param
     * @return
     * @throws
     * @throws
     */
    public String getAuthorizationString(SignMessageBuilder signMessageBuilder) {

        String signStr = signMessageBuilder.buildMchSignMessage();
        String signater = null;
        try {
            signater = RSAUtils.privateEncrypt(signStr, RSAUtils.getPrivateKey(privatekey));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        String authHeaderValue = "WECHATPAY2-SHA256-RSA2048 "
                + "mchid=\"" + SPMCHID + "\","
                + "nonce_str=\"" + signMessageBuilder.getNonceStr() + "\","
                + "timestamp=\"" + signMessageBuilder.getTimestamp() + "\","
                + "serial_no=\"" + SERIALNO + "\","
                + "signature=\"" + signater + "\"";

        return authHeaderValue;
    }


    /**
     * 获取订单类型转换后 枚举
     *
     * @param oldOrderType
     * @return
     */
    public QueryOrderType convent2OrderTypeEnum(Integer oldOrderType) {

        if (OldOrderType.TAKE_OUT.getCode().equals(oldOrderType)) {
            return QueryOrderType.TAKE_OUT;
        }
        if (OldOrderType.COLLECT_GOODS.getCode().equals(oldOrderType)) {
            return QueryOrderType.COLLECT_GOODS;
        }
        if (OldOrderType.MALL.getCode().equals(oldOrderType)) {
            return QueryOrderType.MALL;
        }
        if (OldOrderType.EAT_IN.getCode().equals(oldOrderType)) {
            return QueryOrderType.EAT_IN;
        }
        return null;
    }

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


    /**
     * 转换第三方配送信息
     */
    public BaseCreateOrderRequest.DeliveryTypeInfo convent2DeliveryTypeInfo(CreateOrderDto.DeliveryTypeInfo oldDeliveryTypeInfo) {
        if (oldDeliveryTypeInfo == null || StringUtils.isBlank(oldDeliveryTypeInfo.getDeliveryType())) {
            return null;
        }
        BaseCreateOrderRequest.DeliveryTypeInfo newDeliveryTypeInfo = new BaseCreateOrderRequest.DeliveryTypeInfo();
        if (QueryDeliveryType.SELF.getCode().equals(oldDeliveryTypeInfo.getDeliveryType())) {
            newDeliveryTypeInfo.setDeliveryType(QueryDeliveryType.SELF);
        }
        if (QueryDeliveryType.THIRD.getCode().equals(oldDeliveryTypeInfo.getDeliveryType())) {
            newDeliveryTypeInfo.setDeliveryType(QueryDeliveryType.THIRD);
        }
        return newDeliveryTypeInfo;
    }

    /**
     * 转换创建订单新
     */
    public CreateOrderResponseVo convent2CreateOrderResponseVo(CreateOrderFlowResponse.CreateOrderResponseVo createOrderResponseVo) {
        if (createOrderResponseVo == null) {
            return null;
        }
        CreateOrderResponseVo createOrder = new CreateOrderResponseVo();
        createOrder.setOid(createOrderResponseVo.getOrderId());
        createOrder.setFmId(createOrderResponseVo.getFmId());
        createOrder.setWxappId(createOrderResponseVo.getWxAppid());
        createOrder.setTimestamp(createOrderResponseVo.getTimestamp());
        createOrder.setNonceStr(createOrderResponseVo.getNonceStr());
        createOrder.setPackageX(createOrderResponseVo.getPackageX());
        createOrder.setSignType(createOrderResponseVo.getSignType());
        createOrder.setSign(createOrderResponseVo.getSign());
        createOrder.setPaySuccess(createOrderResponseVo.getPaySuccess());
        return createOrder;
    }

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

    /**
     * 支付信息转换
     */
    public UnifiedOrderRequest convent2UnifiedOrderRequest(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<UnifiedOrderRequest.ProductBean> productBeans = new ArrayList<UnifiedOrderRequest.ProductBean>();
        if (CollectionUtils.isNotEmpty(orderBean.getProductList())) {
            orderBean.getProductList().forEach(orderProductBean -> {
                UnifiedOrderRequest.ProductBean productBean = new UnifiedOrderRequest.ProductBean();
                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<UnifiedOrderRequest.ProductBean> productBeans = new ArrayList<UnifiedOrderRequest.ProductBean>();
        if (CollectionUtils.isNotEmpty(orderBean.getProductList())) {
            orderBean.getProductList().forEach(orderProductBean -> {
                UnifiedOrderRequest.ProductBean productBean = new UnifiedOrderRequest.ProductBean();
                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
     */
    private 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());
        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.getType() != null) {
            createOrderResponseVo.setOrderType(getNewOrderType(orderBean.getType(), 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);
        }

        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.getType() != null) {
            createOrderResponseVo.setOrderType(getNewOrderType(orderBean.getType(), 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());
        UnifiedOrderResponse.PayOrderBean 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.getSign());
            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());
        MqMessageRequest mqMessageRequest = new MqMessageRequest();
        mqMessageRequest.setBackOrdersNotifyActivityExchange(backOrdersNotifyActivityExchange);
        mqMessageRequest.setBackOrdersNotifyActivityQueue(backOrdersChangeOrderStatusConsumerQueue);
        sdkUpdateOrderProductInfoRequest.setMqMessageRequest(mqMessageRequest);
        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);
            }
        }
//        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);
//        }
//        createOrderDto.setAccounts(CollectionUtils.isNotEmpty(orderAccountDtos) ? orderAccountDtos : Collections.emptyList());

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

        //设置库存扣减
        if (shoppingCartGoodsResponse != null && CollectionUtils.isNotEmpty(shoppingCartGoodsResponse.getStocks())) {
            List<ActivityUpdateStockRequest.StockBeanDto> stocks = new ArrayList<>();
            for (cn.freemud.entities.dto.promotion.SubtractStockVO stockVO : shoppingCartGoodsResponse.getStocks()) {
                ActivityUpdateStockRequest.StockBeanDto stockBeanDto = new ActivityUpdateStockRequest.StockBeanDto();
                stockBeanDto.setActivityCode(stockVO.getActivityCode());
                stockBeanDto.setActivityStock(stockVO.getActivityStock() == null ? 1 : stockVO.getActivityStock());
                if (CollectionUtils.isNotEmpty(stockVO.getGoodsStock())) {
                    List<GoodsStockDTO> goodsStockDTOS = new ArrayList<>();
                    stockVO.getGoodsStock().forEach(goods -> {
                        GoodsStockDTO goodsStockDTO = new GoodsStockDTO();
                        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);
                }
                stocks.add(stockBeanDto);
            }
            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(StoreResponse.BizVO storeResponseDto) {
        OrderExtendedReq orderExtended = new OrderExtendedReq();
        orderExtended.setOrderClientGroupCode(storeResponseDto.getParentCode());
        orderExtended.setOrderClientGroup(storeResponseDto.getParentName());
        return orderExtended;
    }


//    public OrderTaskReq saveOrderTaskReq(String orderWarnTime, Long gmtExpect) {
//        OrderTaskReq orderTaskReq = new OrderTaskReq();
//        Date date = new Date(gmtExpect);
//        long timeStamp = getMinTime(orderWarnTime) * 60 * 1000;
//        Date warnDate = new Date(gmtExpect-timeStamp);
//        orderTaskReq.setTaskTime(DateUtil.convert2String(date,DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
//        orderTaskReq.setProcessingTime(DateUtil.convert2String(warnDate,DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
//        return orderTaskReq;
//    }

//    public Integer getMinTime(String code) {
//        Integer minTime = 0;
//        if(StringUtils.isBlank(code)){
//            return minTime;
//        }
//        switch (code) {
//            case "1":
//                minTime = 15;
//                break;
//            case "2":
//                minTime = 30;
//                break;
//            case "3":
//                minTime = 45;
//                break;
//            case "4":
//                minTime = 60;
//                break;
//            case "5":
//                minTime = 5;
//                break;
//            case "6":
//                minTime = 10;
//                break;
//            default:
//                minTime = 0;
//        }
//        return minTime;
//    }

    /**
     * 新老订单类型转换
     *
     * @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, CreateOrderVo.UnionPayCard 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(cardAmount);
        requestDto.setOrderExtInfoDTO(orderExtInfoDTO);
        requestDto.setTransId(transId);
        requestDto.setOrderClient(orderClient);
        requestDto.setUnionPayCard(unionPayCard);
        return requestDto;
    }

    public CreatePrepayRequestDto convertToCreatePrepayRequestDto(AssortmentCustomerInfoVo userLoginInfoDto, CreateOrderVo createOrderVo,
                                                                  CreateOrderOperateDto createOrderOperateDto, OrderExtInfoDto orderExtInfoDTO) {
        return this.convertToCreatePrepayRequestDto(createOrderVo.getPartnerId()
                , userLoginInfoDto.getWxAppId()
                , userLoginInfoDto.getOpenId()
                , createOrderVo.getFaceCode()
                , createOrderVo.getCardCode()
                , null
                , createOrderOperateDto.getFatherOrderBean()
                , createOrderOperateDto.getProductOrderBean()
                , createOrderOperateDto.getTotalAmount() == null ? 0 : createOrderOperateDto.getTotalAmount()
                , createOrderOperateDto.getCardAmount() == null ? 0 : createOrderOperateDto.getCardAmount()
                , orderExtInfoDTO
                , createOrderOperateDto.getFatherOrderBean().getOid()
                , null
                , createOrderVo.getUnionPayCard()
                , createOrderVo.getShopId()
                , createOrderVo.getChannel() == null ? "" : createOrderVo.getChannel()
        );
    }

    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
            , CreateOrderVo.UnionPayCard unionPayCard
            , String storeId
            , String channel) {
        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(cardAmount);
        requestDto.setOrderExtInfoDTO(orderExtInfoDTO);
        requestDto.setTransId(transId);
        requestDto.setOrderClient(orderClient);
        requestDto.setUnionPayCard(unionPayCard);
        requestDto.setStoreId(storeId);
        requestDto.setChannel(channel);
        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);
    }

    public Integer getNewOrderClient(String name) {
        String _name = OrderSourceType.SAAS.getCode();
        Integer orderClientType;
        switch (name) {
            case "saas":
                orderClientType = 2;
                break;
            case "alipay":
                orderClientType = 3;
                break;
            case "jdwm":
                orderClientType = 10;
                break;
            case "mtwm":
                orderClientType = 11;
                break;
            case "eleme":
                orderClientType = 8;
                break;
            case "bdwm":
                orderClientType = 9;
                break;
            case "ebwm":
                orderClientType = 9;
                break;
            case "saas_member":
                orderClientType = 13;
                break;
            case "saas_order":
                orderClientType = 14;
                break;
            case "pos":
                orderClientType = 15;
                break;
            case "meal":
                orderClientType = 19;
                break;
            case "saasmall":
                orderClientType = 23;
                break;
            default:
                orderClientType = OrderClientType.SAAS.getIndex();
                break;
        }
        return orderClientType;
    }

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

    public List<AssortmentOpenPlatformPartnerWxappConfig> cacheSelectDefaultPage(String wxAppId, String type) {
        if (!StringUtils.isEmpty(wxAppId) && !StringUtils.isEmpty(type)) {
            String hashKey = "ecology:kgd:wxappconfig:open_platform_partner_wxapp_config:appkey_" + wxAppId;
            Object value = redisCache.hashGet(hashKey, type);
            JSONArray jsonArray = value != null ? JSONArray.parseArray(value.toString()) : new JSONArray();
            if (null != jsonArray && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                    jsonObject.remove("@type");
                }
            }
            return (value != null ? JSONObject.parseArray(jsonArray.toString(), AssortmentOpenPlatformPartnerWxappConfig.class) : new ArrayList());
        } else {
            return new ArrayList();
        }
    }


//    public DeleteOrderDto convent2DeleteOrderDto(String oId) {
//        DeleteOrderDto deleteOrderDto = new DeleteOrderDto();
//        deleteOrderDto.setOrderId(oId);
//        return deleteOrderDto;
//    }

    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()));
        return orderPayDto;

    }

    /**
     * 混合支付返回的支付参数
     *
     * @param payPlatforms
     * @return
     */
    public OrderPayResponse convent2OrderCombPayResponse(List<CombPayResponse.PayPlatform> payPlatforms
            , String partnerId
            , String storeId) {
        CombPayResponse.PayPlatform payPlatform = payPlatforms
                .stream()
                .filter(f -> !PayChannelType.SVC.getEbcode().equals(f.getEbCode())).findFirst()
                .orElse(null);
        OrderPayResponse responseDto = new OrderPayResponse();
        responseDto.setMsg("succ");
        responseDto.setPayEbcode(payPlatform.getEbCode());
        responseDto.setPayId("");

        OrderPayResponse.PayOrderBean payBean = new OrderPayResponse.PayOrderBean();
        responseDto.setPayTransId(payPlatform.getTransId());
        responseDto.setFmId(payPlatform.getFmTradeNo());
        CombPayResponse.PayPlatform.PayOrderBean payOrderBean = payPlatform.getPayOrder();
        if (null != 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);
        }
        //供修改订单
        for (CombPayResponse.PayPlatform pt : payPlatforms) {
            OrderPayItemResp payItem = new OrderPayItemResp();
            payItem.setFmTradeNo(pt.getFmTradeNo());
            payItem.setStoreId(storeId);
            payItem.setPayChannelType(PayChannelType.getByEbcode(pt.getEbCode()).getIndex().intValue());
            payItem.setPayChannelName(PayChannelType.getByEbcode(pt.getEbCode()).getName());
            payItem.setTransId(pt.getTransId());
            payItem.setPartnerId(partnerId);
            if (PayChannelType.SVC.getEbcode().equals(pt.getEbCode())) {
                payItem.setPayAmount(new BigDecimal(pt.getPayAmount()));
                responseDto.setPayChannelType(PayChannelType.SVC);
            } else if (PayChannelType.WECHAT.getEbcode().equals(pt.getEbCode()) || PayChannelType.ALIPAY.getEbcode().equals(pt.getEbCode())) {
                payItem.setPayAmount(new BigDecimal(pt.getPayAmount()));
                responseDto.setPayChannelType(PayChannelType.getByEbcode(pt.getEbCode()));
            }
            responseDto.getPayItem().add(payItem);
        }
        if (responseDto.getPayItem().size() == 2) {
            responseDto.setPayChannelType(PayChannelType.COMB);
        }
        return responseDto;
    }

    /**
     * 初始化扣减活动库存请求对象
     * 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.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, OrderStatus.getAllCodes());
                queryOrdersDto.setOrderStatuses(orderStatuses);
                //queryOrdersDto.setStatus(OrderStatus.getAllCodes());
                if (Objects.equals((int) OrderMarketType.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[]{OrderStatus.TAKE_ORDER.getCode(), OrderStatus.RECEIPT.getCode(),
                        OrderStatus.DISTRIBUTION.getCode(), OrderStatus.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(OrderStatus.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(OrderStatus.CALCEL.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(OrderStatus.CALCEL.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(OrderStatus.RECEIPT.getCode(), OrderStatus.TAKE_ORDER.getCode());
                queryOrdersDto.setOrderStatuses(orderStatuses);
            }
        }

        // 兼容历史版本，如果传参是4 查询拆程4和5
        List<Integer> orderTypes = new ArrayList<>();
        if (queryOrderType != null) {
            if (Objects.equals(queryOrderType, OrderType.COLLECT_GOODS.getCode())) {
                orderTypes.add(OrderType.COLLECT_GOODS.getCode());
                orderTypes.add(OrderType.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[]{OrderStatus.COMPLETE.getCode(), OrderStatus.CALCEL.getCode(), OrderStatus.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(orderSdkAdapter.getNewOrderStatus(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 = orderSdkAdapter.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 (String.valueOf(OrderClientType.SAASMALL.getIndex()).equals(orderBean.getOrderClient())) {
            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 (OrderClientType.SAASMALL.getIndex().toString().equalsIgnoreCase(orderBean.getOrderClient())) {
            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> orderStatusList = Arrays.asList(OrderStatus.WAIT_PAY.getCode(), OrderStatus.RECEIPT.getCode(), OrderStatus.DISTRIBUTION.getCode(), OrderStatus.COMPLETE.getCode());
        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 (orderStatusList.contains(orderBean.getStatus()) && (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 (orderStatusList.contains(orderBean.getStatus()) && (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> orderStatusList = Arrays.asList(OrderStatus.RECEIPT.getCode(), OrderStatus.DISTRIBUTION.getCode(), OrderStatus.COMPLETE.getCode());
        //是否忽略售后单状态”呀，大部分情况都是false；只有拒绝退款后继续发货状态并行时新赠的“是否忽略售后单状态”字段为true
        AfterSalesOrderResp afterSalesOrderResp = orderBean.getAfterSalesOrderResp();
        if (null != afterSalesOrderResp && ((Objects.equals(AfterSalesStatus.CANCEL.getIndex(), afterSalesOrderResp.getAfterSalesStatus()) && (Objects.equals(OrderStatus.DISTRIBUTION.getCode(), orderBean.getStatus()) || Objects.equals(OrderStatus.COMPLETE.getCode(), orderBean.getStatus()))) ||
                (Objects.equals(AfterSalesStatus.REJECTED.getIndex(), afterSalesOrderResp.getAfterSalesStatus()) && (orderStatusList.contains(orderBean.getStatus()))))) {
            orderCompareAfterSaleOrder = true;
        }
        return orderCompareAfterSaleOrder;
    }


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

    /**
     * 礼品卡支付参数转化
     */
    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;
    }

}
