package cn.freemud.service.impl;

import cn.freemud.adapter.OrderAdapter;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.bo.CreateOrderBONew;
import cn.freemud.entities.dto.ConfirmOrderDto;
import cn.freemud.entities.dto.StoreResponseDto;
import cn.freemud.entities.dto.coupon.InvalidCouponsRequestDto;
import cn.freemud.entities.dto.coupon.InvalidCouponsResponseDto;
import cn.freemud.entities.dto.order.CreateOrderOperateDto;
import cn.freemud.entities.dto.order.CreatePrepayRequestDto;
import cn.freemud.entities.dto.shoppingCart.ActivityDiscountsDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.dto.store.StoreMixResponseDto;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.OrderStatus;
import cn.freemud.enums.PayStatus;
import cn.freemud.enums.ResponseResult;
import cn.freemud.enums.TradeState;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.redis.RedisCache;
import cn.freemud.service.AppOrderService;
import cn.freemud.service.StoreService;
import cn.freemud.service.thirdparty.CouponOnlineClient;
import cn.freemud.utils.BeanUtil;
import cn.freemud.utils.RedisUtil;
import cn.freemud.utils.ResponseUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.application.sdk.api.base.SDKCommonBaseContextWare;
import com.freemud.application.sdk.api.constant.ResponseResultEnum;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.enums.AfterSalesType;
import com.freemud.application.sdk.api.ordercenter.enums.BizTypeEnum;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest;
import com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
import com.freemud.application.sdk.api.paymentcenter.client.request.PaymentCloseUnifiedOrderRequest;
import com.freemud.application.sdk.api.paymentcenter.client.request.PaymentQueryRequest;
import com.freemud.application.sdk.api.paymentcenter.client.response.PaymentCloseUnifiedOrderResponse;
import com.freemud.application.sdk.api.paymentcenter.client.response.PaymentQueryResponse;
import com.freemud.application.sdk.api.paymentcenter.client.service.PaymentNewService;
import com.freemud.application.sdk.api.productcenter.domain.ProductBeanDTO;
import com.freemud.application.sdk.api.productcenter.domain.ProductInfosDTO;
import com.freemud.application.sdk.api.productcenter.request.product.GetProductRequest;
import com.freemud.application.sdk.api.productcenter.service.ProductService;
import com.freemud.application.sdk.api.storecenter.request.StoreInfoRequest;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import com.freemud.sdk.api.assortment.order.adapter.OrderSdkAdapter;
import com.freemud.sdk.api.assortment.order.entities.promption.SubtractStockVO;
import com.freemud.sdk.api.assortment.order.request.order.CancelOrderRequest;
import com.freemud.sdk.api.assortment.order.request.order.OrderEditRequest;
import com.freemud.sdk.api.assortment.order.request.order.QueryRelatedOrderByCodeRequest;
import com.freemud.sdk.api.assortment.order.response.order.BaseOrderResponse;
import com.freemud.sdk.api.assortment.order.response.order.CreateOrderResponse;
import com.freemud.sdk.api.assortment.order.response.order.QueryRelatedOrderByCodeResp;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
public class AppOrderServiceImpl implements AppOrderService {

    @Autowired
    private OrderServiceImpl orderservice;
    @Autowired
    private CheckOrder checkOrder;
    @Autowired
    private OrderAdapter orderAdapter;
    @Autowired
    private OrderCenterSdkService orderCenterSdkService;
    @Autowired
    private PaymentNewService paymentNewService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RedisService redisService;

    @Autowired
    private StoreServiceImpl storeService;

    @Autowired
    private OrderSdkService orderSdkService;
    @Autowired
    private OrderSdkAdapter orderSdkAdapter;
    @Autowired
    private SellCouponOrderServiceImpl sellCouponOrderService;

    @Autowired
    private CouponOnlineClient couponOnlineClient;

    @Autowired
    private PayServiceImpl payServiceimpl;

    /**
     * 不支持会员卡
     */
    @Override
    public BaseResponse createOrder(CreateOrderBONew createOrderBO) {
        String trackingNo = LogThreadLocal.getTrackingNo();
        CreateOrderVo createOrderVo = createOrderBO.getCreateOrderVo();
        // 查询用户信息
        AssortmentCustomerInfoVo userLoginInfoDto = checkOrder.checkOrderByMember(createOrderBO);
        // 查询门店信息 营业时间、营业状态，服务器当前时间在营业时间内 点餐桌号
        StoreResponseDto storeResponseDto = checkOrder.checkOrderByStore(createOrderBO).getStoreInfo();
        // 查询购物车（内部校验券点餐方式，券是否可用） 校验当前订单类型的下单参数
        ShoppingCartGoodsDto shoppingCartGoodsDto = checkOrder.getShoppingCartGoodsDto(createOrderVo);
        createOrderBO.setShoppingCartGoodsDto(shoppingCartGoodsDto);
        // 查询小程序自提外卖配置信息 校验当前订单类型的下单参数 校验外卖是否满足起送条件
        Integer pushOrderTime = checkOrder.checkOrderByOrderType(createOrderBO);
        //1.5.4版本，商品库存校验与扣库存
        //List<String> stockProductIds = checkOrder.getStockProductIdList(createOrderVo, shoppingCartGoodsDto);
        // 下单前检查优惠券是否可用
        if (StringUtils.isNotBlank(createOrderVo.getCouponCode())){
            InvalidCouponsRequestDto requestDto = new InvalidCouponsRequestDto();
            List<String> couponList = new ArrayList<>();
            couponList.add(createOrderVo.getCouponCode());
            requestDto.setCouponCodes(couponList);
            requestDto.setPartnerId(Integer.valueOf(createOrderVo.getPartnerId()));
            InvalidCouponsResponseDto invalidCouponsResponseDto = couponOnlineClient.invalidCoupons(requestDto);
            if (invalidCouponsResponseDto.getStatusCode() != 100 || invalidCouponsResponseDto.getData() == null || (invalidCouponsResponseDto.getData() != null && CollectionUtils.isNotEmpty(invalidCouponsResponseDto.getData().getInvalidCoupons()))){
                return ResponseUtil.error(ResponseResult.COUPON_INVALID.getCode(), ResponseResult.COUPON_INVALID.getMessage());
            }
        }

        OrderExtInfoDto extInfo = orderservice.setOrderExtInfo(userLoginInfoDto, storeResponseDto, pushOrderTime, createOrderVo, shoppingCartGoodsDto);
        //创建订单
        BaseResponse createOrderOperateDtoResponse = orderservice.sdkCreateOrder(createOrderBO);
        if (createOrderOperateDtoResponse == null || !ResponseResult.SUCCESS.getCode().equals(createOrderOperateDtoResponse.getCode()) || createOrderOperateDtoResponse.getResult() == null) {
            return createOrderOperateDtoResponse;
        }
        CreateOrderOperateDto createOrderOperateDto = (CreateOrderOperateDto) createOrderOperateDtoResponse.getResult();
        BaseResponse baseResponse = this.updateOrderExtInfo(createOrderOperateDto.getProductOrderBean(), extInfo, trackingNo);
        if (baseResponse != null) {
            return baseResponse;
        }
        //返回没创建预支付的结果
        CreateOrderResponseVo responseVo = orderAdapter.convent2CreateFatherSonOrderNoPayResponseVo(createOrderOperateDto.getProductOrderBean());
        return ResponseUtil.success(responseVo);
    }

    @Override
    public BaseResponse createPrepay(CreatePrepayVo createPrepayVo) {
        CreateOrderOperateDto createOrderOperateDto = this.getCreateOrderOperateDto(createPrepayVo.getOrderCode());
        OrderBeanV1 productOrderBean = createOrderOperateDto.getProductOrderBean();
        this.checkOrderBefore(createPrepayVo, productOrderBean);
        // 关闭历史预支付订单
        this.closeHistoryPrePay(productOrderBean);
        OrderExtInfoDto extInfo = JSONObject.parseObject(productOrderBean.getExtInfo(), OrderExtInfoDto.class);
        extInfo.setAppid(createPrepayVo.getPayAppId());
        extInfo.setOpenid(createPrepayVo.getOpenId());
        if (StringUtils.isNotBlank(createPrepayVo.getPayCode())) {
            extInfo.setPayCode(createPrepayVo.getPayCode());
        }
        String faceCode = "";
        String cardCode = "";
        String transId = createPrepayVo.getOrderCode() + redisService.increment(RedisUtil.getPaymentTransIdSequenceKey(createPrepayVo.getOrderCode()), 1, TimeUnit.DAYS);
        CreatePrepayRequestDto createPrepayRequestDto = orderAdapter.convertToCreatePrepayRequestDto(createPrepayVo.getPartnerId(), createPrepayVo.getPayAppId(), createPrepayVo.getOpenId(), faceCode,
                cardCode, createPrepayVo.getPayCode(), createOrderOperateDto.getFatherOrderBean(), createOrderOperateDto.getProductOrderBean(), createOrderOperateDto.getTotalAmount(),
                createOrderOperateDto.getCardAmount(), extInfo, transId, OrderClientType.APP);
        redisService.savePaymentTransIdOrder(RedisUtil.getPaymentTransIdOrderKey(transId), productOrderBean.getOid(), 60L, TimeUnit.MINUTES);
        return ResponseUtil.success(payServiceimpl.createPrepayOrder(createPrepayRequestDto));
    }


    /**
     * APP下单，下单带商品信息，不经过购物车服务，不唤起支付
     */
    @Override
    public BaseResponse createOrderOld(AppCreateOrderVo createOrderReq, AssortmentCustomerInfoVo customerInfo) {
        String trackingNo = LogThreadLocal.getTrackingNo();
        String partnerId = createOrderReq.getPartnerId();
        String shopId = createOrderReq.getShopId();
        // 获取门店信息
        StoreMixResponseDto storeMixResponseDto = storeService.getStoreInfoNew(partnerId, shopId, false,false);
        if (storeMixResponseDto == null || storeMixResponseDto.getStoreInfo() == null) {
            throw new ServiceException(ResponseResult.STORE_NOT_FOUND);
        }
        StoreResponseDto storeResponse = storeMixResponseDto.getStoreInfo();
        // 查询门店信息 营业时间、营业状态，服务器当前时间在营业时间内 点餐桌号
        checkOrder.checkOrderByStore(storeResponse);
        /**蜜雪新增需求-->APP可以购买虚拟商品券业务逻辑**/
        OrderBeanV1 orderBean = new OrderBeanV1();
        if (createOrderReq.getBizType() != null && BizTypeEnum.SALE_COUPON.getBizType().equals(createOrderReq.getBizType())) {
            //现阶段蜜雪卖券业务是能单个，所以默认取0.后续多个的话，也需要调整平台买券取数规则
            String skuId = createOrderReq.getOrderProducts().get(0).getSkuId();
            //20200107提取虚拟商品券效验方法---》校验虚拟商品，如果正常则返回创建订单对象
            BaseResponse createOrderRequestResponse =
                    sellCouponOrderService.checkOrderCoupon(customerInfo, storeResponse, trackingNo, createOrderReq.getMenuType(), Integer.valueOf(createOrderReq.getBizType()), partnerId, shopId, skuId, null,createOrderReq.getScene());
            if (createOrderRequestResponse == null || !ResponseResult.SUCCESS.getCode().equals(createOrderRequestResponse.getCode()) || createOrderRequestResponse.getResult() == null) {
                return createOrderRequestResponse;
            }
            CreateOrderRequest createOrderRequest = (CreateOrderRequest) createOrderRequestResponse.getResult();
            OrderExtInfoDto orderExtInfoDto = new OrderExtInfoDto();
            orderExtInfoDto.setOpenid(customerInfo.getOpenId());
            orderExtInfoDto.setAppid(customerInfo.getWxAppId());
            orderExtInfoDto.setSessionId(customerInfo.getSessionId());
            // 扩展字段中存储 sessionKey
            orderExtInfoDto.setSessionKey(customerInfo.getSessionKey());
            orderExtInfoDto.setFromAppId(customerInfo.getWxAppId());
            createOrderRequest.setExtInfo(JSONArray.toJSON(orderExtInfoDto).toString());
            OrderBaseResp<OrderInfoReqs> orderInfoReqsBaseResponse = orderSdkService.createOrder(createOrderRequest, trackingNo);
            CreateOrderResponse createOrderResponse = orderSdkAdapter.convent2NEWOrderInfoReqs(orderInfoReqsBaseResponse);
            if (createOrderResponse == null || createOrderResponse.getErrcode() != 100) {
                return ResponseUtil.error(ResponseResult.ORDER_CREATE_ERROR);
            }
            orderBean = createOrderResponse.getData();
        } else {
            /**APP创建实体商品业务逻辑**/
            // 查商品服务确定金额
            ShoppingCartGoodsDto shoppingCartGoodsDto = checkOrderProduct(partnerId, shopId, createOrderReq.getOrderProducts(),
                    createOrderReq.getMenuType(), createOrderReq.getReachStoreType());
            CreateOrderVo createOrderVo = new CreateOrderVo();
            BeanUtil.convertBean(createOrderReq, createOrderVo);
            CreateOrderBONew createOrderBO = new CreateOrderBONew(createOrderVo);
            createOrderBO.setUserLoginInfoDto(customerInfo);
            createOrderBO.setStoreMixResponseDto(storeMixResponseDto);
            createOrderBO.setShoppingCartGoodsDto(shoppingCartGoodsDto);
            createOrderVo.setStoreName(storeResponse.getStoreName());
            // 查询小程序自提外卖配置信息 校验当前订单类型的下单参数 校验外卖是否满     足起送条件
            Integer pushOrderTime = checkOrder.checkOrderByOrderType(createOrderBO);
            //1.5.4版本，商品库存校验与扣库存
            //List<String> stockProductIds = checkOrder.getStockProductIdList(createOrderVo, shoppingCartGoodsDto);
            OrderExtInfoDto extInfo = orderAdapter.setOrderExtInfo(customerInfo, storeResponse, createOrderVo, shoppingCartGoodsDto);
            //创建订单
            BaseResponse createOrderOperateDtoResponse = orderservice.sdkCreateOrder(createOrderBO);
            if (createOrderOperateDtoResponse == null || !ResponseResult.SUCCESS.getCode().equals(createOrderOperateDtoResponse.getCode()) || createOrderOperateDtoResponse.getResult() == null) {
                return createOrderOperateDtoResponse;
            }
            CreateOrderOperateDto createOrderOperateDto = (CreateOrderOperateDto) createOrderOperateDtoResponse.getResult();
            BaseResponse baseResponse = this.updateOrderExtInfo(createOrderOperateDto.getProductOrderBean(), extInfo, trackingNo);
            if (baseResponse != null) {
                return baseResponse;
            }
            orderBean = createOrderOperateDto.getProductOrderBean();
        }
        //返回没创建预支付的结果
        CreateOrderResponseVo responseVo = orderAdapter.convent2CreateFatherSonOrderNoPayResponseVo(orderBean);
        return ResponseUtil.success(responseVo);
    }


    @Override
    public String paySuccessCallback(PaysuccessNoticeMessage message, ConfirmOrderDto confirmOrderDto, Map<String, OrderBeanV1> orderBeans) {
        String paySuccessCallbackResult = orderservice.paySuccessCallback(message, confirmOrderDto, orderBeans);
//        QueryOrdersResponseDto.DataBean.OrderBean orderBean = orderBeans.get(OrderBeanType.SAASORDER.getCode());
        // 删除订单自增缓存
        //redisCache.delete(RedisUtil.getPaymentTransIdSequenceKey(orderBean.getOid()));
        // 删除支付交易号订单关系缓存
        //redisCache.delete(RedisUtil.getPaymentTransIdOrderKey(message.getTrans_id()));
        return paySuccessCallbackResult;
    }

    private void checkOrderBefore(CreatePrepayVo createPrepayVo, OrderBeanV1 orderBean) {
        if (!PayStatus.NOT_PAY.getCode().equals(orderBean.getPayStatus()) || !OrderStatus.WAIT_PAY.getCode().equals(orderBean.getStatus())) {
            throw new ServiceException(ResponseResult.ORDER_STATUS_PRE_PAYMENT_NOT_SUPPORT);
        }
        //蜜雪sessionId不一致的跳过验证
        OrderExtInfoDto extInfo = JSONObject.parseObject(orderBean.getExtInfo(), OrderExtInfoDto.class);
//        if (extInfo == null || StringUtils.isBlank(extInfo.getSessionId()) || !extInfo.getSessionId().equals(createPrepayVo.getSessionId())) {
        if (extInfo == null || StringUtils.isBlank(extInfo.getSessionId())) {
            throw new ServiceException(ResponseResult.ORDER_OWNER_ERROR);
        }
    }

    /**
     * 更新订单扩展信息
     */
    private BaseResponse updateOrderExtInfo(OrderBeanV1 orderBean, OrderExtInfoDto orderExtInfo, String trackingNo) {
        OrderEditRequest orderEditRequest = new OrderEditRequest(orderBean.getOid(), JSONObject.toJSONString(orderExtInfo));
        orderEditRequest.setTrackingNo(trackingNo);
        BaseOrderResponse baseOrderResponse = orderCenterSdkService.orderEdit(orderEditRequest);
        if (!ObjectUtils.equals(ResponseCodeConstant.RESPONSE_SUCCESS, baseOrderResponse.getErrcode())) {
            CancelOrderRequest cancelOrderRequest = orderAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
                    AfterSalesType.SYSTEM_CANCEL, "编辑订单支付信息失败", trackingNo, null);
            orderCenterSdkService.orderCancel(cancelOrderRequest);
            return ResponseUtil.error(baseOrderResponse.getErrcode().toString(), baseOrderResponse.getErrmsg());
        }
        return null;
    }

    private CreateOrderOperateDto getCreateOrderOperateDto(String orderId) {
        QueryRelatedOrderByCodeRequest baseQueryOrderRequest = new QueryRelatedOrderByCodeRequest();
        baseQueryOrderRequest.setOrderCode(orderId);
        baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        QueryRelatedOrderByCodeResp queryOrderByIdResponse = orderCenterSdkService.queryRelatedOrderByCode(baseQueryOrderRequest);
        if (queryOrderByIdResponse == null || CollectionUtils.isEmpty(queryOrderByIdResponse.getOrderBeanList())) {
            throw new ServiceException(ResponseResult.ORDER_QUERYORDER_ERROR);
        }
        List<OrderBeanV1> orderBeanList = queryOrderByIdResponse.getOrderBeanList();
        long totalAmount = 0;
        OrderBeanV1 fatherBeanListOne = new OrderBeanV1();
        OrderBeanV1 productBeanListOne = new OrderBeanV1();
        if (1 == orderBeanList.size()) {
            fatherBeanListOne = orderBeanList.get(0);
            productBeanListOne = orderBeanList.get(0);
            totalAmount = orderBeanList.get(0).getAmount();
        } else {
            fatherBeanListOne = orderBeanList.stream().filter(orderBeanTemp -> orderBeanTemp.getIsParent()).findFirst().orElse(fatherBeanListOne);
            productBeanListOne = orderBeanList.stream().filter(orderBeanTemp -> 1 == orderBeanTemp.getBizType()).findFirst().orElse(productBeanListOne);
            totalAmount = orderBeanList.stream().mapToLong(OrderBeanV1::getAmount).count();
        }

        CreateOrderOperateDto createOrderOperateDto = new CreateOrderOperateDto();
        createOrderOperateDto.setTotalAmount(totalAmount);
        createOrderOperateDto.setCardAmount(0);
        createOrderOperateDto.setFatherOrderBean(fatherBeanListOne);
        createOrderOperateDto.setProductOrderBean(productBeanListOne);
        return createOrderOperateDto;
    }

    private void closeHistoryPrePay(OrderBeanV1 orderBean) {
        OrderExtInfoDto extInfo = JSONObject.parseObject(orderBean.getExtInfo(), OrderExtInfoDto.class);
        //判断当前订单是否存在预支付订单
        if (extInfo != null && StringUtils.isNotEmpty(extInfo.getFmId())) {
            //订单状态未支付且存在预支付订单：
            // 1.查询预支付订单支付状态
            PaymentQueryRequest paymentQueryRequest = new PaymentQueryRequest();
            paymentQueryRequest.setPartnerId(orderBean.getCompanyId());
            paymentQueryRequest.setStoreId(orderBean.getShopId());
            paymentQueryRequest.setFmId(extInfo.getFmId());
            paymentQueryRequest.setVer("2");
            com.freemud.application.sdk.api.base.BaseResponse<PaymentQueryResponse> queryResponseBaseResponse = paymentNewService.query(paymentQueryRequest, LogThreadLocal.getTrackingNo());
            //判断预支付订单状态
            if (ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), queryResponseBaseResponse.getCode())) {
                throw new ServiceException(ResponseResult.ORDER_PAY_GETPRE_MESSAGE_ERROR);
            }
            //判断当前预支付订单是否已经支付成功
            if (ObjectUtils.equals(TradeState.SUCCESS.getCode(), queryResponseBaseResponse.getData().getTradeState())) {
                throw new ServiceException(ResponseResult.ORDER_HAS_PAID);
            }
            // 3.取消前一个预支付订单  调用支付取消预支付订单,如果预支付订单已经取消了再调用取消预支付订单接口会报错的
            if (ObjectUtils.equals(TradeState.NOTPAY.getCode(), queryResponseBaseResponse.getData().getTradeState())) {
                PaymentCloseUnifiedOrderRequest closeUnifiedOrderRequest = new PaymentCloseUnifiedOrderRequest();
                closeUnifiedOrderRequest.setFmId(extInfo.getFmId());
                closeUnifiedOrderRequest.setVer("2");
                closeUnifiedOrderRequest.setPartnerId(orderBean.getCompanyId());
                closeUnifiedOrderRequest.setStoreId(orderBean.getShopId());
                com.freemud.application.sdk.api.base.BaseResponse<PaymentCloseUnifiedOrderResponse> cancelNewUnifiedOrder = paymentNewService.cancelNewUnifiedOrder(closeUnifiedOrderRequest, LogThreadLocal.getTrackingNo());
                if (ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), cancelNewUnifiedOrder.getCode())) {
                    throw new ServiceException(ResponseResult.ORDER_PRE_PAYMENT_CLOSE_FAILED);
                }
            }
        }
    }


    /**
     * 查询商品信息
     */
    public ShoppingCartGoodsDto checkOrderProduct(String partnerId, String shopId, List<OrderProductVo> orderProducts,
                                                  String menuType, Integer reachStoreType) {
        ShoppingCartGoodsDto shoppingCartGoodsDto = new ShoppingCartGoodsDto();


        List<String> spuIds = new ArrayList<>();
        for (OrderProductVo op : orderProducts) {
            if (StringUtils.isNotBlank(op.getSkuId())) {
                spuIds.add(op.getSpuId());
            }
        }

        if (CollectionUtils.isEmpty(spuIds)) {
            throw new ServiceException(ResponseResult.PARAMETER_MISSING);
        }
        //去重
        List<String> result = spuIds.stream().distinct().collect(Collectors.toList());

        GetProductRequest getProductInfoDto = new GetProductRequest();
        getProductInfoDto.setPartnerId(partnerId);
        getProductInfoDto.setShopId(shopId);
        getProductInfoDto.setProductInfoType(2);
        getProductInfoDto.setProductIds(result);
        getProductInfoDto.setChannel(menuType);
        ProductService productService = SDKCommonBaseContextWare.getBean(ProductService.class);
        com.freemud.application.sdk.api.base.BaseResponse<ProductInfosDTO> productInfosDTOBaseResponse = productService.listProductInfoByIdList(getProductInfoDto, LogThreadLocal.getTrackingNo());
        if (!Objects.equals(ResponseResultEnum.SUCCESS.getCode(), productInfosDTOBaseResponse.getCode())
                || productInfosDTOBaseResponse.getData() == null || productInfosDTOBaseResponse.getData().getProducts().size() == 0) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_PRODUCT_NOT_EXIST);
        }

        List<ProductBeanDTO> productBeanDTOS = productInfosDTOBaseResponse.getData().getProducts();

        //包装费
        Long packageAmount = 0L;
        //原总价
        Long originalTotalAmount = 0L;
        //总价
        Long totalAmount = 0L;

        int sequence = 0;
        List<ShoppingCartGoodsDto.CartGoodsDetailDto> products = new ArrayList<>();
        for (OrderProductVo op : orderProducts) {
            sequence += 1;
            ShoppingCartGoodsDto.CartGoodsDetailDto cartGoodsDetailDto = new ShoppingCartGoodsDto.CartGoodsDetailDto();
            //单品
            if (StringUtils.isNotBlank(op.getSpuId()) && op.getSpuId().equals(op.getSkuId())) {
                for (ProductBeanDTO productBeanDTO : productBeanDTOS) {
                    if (op.getSpuId().equals(productBeanDTO.getPid())) {
                        cartGoodsDetailDto.setSpuId(productBeanDTO.getPid());
                        cartGoodsDetailDto.setSkuId(productBeanDTO.getPid());
                        cartGoodsDetailDto.setSpuName(productBeanDTO.getName());
                        cartGoodsDetailDto.setSkuName(productBeanDTO.getName());
                        cartGoodsDetailDto.setOriginalPrice(productBeanDTO.getOriginalPrice());
                        originalTotalAmount += productBeanDTO.getOriginalPrice() * op.getQty();
                        totalAmount += productBeanDTO.getFinalPrice() * op.getQty();
                        packageAmount += productBeanDTO.getPackPrice() * op.getQty();
                        cartGoodsDetailDto.setPicture(productBeanDTO.getPicture());
                        cartGoodsDetailDto.setQty(op.getQty());
                        cartGoodsDetailDto.setTotalDiscountAmount(0);
                        cartGoodsDetailDto.setHasProductCoupon(false);
                        cartGoodsDetailDto.setStockLimit(productBeanDTO.getStockLimit() == 1);
                        cartGoodsDetailDto.setWeight(productBeanDTO.getWeight());
                        cartGoodsDetailDto.setSequence(sequence);
                        cartGoodsDetailDto.setUnit(productBeanDTO.getUnit());

                        List<ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra> extraList = new ArrayList<>();
                        if (CollectionUtils.isNotEmpty(op.getExtra())) {
                            for (OrderProductExtraVo orderProductExtraVo : op.getExtra()) {
                                ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra cartGoodsExtra = new ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra();
                                cartGoodsExtra.setAttributeId(orderProductExtraVo.getAttributeId());
                                cartGoodsExtra.setAttributeName(orderProductExtraVo.getAttributeName());
                                extraList.add(cartGoodsExtra);
                            }
                        }
                        cartGoodsDetailDto.setExtraList(extraList);
                        cartGoodsDetailDto.setActivityDiscountsDtos(null);
                        cartGoodsDetailDto.setComboProducts(null);
                        break;
                    }

                }
            }

            //多规格商品
            if (StringUtils.isNotBlank(op.getSpuId()) && !op.getSpuId().equals(op.getSkuId())) {
                for (ProductBeanDTO productBeanDTO : productBeanDTOS) {
                    if (op.getSpuId().equals(productBeanDTO.getPid())) {
                        cartGoodsDetailDto.setSpuId(productBeanDTO.getPid());
                        cartGoodsDetailDto.setSpuName(productBeanDTO.getName());

                        for (ProductBeanDTO.SkuProductBean skuProductBean : productBeanDTO.getSkuList()) {
                            if (op.getSkuId().equals(skuProductBean.getSkuId())) {
                                cartGoodsDetailDto.setSkuId(skuProductBean.getSkuId());
                                cartGoodsDetailDto.setSkuName(skuProductBean.getProductName());
                                cartGoodsDetailDto.setOriginalPrice(skuProductBean.getOriginalPrice());

                                originalTotalAmount += skuProductBean.getOriginalPrice() * op.getQty();
                                totalAmount += skuProductBean.getFinalPrice() * op.getQty();
                                packageAmount += skuProductBean.getPackPrice() * op.getQty();

                                cartGoodsDetailDto.setStockLimit(skuProductBean.getStockLimit() == 1);
                                break;
                            }
                        }
                        cartGoodsDetailDto.setPicture(productBeanDTO.getPicture());
                        cartGoodsDetailDto.setQty(op.getQty());
                        cartGoodsDetailDto.setTotalDiscountAmount(0);
                        cartGoodsDetailDto.setHasProductCoupon(false);

                        cartGoodsDetailDto.setWeight(productBeanDTO.getWeight());
                        cartGoodsDetailDto.setSequence(sequence);
                        cartGoodsDetailDto.setUnit(productBeanDTO.getUnit());

                        List<ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra> extraList = new ArrayList<>();
                        if (CollectionUtils.isNotEmpty(op.getExtra())) {
                            for (OrderProductExtraVo orderProductExtraVo : op.getExtra()) {
                                ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra cartGoodsExtra = new ShoppingCartGoodsDto.CartGoodsDetailDto.CartGoodsExtra();
                                cartGoodsExtra.setAttributeId(orderProductExtraVo.getAttributeId());
                                cartGoodsExtra.setAttributeName(orderProductExtraVo.getAttributeName());
                                extraList.add(cartGoodsExtra);
                            }
                        }
                        cartGoodsDetailDto.setExtraList(extraList);
                        cartGoodsDetailDto.setActivityDiscountsDtos(null);
                        cartGoodsDetailDto.setComboProducts(null);
                        break;
                    }
                }
            }


            if (StringUtils.isNotBlank(cartGoodsDetailDto.getSpuId())) {
                products.add(cartGoodsDetailDto);
            }
        }

        shoppingCartGoodsDto.setProducts(products);


        shoppingCartGoodsDto.setOriginalTotalAmount(originalTotalAmount);
        shoppingCartGoodsDto.setTotalAmount(totalAmount);
//        shoppingCartGoodsDto.setTotalDiscountAmount(0L);
        //堂食无包装费
        if (reachStoreType != null && reachStoreType != 5) {
            shoppingCartGoodsDto.setPackageAmount(packageAmount);
        }
        //积分抵扣
        shoppingCartGoodsDto.setScoreReduceAmount(0L);
        shoppingCartGoodsDto.setReduceScore(0L);
//        shoppingCartGoodsDto.setMemberCardAmount(0);

        //结算页购买会员卡
        shoppingCartGoodsDto.setCardOriginalAmount(0);
        shoppingCartGoodsDto.setCardDiscountAmount(0);

        //活动优惠
        List<ActivityDiscountsDto> activityDiscountsDtos = new ArrayList<>();
        shoppingCartGoodsDto.setActivityDiscountsDtos(activityDiscountsDtos);

        //活动库存
        List<SubtractStockVO> stocks = new ArrayList<>();
        shoppingCartGoodsDto.setStocks(stocks);

        //收货地址获取
        shoppingCartGoodsDto.setDeliveryAmount(0L);
        //满额减配送费活动
        shoppingCartGoodsDto.setDiscountDeliveryAmount(0L);
//        shoppingCartGoodsDto.setThresholdAmount(0L);
//        shoppingCartGoodsDto.setDiscountDeliveryActivityCode(null);
        return shoppingCartGoodsDto;
    }


}
