package cn.freemud.service.impl;

import cn.freemud.adapter.OrderAdapter;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.base.log.LogTreadLocal;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.dto.ConfirmOrderDto;
import cn.freemud.entities.dto.QueryOrdersResponseDto;
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.vo.*;
import cn.freemud.enums.*;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.redis.RedisCache;
import cn.freemud.service.AppOrderService;
import cn.freemud.utils.BeanUtil;
import cn.freemud.utils.RedisUtil;
import cn.freemud.utils.ResponseUtil;
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.enums.AfterSalesType;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
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.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.QueryOrdersResponse;
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;

    //门店SDK
    @Autowired
    private StoreCenterService storeCenterService;

    /**
     * 不支持会员卡
     */
    @Override
    public BaseResponse createOrderFlow(CreateOrderVo createOrderVo) {
        String trackingNo = LogThreadLocal.getTrackingNo();
        // 查询用户信息
        AssortmentCustomerInfoVo userLoginInfoDto = checkOrder.checkOrderByMember(createOrderVo, trackingNo);
        // 查询门店信息 营业时间、营业状态，服务器当前时间在营业时间内 点餐桌号
        StoreResponse.BizVO storeResponseDto = checkOrder.checkOrderByStore(createOrderVo, trackingNo);
        // 查询购物车（内部校验券点餐方式，券是否可用） 校验当前订单类型的下单参数
        ShoppingCartGoodsDto shoppingCartGoodsDto = checkOrder.getShoppingCartGoodsDto(createOrderVo);
        // 查询小程序自提外卖配置信息 校验当前订单类型的下单参数 校验外卖是否满足起送条件
        Integer pushOrderTime = checkOrder.checkOrderByOrderType(createOrderVo, userLoginInfoDto, storeResponseDto, shoppingCartGoodsDto, trackingNo);
        //1.5.4版本，商品库存校验与扣库存
        //List<String> stockProductIds = checkOrder.getStockProductIdList(createOrderVo, shoppingCartGoodsDto);
        OrderExtInfoDto extInfo = orderservice.getExtInfo(userLoginInfoDto, storeResponseDto, pushOrderTime, createOrderVo);
        //创建订单
        BaseResponse createOrderOperateDtoResponse = orderservice.sdkCreateOrder(createOrderVo, storeResponseDto, shoppingCartGoodsDto, userLoginInfoDto);
        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());
        QueryOrdersResponse.DataBean.OrderBean 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(), 30L, TimeUnit.MINUTES);
        return orderservice.createPrepayOrder(createPrepayRequestDto);
    }

    /**
     * APP下单，下单带商品信息，不经过购物车服务，不唤起支付
     */
    @Override
    public BaseResponse createOrder(AppCreateOrderVo createOrderReq,AssortmentCustomerInfoVo customerInfo) {
        String trackingNo = LogThreadLocal.getTrackingNo();
        String partnerId = createOrderReq.getPartnerId();
        String shopId = createOrderReq.getShopId();
        // 获取门店信息
        StoreInfoRequest storeInfoRequest = new StoreInfoRequest(partnerId, shopId,null);
        StoreResponse storeResponse = storeCenterService.getStoreInfo(storeInfoRequest, trackingNo);
        if (storeResponse == null || storeResponse.getBizVO() == null) {
            throw new ServiceException(ResponseResult.STORE_NOT_FOUND);
        }
        // 查询门店信息 营业时间、营业状态，服务器当前时间在营业时间内 点餐桌号
        checkOrder.checkOrderByStore(storeResponse.getBizVO());
        // 查商品服务确定金额
        ShoppingCartGoodsDto shoppingCartGoodsDto = checkOrderProduct(partnerId,shopId,createOrderReq.getOrderProducts(),
                createOrderReq.getMenuType(),createOrderReq.getReachStoreType());
        CreateOrderVo createOrderVo = new CreateOrderVo();
        BeanUtil.convertBean(createOrderReq,createOrderVo);
        createOrderVo.setStoreName(storeResponse.getBizVO().getStoreName());
        // 查询小程序自提外卖配置信息 校验当前订单类型的下单参数 校验外卖是否满足起送条件
        Integer pushOrderTime = checkOrder.checkOrderByOrderType(createOrderVo, customerInfo, storeResponse.getBizVO(), shoppingCartGoodsDto, trackingNo);
        //1.5.4版本，商品库存校验与扣库存
        //List<String> stockProductIds = checkOrder.getStockProductIdList(createOrderVo, shoppingCartGoodsDto);
        OrderExtInfoDto extInfo = orderservice.getExtInfo(customerInfo, storeResponse.getBizVO(), pushOrderTime, createOrderVo);
        //创建订单
        BaseResponse createOrderOperateDtoResponse = orderservice.sdkCreateOrder(createOrderVo, storeResponse.getBizVO(), shoppingCartGoodsDto, customerInfo);
        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 String paySuccessCallback(PaysuccessNoticeMessage message, ConfirmOrderDto confirmOrderDto, Map<String, QueryOrdersResponseDto.DataBean.OrderBean> 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, QueryOrdersResponse.DataBean.OrderBean 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);
        }

        OrderExtInfoDto extInfo = JSONObject.parseObject(orderBean.getExtInfo(), OrderExtInfoDto.class);
        if(extInfo == null || StringUtils.isBlank(extInfo.getSessionId()) || !extInfo.getSessionId().equals(createPrepayVo.getSessionId())) {
            throw new ServiceException(ResponseResult.ORDER_OWNER_ERROR);
        }
    }

    /**
     * 更新订单扩展信息 
     */
    private BaseResponse updateOrderExtInfo(QueryOrdersResponse.DataBean.OrderBean 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(LogTreadLocal.getTrackingNo());
        QueryRelatedOrderByCodeResp queryOrderByIdResponse = orderCenterSdkService.queryRelatedOrderByCode(baseQueryOrderRequest);
        if(queryOrderByIdResponse == null || CollectionUtils.isEmpty(queryOrderByIdResponse.getOrderBeanList())) {
            throw new ServiceException(ResponseResult.ORDER_QUERYORDER_ERROR);
        }
        List<QueryOrdersResponse.DataBean.OrderBean> orderBeanList = queryOrderByIdResponse.getOrderBeanList();
        long totalAmount = 0;
        QueryOrdersResponse.DataBean.OrderBean fatherBeanListOne = new QueryOrdersResponse.DataBean.OrderBean();
        QueryOrdersResponse.DataBean.OrderBean productBeanListOne = new QueryOrdersResponse.DataBean.OrderBean();
        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(QueryOrdersResponse.DataBean.OrderBean::getAmount).count();
        }

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

        private void closeHistoryPrePay(QueryOrdersResponse.DataBean.OrderBean 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;
    }


}
