/**
 * 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.QueryOrdersResponseDto.DataBean.OrderBean.ProductBean;
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.shoppingCart.ActivityDiscountsDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.*;
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.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.freemud.api.assortment.datamanager.entity.db.AssortmentOpenPlatformPartnerWxappConfig;
import com.freemud.api.assortment.datamanager.entity.db.AssortmentOpenPlatformWxapp;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.api.assortment.datamanager.enums.IappIdType;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.api.assortment.datamanager.manager.cache.CacheOpenPlatformPartnerWxappConfigManager;
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.OrderExtendedReq;
import com.freemud.application.sdk.api.ordercenter.request.create.OrderTaskReq;
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.entities.OrderExtInfoDTO;
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.freemud.sdk.api.assortment.promotion.request.OrderBeanRequest;
import com.freemud.sdk.api.assortment.promotion.response.ShoppingCartGoodsResponse;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.awt.geom.Point2D;
import java.math.BigDecimal;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.text.DecimalFormat;
import java.util.*;
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 yyyyMMdd = FastDateFormat.getInstance("yyyy-MM-dd", Locale.CHINA);

    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==";

    @Value("${saas.reverseNotifyiDcUrl}")
    private String reverseNotifyiDcUrl;
    @Value("${saas.refund.notify.callback}")
    private String refundNotifyCallback;
    @Autowired
    private ShoppingCartAdapter shoppingCartAdapter;
    @Autowired
    private CacheOpenPlatformPartnerWxappConfigManager cacheWxappConfigManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private OrderCommonService orderCommonService;

    private static Gson gson = new Gson();

    /**
     * @param createOrderVo
     * @param shoppingCartGoodsDto
     * @return
     */
    public BaseCreateOrderRequest convent2CreateOrderDto(CreateOrderVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto,String orderWarnTime) {

        UserDeliveryInfoDto deliveryInfoDto = createOrderVo.getUserDeliveryInfoDto();
        BaseCreateOrderRequest createOrderDto = getCreateOrderDto(createOrderVo);
        long deliveryAmount = 0;
        if (deliveryInfoDto != null) {
            deliveryAmount = getUserRealDeliveryAmount(deliveryInfoDto.getStoreDeliveryInfoDto(), deliveryInfoDto.getUserLongitude(), deliveryInfoDto.getUserLatitude());
        }
        if(createOrderDto.getGmtExpect() != null && createOrderDto.getGmtExpect() != 0){
            //预订单任务
            createOrderDto.setOrderTask(saveOrderTaskReq(orderWarnTime,createOrderDto.getGmtExpect()));
        }
        Long packageAmount = shoppingCartGoodsDto.getPackageAmount() == null ? 0L : shoppingCartGoodsDto.getPackageAmount();
        createOrderDto.setAmount(shoppingCartGoodsDto.getTotalAmount() + deliveryAmount + packageAmount);
        // 解析购物车信息
        List<ShoppingCartGoodsDto.CartGoodsDetailDto> cartGoodsDetailDtos = shoppingCartGoodsDto.getProducts();
        List<ActivityDiscountsDto> activityDiscountsDtos = shoppingCartGoodsDto.getActivityDiscountsDtos();
        List<CreateOrderProductRequest> products = new ArrayList<>();
        ArrayList<CreateOrderAccountRequest> orderAccountDtos = new ArrayList<>();
        // 根据购物车商品信息获取优惠信息
        int orderAccountIndex = 0;
        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()));
                }
            }
        }
        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();
            orderAccountDtos.add(createOrderAccountDto);
        }

        if (deliveryAmount > 0) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId("")
                    .name("配送费")
                    .price(deliveryAmount)
                    .accountType(getQueryOrderAccountType(OldOrderAccountType.getByCode(OrderAccountType.DELIVERY_AMOUNT.getCode())))
                    .sequence(orderAccountIndex++)
                    .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);
        }
        return createOrderDto;
    }

    public CreateFatherSonOrderRequest convertFatherSonOrderRequest(CreateOrderVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto, OrderExtendedReq orderExtendedReq,String orderWarnTime) {
        CreateFatherSonOrderRequest createFatherSonOrderRequest = new CreateFatherSonOrderRequest();
        createFatherSonOrderRequest.setPartnerId(createOrderVo.getPartnerId());
        createFatherSonOrderRequest.setTrackingNo(LogTreadLocal.getTrackingNo());
        UserDeliveryInfoDto deliveryInfoDto = createOrderVo.getUserDeliveryInfoDto();
        List<CreateFatherSonOrderRequest.OrderInfo> orderInfoList = new ArrayList<>();
        CreateFatherSonOrderRequest.OrderInfo productOrderInfo = convertProductOrderInfo(createOrderVo, deliveryInfoDto, shoppingCartGoodsDto,orderWarnTime);
        productOrderInfo.setOrderExtended(orderExtendedReq);
        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;
    }


    /**
     * 计算用户收货地址实际配送费
     *
     * @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() : "";
        StringBuffer takeMealTime = new StringBuffer("");
        Date takeMealDate = null;
        if (StringUtils.isNotBlank(createOrderVo.getTakeMealTime())) {
            takeMealTime = takeMealTime.append(DateUtil.convert2String(new Date(), "yyyy-MM-dd"))
                    .append(" ").append(createOrderVo.getTakeMealTime()).append(":00");
            takeMealDate = DateUtil.convert2Date(takeMealTime.toString(), "yyyy-MM-dd HH:mm:ss");
        }
        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(StringUtils.isNotBlank(createOrderVo.getCardCode())){
            createOrderDto.setPayChannel("10102");
            createOrderDto.setPayChannelName("储值卡支付");
        }
        createOrderDto.setSource(OrderSourceType.SAAS.getCode());
        createOrderDto.setSourceName(OrderSourceType.SAAS.getDesc());
        createOrderDto.setRemark(remark);
        createOrderDto.setGmtExpect(takeMealDate != null ? takeMealDate.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());
        return createOrderDto;
    }

    public CreateFatherSonOrderRequest.OrderInfo convertProductOrderInfo(CreateOrderVo createOrderVo
            , UserDeliveryInfoDto userDeliveryInfoDto, ShoppingCartGoodsDto shoppingCartGoodsDto,String orderWarnTime) {
        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() : "";
        StringBuffer takeMealTime = new StringBuffer("");
        CreateFatherSonOrderRequest.OrderInfo productOrderInfo = new CreateFatherSonOrderRequest.OrderInfo();
        Date takeMealDate = null;
        if (StringUtils.isNotBlank(createOrderVo.getTakeMealTime())) {
            takeMealTime = takeMealTime.append(DateUtil.convert2String(new Date(), "yyyy-MM-dd"))
                    .append(" ").append(createOrderVo.getTakeMealTime()).append(":00");
            takeMealDate = DateUtil.convert2Date(takeMealTime.toString(), "yyyy-MM-dd HH:mm:ss");
            productOrderInfo.setOrderTask(saveOrderTaskReq(orderWarnTime,takeMealDate.getTime()));
        }
        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(StringUtils.isNotBlank(createOrderVo.getCardCode())){
            productOrderInfo.setPayChannel("10102");
            productOrderInfo.setPayChannelName("储值卡支付");
        }
        productOrderInfo.setSource(OrderSourceType.SAAS.getCode());
        productOrderInfo.setSourceName(OrderSourceType.SAAS.getDesc());
        productOrderInfo.setRemark(remark);
        productOrderInfo.setGmtExpect(takeMealDate != null ? takeMealDate.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());
        if (StringUtils.isNotBlank(createOrderVo.getTakeMealTime())) {
            takeMealTime = takeMealTime.append(DateUtil.convert2String(new Date(), "yyyy-MM-dd"))
                    .append(" ").append(createOrderVo.getTakeMealTime()).append(":00");
        }
        long deliveryAmount = 0;
        if (userDeliveryInfoDto != null) {
            deliveryAmount = getUserRealDeliveryAmount(userDeliveryInfoDto.getStoreDeliveryInfoDto(), userDeliveryInfoDto.getUserLongitude(), userDeliveryInfoDto.getUserLatitude());
        }
        Long packageAmount = shoppingCartGoodsDto.getPackageAmount() == null ? 0L : shoppingCartGoodsDto.getPackageAmount();
        productOrderInfo.setAmount(shoppingCartGoodsDto.getTotalAmount() + deliveryAmount + packageAmount
                - shoppingCartGoodsDto.getCardOriginalAmount() + shoppingCartGoodsDto.getCardDiscountAmount());
        // 解析购物车信息
        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;
        ArrayList<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(orderAccountIndex++)
                    .build();
            orderAccountDtos.add(createOrderAccountDto);
        }
        if (deliveryAmount > 0) {
            CreateOrderAccountRequest createOrderAccountDto = CreateOrderAccountRequest.builder()
                    .accountId("")
                    .name("配送费")
                    .price(deliveryAmount)
                    .accountType(QueryOrderAccountType.DELIVERY_AMOUNT)
                    .sequence(orderAccountIndex++)
                    .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(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);
/*        List<CreateOrderProductRequest.ProductDiscount> memberProductList = new ArrayList<>();
        CreateOrderProductRequest.ProductDiscount memberProduct = new CreateOrderProductRequest.ProductDiscount();
        memberProduct.setQueryOrderAccountType(QueryOrderAccountType.CARD_DISCOUNT_AMOUNT);
        memberProduct.setDiscountPrice(cardDiscountAmount);
        List<CreateOrderProductRequest> products = new ArrayList<>();
        CreateOrderProductRequest product = new CreateOrderProductRequest();
        product.setDiscountList(memberProductList);
        products.add(product);
        memberOrderInfo.setProducts(products);*/
        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(StringUtils.isNotBlank(createOrderVo.getCardCode())){
            fatherOrderInfo.setPayChannel("10102");
            fatherOrderInfo.setPayChannelName("储值卡支付");
        }
        long deliveryAmount = 0;
        if (userDeliveryInfoDto != null) {
            deliveryAmount = getUserRealDeliveryAmount(userDeliveryInfoDto.getStoreDeliveryInfoDto(), userDeliveryInfoDto.getUserLongitude(), userDeliveryInfoDto.getUserLatitude());
        }
        Long packageAmount = shoppingCartGoodsDto.getPackageAmount() == null ? 0 : shoppingCartGoodsDto.getPackageAmount();
        fatherOrderInfo.setAmount(shoppingCartGoodsDto.getTotalAmount() + deliveryAmount + 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.MALL.getCode().equals(channelType)) {
            queryOrdersDto.setSource(new String[]{"mall"});
        } 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);
            }
        }

        // 兼容历史版本，如果传参是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()};
            queryOrdersDto.setStatus(statuses);
        }

        if (OrderChannelType.MALL.getCode().equals(channelType)) {
            Integer[] statuses = new Integer[]{OrderStatus.COMPLETE.getCode(), OrderStatus.CALCEL.getCode()};
            queryOrdersDto.setStatus(statuses);
            queryOrdersDto.setType(new Integer[]{});
        }

        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());
            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 {
                responseVo.setTakeOut(0);
                responseVo.setTakeOutDesc("店内就餐");
            }
            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() : "");
            if(ordersBean.getPayChannel() != null && "10102".equals(ordersBean.getPayChannel()) ){
                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());
            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());
            responseVo.setOrderTypeDesc(Optional.ofNullable(OrderType.getByCode(ordersBean.getType()))
                    .map(OrderType::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());
                }
            }
            //商品信息转换
            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();
                    }
                    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");
                        String customerScoreAmountStr = 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.setEnableRefund(false);
            if (OrderStatus.TAKE_ORDER.getCode().equals(ordersBean.getStatus()) && PayStatus.HAVE_PAID.getCode().equals(ordersBean.getPayStatus())) {
                responseVo.setEnableRefund(true);
            }
            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;
    }


    private 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.TAKE_ORDER.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) {
                    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())) {
                        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.setButtonContactPartner(true);
        }
        if (refundBean != null && RefundStatus.ALREADY_REFUND.getCode().equals(refundBean.getStatus())) {
            orderViewStatusDto.setOrderStatus(OrderStatus.CALCEL.getCode());
            orderViewStatusDto.setOrderStatusDesc("退款中");
            orderViewStatusDto.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
            orderViewStatusDto.setButtonContactPartner(true);
        }
        if (OrderStatus.REFUSE.getCode().equals(orderBean.getStatus())) {
            orderViewStatusDto.setOrderStatus(OrderStatus.REFUSE.getCode());
            orderViewStatusDto.setOrderStatusDesc("已退款");
            orderViewStatusDto.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
            orderViewStatusDto.setButtonContactPartner(true);
        }
        if (PayStatus.HAVE_REFUND.getCode().equals(orderBean.getPayStatus())) {
            orderViewStatusDto.setOrderStatus(OrderStatus.REFUSE.getCode());
            orderViewStatusDto.setOrderStatusDesc("已退款");
            orderViewStatusDto.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
            orderViewStatusDto.setButtonContactPartner(true);
        }

        if (OrderStatus.COMPLETE.getCode().equals(orderBean.getStatus())) {
            // TODO: 2019/9/9 获取商户退款配置
            if (refundBean != null && refundBean.getStatus() != null) {
                orderViewStatusDto.setButtonRefund(false);
            } 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:
                orderRefund = configMap.get(OrderRefundEnum.TAKEORDER_REFUND.getKeyValue());
                if (orderRefund == null || (orderRefund != null && ALLOW_REFUND.equals(orderRefund.getAppValue()))) {
                    canRefund = true;
                }
                break;
            //已接单
            case 3:
                orderRefund = configMap.get(OrderRefundEnum.RECEIPTORDER_REFUND.getKeyValue());
                if (orderRefund == null || (orderRefund != null && ALLOW_REFUND.equals(orderRefund.getAppValue()))) {
                    canRefund = true;
                }
                break;
            //制作完成
            case 31:
                orderRefund = configMap.get(OrderRefundEnum.COMPLETEMAKEORDER_REFUND.getKeyValue());
                if (orderRefund != null && ALLOW_REFUND.equals(orderRefund.getAppValue())) {
                    canRefund = true;
                }
                break;
            // 订单完成
            case 5:
                orderRefund = configMap.get(OrderRefundEnum.ORDER_REFUND.getKeyValue());

                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 (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 -> setMealProducts.add(convent2ProductVo(product)));
                    productVo.setSetMealProducts(setMealProducts);
                }
                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());
        productVo.setName(StringUtils.isBlank(productBean.getSpecificationName()) ? productBean.getProductName() : productBean.getSpecificationName());
        productVo.setSpuName(productBean.getProductName());
        productVo.setPicture(productBean.getPicture());
        productVo.setSequence(productBean.getSequence());
        productVo.setQty(productBean.getNumber());
        productVo.setSpecification("");
        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);
        }
        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;
//        Long saleTotalAmount = originalTotalAmount - discountTotalAmount;
        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 OrderRefundRequestDto convent2OrderRefundRequestDto(OrderRefundVo orderRefundVo, String orderId) {
        OrderRefundRequestDto orderRefundRequestDto = new OrderRefundRequestDto();
        orderRefundRequestDto.setOrderId(orderId);
        orderRefundRequestDto.setReason(orderRefundVo.getReason());
        orderRefundRequestDto.setRemark(orderRefundVo.getRemarks());
        return orderRefundRequestDto;
    }

    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) {
        //Long refund_id = System.currentTimeMillis();
        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");
        }
        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());
//        List<ProductBean> productBeans = orderBean.getProductList().stream().filter(p -> StringUtils.isEmpty(p.getParentProductId())).collect(Collectors.toList());
        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<>();
            if (CollectionUtils.isNotEmpty(productBean.getComboProduct())) {
                for (QueryOrdersResponseDto.DataBean.OrderBean.ProductBean comboProduct : productBean.getComboProduct()) {
                    OrderPrintDto.ProductsBean sonProductVO = getProductBean(comboProduct);
                    comboProductVOs.add(sonProductVO);
                }
            }
            productVO.setSonProducts(comboProductVOs);
            products.add(productVO);
        }

//        // 套餐商品map key=组装ParentProductId  v=订单结构的商品信息
//        Map<String, QueryOrdersResponseDto.DataBean.OrderBean.ProductBean> map = productBeans.stream().filter(productBean ->
//                productBean.getProductType() != null && productBean.getProductType() == 6)
//                .collect(Collectors.toMap(p -> p.getProductId() + "_" + p.getSequence(), p -> p));
//        //套餐商品map key=ParentProductId  v=打印的套餐商品
//        Map<String, OrderPrintDto.ProductsBean> map2 = new HashMap<>();
//
//        productBeans.stream().forEach((QueryOrdersResponseDto.DataBean.OrderBean.ProductBean productBean) -> {
//            OrderPrintDto.ProductsBean productBean1 = getProductBean(productBean);
//
//            QueryOrdersResponseDto.DataBean.OrderBean.ProductBean productBean2 = map.get(productBean.getParentProductId());
//            //套餐子商品
//            if (productBean2 != null) {
//                OrderPrintDto.ProductsBean productsBean = map2.get(productBean.getParentProductId());
//                List<OrderPrintDto.ProductsBean> sonProducts;
//                if (productsBean != null) {
//                    sonProducts = productsBean.getSonProducts();
//                    sonProducts.add(productBean1);
//                    productsBean.setSonProducts(sonProducts);
//                    map2.put(productBean.getParentProductId(), productsBean);
//                } else {
//                    OrderPrintDto.ProductsBean productBean3 = getProductBean(productBean2);
//                    sonProducts = productBean3.getSonProducts();
//                    sonProducts.add(productBean1);
//                    map2.put(productBean.getParentProductId(), productBean3);
//                }
//            }
//            if ((StringUtils.isBlank(productBean.getParentProductId()) || "0".equals(productBean.getParentProductId()))
//                    && productBean.getProductType() != 6) {
//                products.add(productBean1);
//            }
//
//        });
//        products.addAll(map2.values());
        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.setButtonContactPartner(true);
    }

    public void setAgreeRefundDesc(OrderViewStatusDto orderViewStatusDto, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        orderViewStatusDto.setOrderStatus(orderBean.getStatus());
        orderViewStatusDto.setOrderStatusDesc("退款中");
        orderViewStatusDto.setOrderStatusDescText("感谢您对我们的信任，期待再次光临~");
        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);
        }
        createOrderProductDemoDto.setProductType(cartGoodsDetailDto.getProductType());
        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.setIsFixedProduct(false);
        createOrderProductDemoDto.setCustomerCode(cartGoodsDetailDto.getCustomerCode());
        createOrderProductDemoDto.setHasStockProudct(cartGoodsDetailDto.isStockLimit());
        createOrderProductDemoDto.setWeight(cartGoodsDetailDto.getWeight());
        createOrderProductDemoDto.setUnit(cartGoodsDetailDto.getUnit());
        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_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;
        }
        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) {
        UnifiedOrderRequest orderPayDto = new UnifiedOrderRequest();
        orderPayDto.setPartnerId(orderBean.getCompanyId());
        orderPayDto.setBody(paymentRequest.getPrincipalName());
        orderPayDto.setNotifyUrl(paymentRequest.getReverseNotifyiDcUrl());
        orderPayDto.setStoreId(orderBean.getShopId());
        orderPayDto.setTransId(orderBean.getOid());
        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());
        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);
        return orderPayDto;
    }

/*    public CancelOrderRequest convent2CancelOrderRequest(String orderId, String partnerId, AfterSalesType afterSalesType,
                                                         String reason, String trackingNo, Long refund_id) {
        CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
        cancelOrderRequest.setOrderId(orderId);
        cancelOrderRequest.setPartnerId(partnerId);
        cancelOrderRequest.setAfterSalesType(afterSalesType);
        cancelOrderRequest.setReason(reason);
        cancelOrderRequest.setTrackingNo(trackingNo);
        if (refund_id != null) {
            cancelOrderRequest.setRefundSerialNo(refund_id.toString());
        }
        return cancelOrderRequest;
    }*/

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

    /**
     * 获取自定义信息
     */
    public OrderExtInfoDTO getOrderExtInfo(OrderPayResponse orderPayResponse, OrderExtInfoDTO orderExtInfoDto) {
        orderExtInfoDto.setOpenid(orderPayResponse.getOpenId());
        String prepayId = "";
        // StringUtils 依赖修改
        if (orderPayResponse.getPayOrder() != null && !StringUtils.isEmpty(orderPayResponse.getPayOrder().getPackageX())) {
            String[] prepayIds = orderPayResponse.getPayOrder().getPackageX().split("=");
            prepayId = prepayIds.length > 1 ? prepayIds[1] : "";
        }
        orderExtInfoDto.setPrepayId(prepayId);
//        orderExtInfoDto.setAppid(orderPayResponse.getWxAppid());
//        orderExtInfoDto.setServiceTime(orderEditInfo.getServiceTime());
//        orderExtInfoDto.setPushOrderTime(orderEditInfo.getPushOrderTime());
//        orderExtInfoDto.setSessionId(orderEditInfo.getSessionId());
//        orderExtInfoDto.setVersion(orderEditInfo.getVersion());
//        orderExtInfoDto.setRuleId(orderEditInfo.getRuleId());
        return orderExtInfoDto;
    }

    /**
     * 转换前端支付需要的信息
     *
     * @param orderPayResponse
     * @return
     */
    public CreateOrderFlowResponse.CreateOrderResponseVo convent2CreateOrderResponseVo(OrderPayResponse orderPayResponse) {
        CreateOrderFlowResponse.CreateOrderResponseVo createOrderResponseVo = new CreateOrderFlowResponse.CreateOrderResponseVo();
        createOrderResponseVo.setOrderId(orderPayResponse.getOrderId());
        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());
        return createOrderResponseVo;
    }

    /**
     * 父子订单转换前端支付需要的信息
     *
     * @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());
        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());
            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());
        return previewOrderInfoVo;
    }

    /**
     * 购物车信息转换
     */
    public AssortmentSdkUpdateOrderProductInfoRequest conventShoppingCartGoodsDtoByUpdate(ShoppingCartGoodsDto shoppingCartGoodsDto,
            AssortmentCustomerInfoVo assortmentCustomerInfoVo, String orderId, Integer dinersNumber,String nickName) {
        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) {
                CreateOrderProductRequest createOrderProductDto = convent2OrderProduct(cartGoodsDetailDto);
                createOrderProductDto.setIgnoreProductPrice(1);
                createOrderProductRequests.add(createOrderProductDto);
            }
        }
        orderProductInfoRequest.setOrderItemList(createOrderProductRequests);
        orderProductInfoRequest.setOperator(nickName);
        orderProductInfoRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        return orderProductInfoRequest;
    }

    /**
     * 转换促销信息--修改订单及商品金额
     *
     * @param shoppingCartGoodsResponse
     * @param queryOrderByIdResponse
     * @return
     */
    public AssortmentSdkUpdateOrderProductInfoRequest conventShoppingPromotionInfo(ShoppingCartGoodsResponse shoppingCartGoodsResponse, QueryOrderByIdResponse queryOrderByIdResponse, AssortmentCustomerInfoVo assortmentCustomerInfoVo) {
        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());
        sdkUpdateOrderProductInfoRequest.setOpUpdateOrderItemEnum(AssortmentSdkUpdateOrderProductInfoRequest.OpUpdateOrderItemEnum.updatePrePayPrice);
        sdkUpdateOrderProductInfoRequest.setThirdOrderCode(queryOrderByIdResponse.getData().getThirdOrderCode());
        /*sdkUpdateOrderProductInfoRequest.setActualPayAmount(shoppingCartGoodsResponse.getTotalAmount());
        sdkUpdateOrderProductInfoRequest.setOriginalAmount(shoppingCartGoodsResponse.getOriginalTotalAmount());
        sdkUpdateOrderProductInfoRequest.setSettlementAmount(shoppingCartGoodsResponse.getTotalAmount());*/
        sdkUpdateOrderProductInfoRequest.setUserId(assortmentCustomerInfoVo.getMemberId());
        sdkUpdateOrderProductInfoRequest.setUserName(assortmentCustomerInfoVo.getNickName());
        sdkUpdateOrderProductInfoRequest.setOperator(assortmentCustomerInfoVo.getNickName());
        //商品信息
        /*List<CreateOrderProductRequest> createOrderProductRequests = new ArrayList<>();
        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);*/
        return sdkUpdateOrderProductInfoRequest;
    }

    private CreateOrderProductRequest conventOrderInfoAndCarInfoByUpdate(QueryOrdersResponse.DataBean.OrderBean.ProductBean productBean, ShoppingCartGoodsResponse.CartGoodsDetailDto cartGoodsDetailDto) {
        CreateOrderProductRequest createOrderProductRequest = new CreateOrderProductRequest();
        createOrderProductRequest.setId(productBean.getId());
        createOrderProductRequest.setNumber(cartGoodsDetailDto.getQty());
        createOrderProductRequest.setTotalDiscountAmount(cartGoodsDetailDto.getTotalDiscountAmount().longValue());
        createOrderProductRequest.setPrice(cartGoodsDetailDto.getOriginalPrice());
        createOrderProductRequest.setSalePrice((cartGoodsDetailDto.getOriginalPrice() * cartGoodsDetailDto.getQty()) - cartGoodsDetailDto.getTotalDiscountAmount());
        createOrderProductRequest.setAddInfo(productBean.getAddInfo());
        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) {
        OrderBeanRequest orderBeanRequest = new OrderBeanRequest();
        orderBeanRequest.setAmount(orderBean.getAmount());
        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.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.setUnit(comPro.getUnit());
                    comProductBean.setWeight(comPro.getWeight());
                    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;
    }

}
