/**
 * 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.log.LogTreadLocal;
import cn.freemud.base.util.DateUtil;
import cn.freemud.constant.CustomerScoreConstant;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.activity.ShareDiscountActivityDto;
import cn.freemud.entities.dto.order.*;
import cn.freemud.entities.dto.order.CreateOrderAccountDto;
import cn.freemud.entities.dto.order.CreateOrderProductDto;
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.vo.*;
import cn.freemud.entities.vo.encircle.CreateReserveOrderVo;
import cn.freemud.entities.vo.encircle.PreviewOrderInfoVo;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.enums.*;
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.ResponseResult;
import cn.freemud.interceptor.ServiceException;
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.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.cache.CacheOpenPlatformPartnerWxappConfigManager;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.enums.AfterSalesType;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.application.sdk.api.ordercenter.enums.OrderSettlementType;
import com.freemud.application.sdk.api.ordercenter.enums.ProductTypeEnum;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtendedReq;
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.enums.*;
import com.freemud.sdk.api.assortment.order.request.order.*;
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.order.response.payment.OrderPayResponse;
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.data.redis.core.RedisTemplate;
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.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

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

@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("${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;
    @Value("${macafe.waimai.tag}")
    private String maCafeWaimaiTag;
    @Value("${macafe.pick.tag}")
    private String maCafePickTag;
    @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;

    /**
     * @param createOrderVo
     * @param shoppingCartGoodsDto
     * @return
     */
    public BaseCreateOrderRequest convent2CreateOrderDto(CreateOrderVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto,StoreResponse.BizVO storeResponseDto) {
//        UserDeliveryInfoDto deliveryInfoDto = createOrderVo.getUserDeliveryInfoDto();
        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();
            if(shoppingCartGoodsDto.getIsDiscountDelivery() && deliveryAmount>shoppingCartGoodsDto.getDiscountDeliveryAmount()){
                discountDeliveryAmount = shoppingCartGoodsDto.getDiscountDeliveryAmount();
            }
        }
        Long packageAmount = shoppingCartGoodsDto.getPackageAmount() == null ? 0L : shoppingCartGoodsDto.getPackageAmount();
        createOrderDto.setAmount(shoppingCartGoodsDto.getTotalAmount() + discountDeliveryAmount + packageAmount);
        // 解析购物车信息
        List<ShoppingCartGoodsDto.CartGoodsDetailDto> cartGoodsDetailDtos = shoppingCartGoodsDto.getProducts();
        List<ActivityDiscountsDto> activityDiscountsDtos = shoppingCartGoodsDto.getActivityDiscountsDtos();
        List<CreateOrderProductRequest> products = new ArrayList<>();

        // 根据购物车商品信息获取优惠信息
        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 {
                    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 {
                        createOrderProductDto.setAccounts(getAccounts(createOrderProductDto, cartGoodsDetailDto.getActivityDiscountsDtos()));
                    }
                }
            }
        }
        createOrderDto.setProducts(products);
        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();
            if(mcCafePartnerId.equals(createOrderDto.getCompanyId())) {
                JSONObject jsonObject = new JSONObject();
                if(ActivityTypeEnum.TYPE_11.getCode().equals(activityDiscountsDto.getActivityType())
                        || ActivityTypeEnum.TYPE_12.getCode().equals(activityDiscountsDto.getActivityType())) {
                    jsonObject.put("tenderId", activityDiscountsDto.getTenderId());
                } else if(ActivityTypeEnum.TYPE_34.getCode().equals(activityDiscountsDto.getActivityType())) {
                    jsonObject.put("customerCode", activityDiscountsDto.getTenderId());
                }
                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();
            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);
        }
        createOrderDto.setAccounts(CollectionUtils.isNotEmpty(orderAccountDtos) ? orderAccountDtos : Collections.emptyList());

        //设置库存扣减
        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(ActivityTypeEnum.TYPE_53.getCode().equals(stockVO.getActivityType()) ? 1 : stock);
                        goodsStockDTOS.add(goodsStockDTO);
                    });
                    stockBeanDto.setGoodsStock(goodsStockDTOS);
                }
                stocks.add(stockBeanDto);
            }
            ActivityUpdateStockRequest activityUpdateStockRequest = new ActivityUpdateStockRequest();
            activityUpdateStockRequest.setStock(stocks);
            createOrderDto.setActivityUpdateStockRequest(activityUpdateStockRequest);
        }
        createOrderDto.setPayChannelType(createOrderVo.getPayChannelType());
        return createOrderDto;
    }

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

    }

    public CreateFatherSonOrderRequest convertFatherSonOrderRequest(CreateOrderVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto,
                                                                    OrderExtendedReq orderExtendedReq,StoreResponse.BizVO storeResponseDto,
                                                                    String appId) {
        CreateFatherSonOrderRequest createFatherSonOrderRequest = new CreateFatherSonOrderRequest();
        createFatherSonOrderRequest.setPartnerId(createOrderVo.getPartnerId());
        createFatherSonOrderRequest.setTrackingNo(LogTreadLocal.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(createOrderProductDto.getNumber())
                    .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();
            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() : "";
        Integer orderType;
        String receiveAddress = createOrderVo.getStoreAddress();
        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 {
            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.setUserId(createOrderVo.getUserId());
        createOrderDto.setUserName(createOrderVo.getUserName());
        createOrderDto.setPhone(createOrderVo.getMobile());
        createOrderDto.setAddress(receiveAddress);
        createOrderDto.setLatitude(latitude);
        createOrderDto.setLongitude(longitude);
        createOrderDto.setOrderType(convent2OrderTypeEnum(orderType));
        createOrderDto.setPayType(QueryPayType.ONLINE_PAY);
        if (Objects.nonNull(createOrderVo.getUnionPayCard())) {
            createOrderDto.setPayChannel(PayChannel.USVCP.getCode());
            createOrderDto.setPayChannelName(PayChannel.USVCP.getDesc());
        } else if(StringUtils.isNotBlank(createOrderVo.getCardCode())){
            createOrderDto.setPayChannel("10102");
            createOrderDto.setPayChannelName("储值卡支付");
        }
        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()));
        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());
        //设置库存扣减
        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(ActivityTypeEnum.TYPE_53.getCode().equals(stockVO.getActivityType()) ? 1 : stock);
                        goodsStockDTOS.add(goodsStockDTO);
                    });
                    stockBeanDto.setGoodsStock(goodsStockDTOS);
                }
                stocks.add(stockBeanDto);
            }
            ActivityUpdateStockRequest activityUpdateStockRequest = new ActivityUpdateStockRequest();
            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.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());
        //TODO 查询退款的待确定
        if (queryOrderDto.getQueryOrderStatus() != null) {
            if (QueryOrderStatus.ALL_BILL.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                queryOrdersDto.setStatus(OrderStatus.getAllCodes());
            }
            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()});
            }
        }

        // 兼容历史版本，如果传参是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(1,6));

        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<QueryOrdersResponse.DataBean.OrderBean> ordersBeans, String wxAppId, String iAppId) {
        if (CollectionUtils.isEmpty(ordersBeans)) {
            return Collections.emptyList();
        }
        List<QueryOrderResponseVo> list = Lists.newArrayList();

        ordersBeans.forEach(ordersBean -> {
            QueryOrderResponseVo responseVo = new QueryOrderResponseVo();
            responseVo.setOid(ordersBean.getOid());
            responseVo.setShopId(ordersBean.getShopId());
            responseVo.setShopName(ordersBean.getShopName());
            responseVo.setShopAddress(ordersBean.getShopAddress());
            responseVo.setShopPhone(ordersBean.getShopPhone());
            responseVo.setReceiveAddress(ordersBean.getAddress());
            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.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 (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.setPayVoucher(orderExtInfoDto != null ? orderExtInfoDto.getPayTransId() : "");
            responseVo.setPayCreateTime(orderExtInfoDto != null ? orderExtInfoDto.getPayDate() : "");
            responseVo.setPayChannel(ordersBean.getPayChannel());
            if (StringUtils.isNotBlank(ordersBean.getPayChannel())) {
                if ("10102".equals(ordersBean.getPayChannel())) {
                    responseVo.setOrderPayType("储值卡支付");
                } else if (PayChannel.ALIPAY.getCode().equals(ordersBean.getPayChannel())) {
                    responseVo.setOrderPayType("支付宝支付");
                } else if (PayChannel.WXPAY.getCode().equals(ordersBean.getPayChannel())) {
                    responseVo.setOrderPayType("微信支付");
                } else if (Objects.equals(PayChannel.USVCP.getCode(), ordersBean.getPayChannel())) {
                    responseVo.setOrderPayType("电子风味卡支付");
                } else {
                    responseVo.setOrderPayType("微信支付");
                }
            }
            else {
                if (OrderSourceType.ALIPAY.getCode().equals(ordersBean.getSource())) {
                    responseVo.setOrderPayType("支付宝支付");
                }
                else if(OrderSourceType.SAAS.getCode().equals(ordersBean.getSource())) {
                    responseVo.setOrderPayType("微信支付");
                }
                else {
                    responseVo.setOrderPayType("微信支付");
                }
            }


            //取餐码用日订单序号代替- v1.5.4变更为四位随机数
            responseVo.setTakeCode(ordersBean.getOtherCode());
            responseVo.setAmount(ordersBean.getAmount());
                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.setOrderStatusDescText(orderViewStatusDto.getOrderStatusDescText());
            if (CollectionUtils.isNotEmpty(ordersBean.getRefundList())) {
                responseVo.setRefundTips(orderViewStatusDto.getRefundStatusText());
            }
            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.getDeliverStatus() != null) {
                responseVo.setHasThirdDelivery(true);
            }
            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("围餐");
            }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 (CollectionUtils.isNotEmpty(ordersBean.getRefundList())) {
                    QueryOrdersResponse.DataBean.OrderBean.RefundBean refundBean = ordersBean.getRefundList().get(0);
                    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);
                }
            }
            //商品信息转换
            convent2ProductVos(ordersBean.getProductList(), responseVo);
            responseVo.setOrderAccounts(convent2OrderAccountVo(ordersBean.getApportionDetails()));
            Long promotionAmount = 0L;
            Long deliveryAmount = 0L;
            Long packageAmount = 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 (QueryOrdersResponse.DataBean.OrderBean.AccountBean accountBean : ordersBean.getAccountList()) {
                    if (accountBean.getPrice() < 0) {
                        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();
                    }
                    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;
                    }
                }
            }
            responseVo.setDeliveryAmount(deliveryAmount);
            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);
            }
            list.add(responseVo);
        });
        return list;
    }

    private ArrayList<QueryOrderResponseVo.OrderStatusFlow> getOrderTimeDesc(QueryOrdersResponse.DataBean.OrderBean 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(QueryOrdersResponse.DataBean.OrderBean 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(QueryOrdersResponse.DataBean.OrderBean orderBean, String wxAppId) {
        OrderViewStatusDto orderViewStatusDto = new OrderViewStatusDto();
        LogUtil.info("getOrderStatusDesc start ", new Gson().toJson(orderBean), new Gson().toJson(orderBean));
        QueryOrdersResponse.DataBean.OrderBean.RefundBean 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("待支付");
                orderViewStatusDto.setOrderStatusDescText("");
            }
            if (OrderStatus.CALCEL.getCode().equals(orderBean.getStatus())) {
                orderViewStatusDto.setOrderStatus(OrderStatus.CALCEL.getCode());
                orderViewStatusDto.setOrderStatusDesc("已取消");
                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("下单成功");
                    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 (OrderStatus.RECEIPT.getCode().equals(orderBean.getStatus())) {
                if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    orderViewStatusDto.setOrderStatus(OrderStatus.RECEIPT.getCode());
                    orderViewStatusDto.setOrderStatusDesc("制作中");
                    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 (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.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 (OrderType.TAKE_OUT.getCode().equals(orderBean.getType())) {
            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())) {
                if (refundBean == null || RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    if (orderBean.getDeliverStatus() == null) {
                        orderViewStatusDto.setOrderStatus(OrderStatus.TAKE_ORDER.getCode());
                        orderViewStatusDto.setOrderStatusDesc("下单成功");
                        orderViewStatusDto.setOrderStatusDescText("请稍等片刻，美味即将到达哦~");
                        orderViewStatusDto.setButtonContactPartner(true);
                        orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean,wxAppId));
                        orderViewStatusDto.setRiderName("商家自配送");
                        orderViewStatusDto.setRiderText("正在为您匹配配送员");
                        orderViewStatusDto.setRiderPhoto(orderBean.getRiderPhoto());
                    } else {
                        orderViewStatusDto.setOrderStatus(OrderStatus.TAKE_ORDER.getCode());
                        orderViewStatusDto.setOrderStatusDesc("下单成功");
                        orderViewStatusDto.setOrderStatusDescText("请稍等片刻，美味即将到达哦~");
                        orderViewStatusDto.setButtonContactPartner(true);
                        orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean,wxAppId));
                        orderViewStatusDto.setRiderName("处理中");
                        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 (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("制作中");
                        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("制作中");
                        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);
                    }
                }
                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 (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);
                    }
                }
                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);
                }
            }
            //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("配送中");
                    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.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("配送中");
                        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 (refundBean != null && RefundStatus.AGREE_REFUND.getCode().equals(refundBean.getStatus())) {
            orderViewStatusDto.setOrderStatus(OrderStatus.CALCEL.getCode());
            orderViewStatusDto.setOrderStatusDesc("已退款");
            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.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
            orderViewStatusDto.setRefundStatusText("正在退款中，请稍等");
            orderViewStatusDto.setButtonContactPartner(true);
        }
        if (OrderStatus.REFUSE.getCode().equals(orderBean.getStatus())) {
            orderViewStatusDto.setOrderStatus(OrderStatus.REFUSE.getCode());
            orderViewStatusDto.setOrderStatusDesc("已退款");
            orderViewStatusDto.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
            orderViewStatusDto.setRefundStatusText("订单金额已原路退还，请及时查看~");
            orderViewStatusDto.setButtonContactPartner(true);
        }
        if (PayStatus.HAVE_REFUND.getCode().equals(orderBean.getPayStatus())) {
            orderViewStatusDto.setOrderStatus(OrderStatus.REFUSE.getCode());
            orderViewStatusDto.setOrderStatusDesc("已退款");
            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("商家会处理退款申请，请稍后");

            } else {
                orderViewStatusDto.setButtonRefund(checkRefundButton(orderBean, wxAppId));
            }
            orderViewStatusDto.setOrderStatus(OrderStatus.COMPLETE.getCode());
            orderViewStatusDto.setOrderStatusDesc("已完成");
            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(QueryOrdersResponse.DataBean.OrderBean orderBean, String wxAppId) {
        boolean canRefund = false;

        List<AssortmentOpenPlatformPartnerWxappConfig> wxappConfigs = cacheWxappConfigManager.cacheSelectDefaultPage(wxAppId, "2");
        Map<String, AssortmentOpenPlatformPartnerWxappConfig> configMap = wxappConfigs.stream().collect(Collectors.toMap(AssortmentOpenPlatformPartnerWxappConfig::getAppKey, Function.identity()));
        AssortmentOpenPlatformPartnerWxappConfig orderRefund;

        //订单状态
        switch (orderBean.getStatus()) {
            // 未接单
            case 1:
                //区分外卖单和到店订单，判断是否可以退款
                if(OrderType.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
                    orderRefund = configMap.get(OrderRefundEnum.DELIVERY_TAKE_ORDER_REFUND.getKeyValue());
                }else {
                    orderRefund = configMap.get(OrderRefundEnum.TAKEORDER_REFUND.getKeyValue());
                }
                if (orderRefund == null || (orderRefund != null && ALLOW_REFUND.equals(orderRefund.getAppValue()))) {
                    canRefund = true;
                }
                break;
            //已接单
            case 3:
                if(OrderType.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
                    orderRefund = configMap.get(OrderRefundEnum.DELIVERY_RECEIPT_ORDER_REFUND.getKeyValue());
                }else {
                    orderRefund = configMap.get(OrderRefundEnum.RECEIPTORDER_REFUND.getKeyValue());
                }
                if (orderRefund == null || (orderRefund != null && ALLOW_REFUND.equals(orderRefund.getAppValue()))) {
                    canRefund = true;
                }
                break;
            //制作完成
            case 31:
                if(OrderType.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
                    orderRefund = configMap.get(OrderRefundEnum.DELIVERY_COMPLETE_MAKE_ORDER_REFUND.getKeyValue());
                }else {
                    orderRefund = configMap.get(OrderRefundEnum.COMPLETEMAKEORDER_REFUND.getKeyValue());
                }
                if (orderRefund != null && ALLOW_REFUND.equals(orderRefund.getAppValue())) {
                    canRefund = true;
                }
                break;
            // 订单完成
            case 5:
                long currentTime = System.currentTimeMillis();
                long gmtModified = orderBean.getGmtModified();

                long value = 0L;
                AssortmentOpenPlatformPartnerWxappConfig refundDateConfig = configMap.get(OrderRefundEnum.REFUND_DATA_RANGE.getKeyValue());
                if (null != refundDateConfig) {
                    String appValue = refundDateConfig.getAppValue();
                    value = Long.parseLong(StringUtils.isEmpty(appValue) ? "0" : appValue);
                }
                long allowRefundTime = gmtModified + value * 24 * 60 * 60 * 1000;

                if(OrderType.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
                    orderRefund = configMap.get(OrderRefundEnum.DELIVERY_ORDER_REFUND.getKeyValue());
                }else {
                    orderRefund = configMap.get(OrderRefundEnum.ORDER_REFUND.getKeyValue());
                }
                if (orderRefund != null && ALLOW_REFUND.equals(orderRefund.getAppValue()) && (allowRefundTime - currentTime) >= 0) {
                    canRefund = true;
                }
                break;
            default:
                break;

        }
        return canRefund;
    }

    public List<OrderAccountVo> convent2OrderAccountVo(List<QueryOrdersResponse.DataBean.OrderBean.OrderSettlement> 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());
        for (QueryOrdersResponse.DataBean.OrderBean.OrderSettlement 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("积分抵扣");
                }
                int value = orderSettlement.getSettlementAmount().intValue();
                accountVo.setDiscountAmount(value < 0 ? -value : value);
                orderAccountVos.add(accountVo);
            }
        }

        return orderAccountVos;
    }

    public void convent2ProductVos(List<QueryOrdersResponse.DataBean.OrderBean.ProductBean> productBeans, QueryOrderResponseVo responseVo) {
        if (CollectionUtils.isEmpty(productBeans)) {
            return;
        }
        List<ProductVo> productVos = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(productBeans)) {
            for (QueryOrdersResponse.DataBean.OrderBean.ProductBean productBean : productBeans) {
                ProductVo productVo = convent2ProductVo(productBean);
                // 套餐商品设置子商品节点
                if (ObjectUtils.equals(ProductTypeEnum.SETMEAL_PRODUCT.getCode(), productBean.getProductType()) || ObjectUtils.equals(ProductTypeEnum.SETMEAL_UPPRICE_PRODUCT.getCode(), productBean.getProductType())) {
                    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);
                                    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());
                                });
                                comboProduct.setSetMaterialProducts(setMaterialProducts);
                            }
                        }
                    });
                    productVo.setSetMealProducts(setMealProducts);
                }
                if (ObjectUtils.equals(ProductTypeEnum.MATERIAL_PRODUCT.getCode(), productBean.getProductType())) {
                    List<ProductVo> setMaterialProducts = new ArrayList<>();
                    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());
        }
    }

    public ProductVo convent2ProductVo(QueryOrdersResponse.DataBean.OrderBean.ProductBean 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();
        OrderProductAddInfoDto extInfo = JSON.parseObject(productBean.getExtInfo(), OrderProductAddInfoDto.class);
        if(CollectionUtils.isNotEmpty(extInfo.getSpecialAttrs())) {
            String attr = "";
            for (OrderSpecialExtraAttrRequest special : extInfo.getSpecialAttrs()) {
                if(special.getAttributeName().indexOf("冰") >= 0) {
                    attr += special.getAttributeName()+",";
                }
            }
            if(attr.length() > 0) {
                attr = attr.substring(0, attr.length()-1);
                productName += "("+attr+")";
            }
        }

        productVo.setName(productName);
        productVo.setSpuName(productBean.getProductName());
        productVo.setPicture(productBean.getPicture());
        productVo.setSequence(productBean.getSequence());
        productVo.setQty(productBean.getNumber());
        productVo.setSpecification("");
        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.setOriginalPrice(productBean.getPrice());
        productVo.setFinalPrice(productBean.getSalePrice());
        productVo.setExtras(shoppingCartAdapter.getExtraName(productBean.getSpecificationName(), attributeNames));
        //计算商品原总金额=商品原价格 * 商品数量
        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 (QueryOrdersResponse.DataBean.OrderBean.ProductBean.ProductDiscount 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())) {
                    hasProductCoupon = true;
                    productVo.setName(productDiscount.getDiscountDesc());
                    productVo.setSpuName(productDiscount.getDiscountDesc());
                    productVo.setExtras("");
                    productVo.setSpecification("");
                }
                if (OrderAccountType.BUYM_SENDN.getCode().equals(productDiscount.getDiscountType())) {
                    activityType = ActivityTypeEnum.TYPE_61.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();
                }
            }
        }
        //优惠券满减总优惠
        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());
        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(QueryOrdersResponseDto.DataBean.OrderBean 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 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);
        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(QueryOrdersResponseDto.DataBean.OrderBean 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(QueryOrdersResponseDto.DataBean.OrderBean.ProductBean::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 (QueryOrdersResponseDto.DataBean.OrderBean.AccountBean 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<QueryOrdersResponseDto.DataBean.OrderBean.ProductBean> productBeans) {
        if (CollectionUtils.isEmpty(productBeans)) {
            return Collections.emptyList();
        }
        List<OrderPrintDto.ProductsBean> products = Lists.newArrayList();
        for (QueryOrdersResponseDto.DataBean.OrderBean.ProductBean 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 (QueryOrdersResponseDto.DataBean.OrderBean.ProductBean comboProduct : productBean.getComboProduct()) {
                    OrderPrintDto.ProductsBean sonProductVO = getProductBean(comboProduct);
                    comboProductVOs.add(sonProductVO);
                }
            }
            if (CollectionUtils.isNotEmpty(productBean.getMaterialProduct())) {
                for (QueryOrdersResponseDto.DataBean.OrderBean.ProductBean 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(QueryOrdersResponseDto.DataBean.OrderBean.ProductBean 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<>());
        return productBean1;
    }

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

    //同意
    public void setAgreeRefundDesc(OrderViewStatusDto orderViewStatusDto, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        orderViewStatusDto.setOrderStatus(orderBean.getStatus());
        orderViewStatusDto.setOrderStatusDesc("退款中");
        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 -> {
                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 -> {
                materialProducts.add(convent2OrderProductMaterial(product));
            });
            createOrderProductDemoDto.setMaterialProduct(materialProducts);
        }


        createOrderProductDemoDto.setProductType(cartGoodsDetailDto.getProductType());
        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());
                    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(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.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(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());
        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());
        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());
        createOrderProductDemoDto.setProductType(productType);
        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());
        if(CollectionUtils.isNotEmpty(cartGoodsDetailDto.getSpecialExtra())) {
//            createOrderProductDemoDto.setSpecialCodes(cartGoodsDetailDto.getSpecialExtra().stream().map(ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra::getSpecialCode).collect(Collectors.toList()));
            createOrderProductDemoDto.setSpecialAttrs(new ArrayList<>());
            createOrderProductDemoDto.setSpecialCodes(new ArrayList<>());
            cartGoodsDetailDto.getSpecialExtra().stream().forEach(o -> {
                createOrderProductDemoDto.getSpecialAttrs().add(new OrderSpecialExtraAttrRequest(o.getAttributeName(), o.getSpecialCode()));
                createOrderProductDemoDto.getSpecialCodes().add(o.getSpecialCode());
            });
        }
        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_34.getCode().equals(activityType)) {
            return OldOrderAccountType.FREIGHT_COUPON;
        }
        if (ActivityTypeEnum.TYPE_31.getCode().equals(activityType)) {
            return OldOrderAccountType.DISCOUNT_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_23.getCode().equals(activityType)){
            return OldOrderAccountType.SUPER_PURCHASE;
        }
        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.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(QueryOrdersResponse.DataBean.OrderBean orderBean, PaymentRequest paymentRequest, Long amount, Integer cardAmount, String transId) {
        return convent2UnifiedOrderRequest(orderBean, paymentRequest, amount, cardAmount, transId, null);
    }

        /**
         * 支付信息转换
         */
    public UnifiedOrderRequest convent2UnifiedOrderRequest(QueryOrdersResponse.DataBean.OrderBean 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());
        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);
        return orderPayResponse;
    }

    /**
     * 父子订单转换前端支付需要的信息
     *
     * @param orderPayResponse
     * @param
     * @return
     */
    public CreateOrderResponseVo convent2CreateFatherSonOrderResponseVo(OrderPayResponse orderPayResponse, QueryOrdersResponse.DataBean.OrderBean 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 ? "" : 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());
        return createOrderResponseVo;
    }

    public CreateOrderResponseVo convent2CreateFatherSonOrderNoPayResponseVo(QueryOrdersResponse.DataBean.OrderBean 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);
        }
        responseDto.setStatusCode(unifiedOrderResponse.getStatusCode());
        responseDto.setPayTransId(unifiedOrderResponse.getPayTransId());
        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.setSpuName("餐具");
                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.setPayStatus(queryOrderResponseVo.getPayStatus());
        previewOrderInfoVo.setPayStatusDesc(queryOrderResponseVo.getPayStatusDesc());
        previewOrderInfoVo.setShopName(queryOrderResponseVo.getShopName());
        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());


        //设置库存扣减
        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(ActivityTypeEnum.TYPE_53.getCode().equals(stockVO.getActivityType()) ? 1 : stock);
                        goodsStockDTOS.add(goodsStockDTO);
                    });
                    stockBeanDto.setGoodsStock(goodsStockDTOS);
                }
                stocks.add(stockBeanDto);
            }
            ActivityUpdateStockRequest activityUpdateStockRequest = new ActivityUpdateStockRequest();
            activityUpdateStockRequest.setStock(stocks);
            sdkUpdateOrderProductInfoRequest.setActivityUpdateStockRequest(activityUpdateStockRequest);
        }
        return sdkUpdateOrderProductInfoRequest;
    }

    private CreateOrderProductRequest conventOrderInfoAndCarInfoByUpdate(QueryOrdersResponse.DataBean.OrderBean.ProductBean 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(QueryOrdersResponse.DataBean.OrderBean.ProductBean::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(QueryOrdersResponse.DataBean.OrderBean 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, QueryOrdersResponse.DataBean.OrderBean fatherOrderBean,
                                                                  QueryOrdersResponse.DataBean.OrderBean 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, QueryOrdersResponse.DataBean.OrderBean fatherOrderBean,
                                                                  QueryOrdersResponse.DataBean.OrderBean 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());
    }

    /**
     * 支付后通知失败返回信息
     */
    public String newSendPayFaileMessage() {
        Map<String, Object> map = Maps.newTreeMap();
        map.put("code", 500);
        map.put("message", "failed");
        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;
    }
}
