package cn.freemud.service.impl;

import cn.freemud.amp.service.SendCouponService;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.base.util.DateUtil;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.Active;
import cn.freemud.entities.dto.BatchQueryActivityInfoRequestDto;
import cn.freemud.entities.dto.BatchQueryActivityInfoResponseDto;
import cn.freemud.entities.dto.delivery.WeixinDeliveryAddressDto;
import cn.freemud.entities.dto.product.pointsmall.*;
import cn.freemud.entities.dto.user.CustomerPropertyBaseResponse;
import cn.freemud.entities.dto.user.StatislScoreResponse;
import cn.freemud.entities.dto.user.StatisticalScoreRequestVo;
import cn.freemud.entities.dto.user.UseScoreRequest;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.ResponseResult;
import cn.freemud.enums.integralproduct.IntegralProductStatusEnum;
import cn.freemud.service.CouponService;
import cn.freemud.service.PointsMallOrderService;
import cn.freemud.service.thirdparty.CustomerPropertyClient;
import cn.freemud.service.thirdparty.PointMallProductClient;
import cn.freemud.utils.AppLogUtil;
import cn.freemud.utils.ResponseUtil;
import com.alibaba.fastjson.JSONObject;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.api.assortment.datamanager.manager.customer.AssortmentCustomerInfoManager;
import com.freemud.application.sdk.api.log.LogThreadLocal;
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.OrderType;
import com.freemud.application.sdk.api.ordercenter.request.OrderAffirmReq;
import com.freemud.application.sdk.api.ordercenter.request.OrderUserConditionsReq;
import com.freemud.application.sdk.api.ordercenter.request.PaySuccessReq;
import com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest;
import com.freemud.application.sdk.api.ordercenter.request.create.DeliveryContactInfoCreateReq;
import com.freemud.application.sdk.api.ordercenter.request.create.OrderItemCreateReq;
import com.freemud.application.sdk.api.ordercenter.request.create.OrderSettlementCreateReq;
import com.freemud.application.sdk.api.ordercenter.response.QueryOrderForUserResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.DeliveryContactInfoResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderItemResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.QueryByCodeResponse;
import com.freemud.application.sdk.api.ordercenter.service.OrderDownLoadSdkService;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
import com.freemud.sdk.api.assortment.order.request.order.OrderProductAddInfoDto;
import com.freemud.sdk.api.assortment.order.request.order.ProductBindingCouponType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class PointsMallOrderServiceImpl implements PointsMallOrderService {


    @Autowired
    private AssortmentCustomerInfoManager customerInfoManager;
    @Autowired
    private PointMallProductClient pointMallProductClient;
    @Autowired
    private OrderSdkService orderSdkService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private CustomerPropertyClient customerPropertyClient;
    @Autowired
    private SendCouponService sendCouponService;
    @Autowired
    private OrderDownLoadSdkService orderDownLoadSdkService;


    @Override
    public BaseResponse createOrder(CreateOrderVo createOrderVo) {
        String sessionId = createOrderVo.getSessionId();
        //查询会员信息
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(sessionId);
        if (userLoginInfoDto == null || StringUtils.isEmpty(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        String partnerId = userLoginInfoDto.getPartnerId();
        String storeId = "99999";
        String memberId = userLoginInfoDto.getMemberId();
        String appId = userLoginInfoDto.getAppId();
        String skuId = "";
        if (CollectionUtils.isNotEmpty(createOrderVo.getProducts())) {
            skuId = createOrderVo.getProducts().get(0).getSkuId();
        }
        //查询商品信息并且校验用户是否能购买　/product/listProductInfo　查询积分商品详情，可根据入参校验商品
        PointMallListProductInfoRequest productInfoRequest = new PointMallListProductInfoRequest();
        productInfoRequest.setPartnerId(partnerId);
        productInfoRequest.setMemberId(memberId);
        productInfoRequest.setProductIdList(Arrays.asList(skuId));
        productInfoRequest.setValidateMember(true);
        productInfoRequest.setValidateStock(true);
        productInfoRequest.setValidateTime(true);
        PointMallListProductInfoResponse<List<IntegralProductType>> productInfosDto = pointMallProductClient.listProductInfo(productInfoRequest);
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS, productInfosDto.getStatusCode()) || CollectionUtils.isEmpty(productInfosDto.getResult())) {
            return ResponseUtil.error(ResponseCodeConstant.RESPONSE_ERROR_STR, "商品异常");
        }
        if (productInfosDto.getResult().get(0).getStatus() != IntegralProductStatusEnum.STATUS_2.getCode()) {
            IntegralProductStatusEnum message = IntegralProductStatusEnum.getByCode(productInfosDto.getResult().get(0).getStatus());
            return ResponseUtil.error(ResponseCodeConstant.RESPONSE_ERROR_STR, message != null ? message.getDesc() : "商品异常");
        }
        IntegralProductType integralProductType = productInfosDto.getResult().get(0);
        if (!Objects.equals(1, integralProductType.getExchangeType())) {
            return ResponseUtil.error(ResponseCodeConstant.RESPONSE_ERROR_STR, "积分商城暂不支持现金兑换");
        }
//        integralProductType.setIntegralPrice(2);
//        integralProductType.setCashPrice(0);
//        integralProductType.setExchangeType(1);
        Integer points = integralProductType.getIntegralPrice();
        Integer exchangeType = integralProductType.getExchangeType();
        boolean isCoupon = integralProductType.getProductType() == 1;
        WeixinDeliveryAddressDto weixinDeliveryAddress = createOrderVo.getWeixinDeliveryAddress();
        if (!isCoupon && (weixinDeliveryAddress == null || StringUtils.isEmpty(weixinDeliveryAddress.getProvinceName()))) {
            return ResponseUtil.error(ResponseCodeConstant.RESPONSE_ERROR_STR, "收货地址异常");
        }
        Active active = null;
        if (isCoupon) {
            String activityCode = integralProductType.getCouponCode();
            //券商品查询券活动信息校验券有效　
            BatchQueryActivityInfoRequestDto queryActivityInfoRequestDto = new BatchQueryActivityInfoRequestDto();
            queryActivityInfoRequestDto.setActiveCode(Arrays.asList(activityCode));
//            queryActivityInfoRequestDto.setActiveCode(Arrays.asList("V1628760321931083"));
            queryActivityInfoRequestDto.setPartnerId(Integer.valueOf(partnerId));
            BatchQueryActivityInfoResponseDto batchQueryActivityInfoResponseDto = couponService.batchQueryActivityInfo(queryActivityInfoRequestDto);
            if (!Objects.equals("0", batchQueryActivityInfoResponseDto.getStatusCode())) {
                return ResponseUtil.error(batchQueryActivityInfoResponseDto.getStatusCode(), "优惠券异常");
            }
            active = batchQueryActivityInfoResponseDto.getActivities().get(0);
        }

        if (exchangeType != 2) {
            //查询积分信息
            StatisticalScoreRequestVo statisticalScoreRequest = new StatisticalScoreRequestVo();
            statisticalScoreRequest.setPartnerId(userLoginInfoDto.getPartnerId());
            statisticalScoreRequest.setMemberId(userLoginInfoDto.getMemberId());
            CustomerPropertyBaseResponse<StatislScoreResponse> statislScoreResponseBaseResponse = customerPropertyClient.statisticalScore(statisticalScoreRequest);
            if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, statislScoreResponseBaseResponse.getCode())) {
                return ResponseUtil.error(statislScoreResponseBaseResponse.getCode(), "查询积分异常");
            }
            if (statislScoreResponseBaseResponse.getData() != null && statislScoreResponseBaseResponse.getData().getCurrentScore() < points) {
                return ResponseUtil.error(statislScoreResponseBaseResponse.getCode(), "积分不足");
            }
        }
        //创建订单
        CreateOrderRequest createOrderRequest = convent2NEWCreateOrderRequest(OrderClientType.I_MEMBER.getIndex(), userLoginInfoDto,
                storeId, "", "", 4, integralProductType, skuId, active, weixinDeliveryAddress);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<OrderInfoReqs> createOrderResponseDto = orderSdkService.createOrder(createOrderRequest, "");
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, createOrderResponseDto.getCode())) {
            return ResponseUtil.error(createOrderResponseDto.getCode(), "创建订单异常");
        }
        String orderCode = createOrderResponseDto.getResult().getOrderCode();
        //扣减积分商品商品库存
        UpdatePointsMallStocksRequest updatePointsMallStocksRequest = new UpdatePointsMallStocksRequest();
        updatePointsMallStocksRequest.setPartnerId(partnerId);
        updatePointsMallStocksRequest.setMemberId(memberId);
        updatePointsMallStocksRequest.setChangeType(2);
        updatePointsMallStocksRequest.setRemark("积分商城兑换");
        updatePointsMallStocksRequest.setTransTime(DateUtil.convert2String(new Date(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        updatePointsMallStocksRequest.setTransNo(orderCode);
        ProductStockRequest productStockRequest = new ProductStockRequest();
        productStockRequest.setProductId(skuId);
        productStockRequest.setExchangeNumber(1);
        productStockRequest.setStockNumber(1);
        updatePointsMallStocksRequest.setProductStocks(Arrays.asList(productStockRequest));
        PointMallListProductInfoResponse pointMallListProductInfoResponse = pointMallProductClient.updateStock(updatePointsMallStocksRequest);
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS, pointMallListProductInfoResponse.getStatusCode())) {
            return ResponseUtil.error(pointMallListProductInfoResponse.getStatusCode().toString(), "扣减库存失败");
        }
        //扣减积分　（失败：失败冲正活动库存）
        if (exchangeType != 2) {
            UseScoreRequest userScoreRequest = new UseScoreRequest();
            userScoreRequest.setMemberId(memberId);
            userScoreRequest.setPartnerId(partnerId);
            userScoreRequest.setChangeScore(points);
            userScoreRequest.setOperationType(12);
            userScoreRequest.setOperationName("积分兑换");
            userScoreRequest.setChangeType(2);
            userScoreRequest.setOrderId(orderCode);
            userScoreRequest.setOrgCode("");
            userScoreRequest.setOrgType(1);
            userScoreRequest.setIdempotencyBussinessId(LogThreadLocal.getTrackingNo());
            userScoreRequest.setIdempotencyBussinessType("5");
            userScoreRequest.setAppId(userLoginInfoDto.getAppId());
            CustomerPropertyBaseResponse baseResponse = customerPropertyClient.useScore(userScoreRequest);
            if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, baseResponse.getCode())) {
                createOrderFail(true, false, partnerId, memberId, orderCode, skuId, points, appId);
                return ResponseUtil.error(baseResponse.getCode(), "扣减积分失败");
            }
        }
        //订单完成　（失败：失败冲正活动库存）
        String nickName = userLoginInfoDto.getNickName();
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse updateOrderStateResp = null;
        if (isCoupon) {
            OrderAffirmReq request = new OrderAffirmReq();
            request.setOrderCode(orderCode);
            request.setPayState(2);
            request.setOperator(nickName);
            updateOrderStateResp = orderSdkService.orderAffirm(request, LogThreadLocal.getTrackingNo());
            if (Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, updateOrderStateResp.getCode())) {
                //发券mq
                sendCouponService.sendCouponMq(createOrderResponseDto.getResult());
            }
        } else {
            PaySuccessReq request = new PaySuccessReq();
            request.setOrderCode(orderCode);
            request.setOperator(nickName);
            updateOrderStateResp = orderSdkService.paySuccess(request, LogThreadLocal.getTrackingNo());
        }
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, updateOrderStateResp.getCode())) {
            createOrderFail(false, true, partnerId, memberId, orderCode, skuId, points, appId);
            return ResponseUtil.error(updateOrderStateResp.getCode(), "创建订单异常");
        }
        CreateOrderResponseVo createOrderResponse = new CreateOrderResponseVo();
        createOrderResponse.setOid(orderCode);
        return ResponseUtil.success(createOrderResponse);
    }


    @Override
    public BaseResponse scoreRecords(QueryOrderVo queryOrderVo) {
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(queryOrderVo.getSessionId());
        if (userLoginInfoDto == null || StringUtils.isBlank(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        Date startDate;
        Date endDate;
        if (StringUtils.isBlank(queryOrderVo.getStartDate()) || StringUtils.isBlank(queryOrderVo.getEndDate())) {
            Date now = new Date();
            startDate = DateUtil.addMonths(now, -6);
            endDate = DateUtil.addDays(now, 1);
        } else {
            String startDateStr = queryOrderVo.getStartDate() + " 00:00:00";
            String endDateStr = queryOrderVo.getEndDate() + " 23:59:59";
            startDate = DateUtil.convert2Date(startDateStr, "yyyy-MM-dd HH:mm:ss");
            if (startDate == null) {
                return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "查询订单开始时间格式不正确");
            }
            endDate = DateUtil.convert2Date(endDateStr, "yyyy-MM-dd HH:mm:ss");
            if (endDate == null) {
                return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "查询订单结束时间格式不正确");
            }
        }
        OrderUserConditionsReq queryOrdersDto = new OrderUserConditionsReq();
        queryOrdersDto.setUserId(userLoginInfoDto.getMemberId());
        queryOrdersDto.setPartnerId(userLoginInfoDto.getPartnerId());
        queryOrdersDto.setPageSize(queryOrderVo.getPageSize() != null ? queryOrderVo.getPageSize() : 500);
        queryOrdersDto.setPageNum(queryOrderVo.getPageNumber() != null ? queryOrderVo.getPageNumber() : 1);
        queryOrdersDto.setStartTimestamp(startDate.getTime() / 1000);
        queryOrdersDto.setEndTimestamp(endDate.getTime() / 1000);
        queryOrdersDto.setOrderClients(Arrays.asList(OrderClientType.I_MEMBER.getIndex()));
        queryOrdersDto.setBizTypes(Arrays.asList(4));
        if (queryOrderVo.getQueryOrderStatus() != null) {
            if (queryOrderVo.getQueryOrderStatus() == 1) {
                queryOrdersDto.setOrderStatus(Arrays.asList(2));
            }
            if (queryOrderVo.getQueryOrderStatus() == 2) {
                queryOrdersDto.setOrderStatus(Arrays.asList(6));
            }
            if (queryOrderVo.getQueryOrderStatus() == 3) {
                queryOrdersDto.setOrderStatus(Arrays.asList(2, 6));
            }
        } else {
            queryOrdersDto.setOrderStatus(Arrays.asList(6));
        }
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<QueryOrderForUserResp> userorderResponse = orderSdkService.queryOrderForUser(queryOrdersDto, LogThreadLocal.getTrackingNo());
        if (null == userorderResponse || null == userorderResponse.getResult()) {
            return ResponseUtil.success();
        }
        List<ScoreRecordVo> result = new ArrayList<>();
        List<OrderInfoReqs> list = userorderResponse.getResult().getItemList();
        list.forEach(order -> {
            ScoreRecordVo responseVo = new ScoreRecordVo();
            responseVo.setOrderCode(order.getOrderCode());
            responseVo.setOrderStatus(order.getOrderState());
//            responseVo.setExpressChannelName(order.getExpressChannelName());
//            responseVo.setExpressChannelCode(order.getExpressChannelCode());
            if (order.getCreateTime() != null) {
                responseVo.setCreateTime(Long.parseLong(order.getCreateTime()));
            }
            boolean entityProduct = false;
            if (CollectionUtils.isNotEmpty(order.getOrderItemList())) {
                OrderItemResp orderItemResp = order.getOrderItemList().get(0);
                responseVo.setProductName(orderItemResp.getProductName());
                responseVo.setProductQuantity(orderItemResp.getProductQuantity());
                responseVo.setProductType(orderItemResp.getProductType());
                responseVo.setIntegralPrice(orderItemResp.getProductPrice().intValue());
                responseVo.setCashPrice(orderItemResp.getSalePrice().intValue());
                responseVo.setProductPicUrl(orderItemResp.getProductPicUrl());
                if (orderItemResp.getProductType() == 2) {
                    entityProduct = true;
                }
            }
            if (entityProduct && CollectionUtils.isNotEmpty(order.getDeliveryContactInfoList())) {
                DeliveryContactInfoResp deliveryContactInfoResp = order.getDeliveryContactInfoList().get(0);
                responseVo.setUserName(deliveryContactInfoResp.getContactsName());
                responseVo.setMobile(deliveryContactInfoResp.getMobile());
                responseVo.setAddressDetail(deliveryContactInfoResp.getAddressDetail());
            }
            result.add(responseVo);
        });
        PageInfo<ScoreRecordVo> pageInfo = new PageInfo<>();
        pageInfo.setList(result);
        pageInfo.setTotal(userorderResponse.getResult().getTotal());
        return ResponseUtil.success(pageInfo);
    }

    @Override
    public BaseResponse scoreRecordDetail(QueryOrderVo queryOrderVo) {
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(queryOrderVo.getSessionId());
        if (userLoginInfoDto == null || StringUtils.isBlank(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        if (StringUtils.isEmpty(queryOrderVo.getOid())) {
            return ResponseUtil.error(ResponseResult.PARAMETER_MISSING);
        }
        String orderCode = queryOrderVo.getOid();
        QueryByCodeResponse queryByCodeResponse = orderSdkService.getOrderInfo("", orderCode, "", null, LogThreadLocal.getTrackingNo());

        if (null == queryByCodeResponse || null == queryByCodeResponse.getResult()) {
            return ResponseUtil.success();
        }
        OrderInfoReqs order = queryByCodeResponse.getResult();
        ScoreRecordVo responseVo = new ScoreRecordVo();
        responseVo.setOrderCode(order.getOrderCode());
        responseVo.setOrderStatus(order.getOrderState());
        responseVo.setExpressChannelName(order.getExpressChannelName());
        responseVo.setExpressNo(order.getExpressNo());
        if (order.getCreateTime() != null) {
            responseVo.setCreateTime(Long.parseLong(order.getCreateTime()));
        }
        boolean entityProduct = false;
        if (CollectionUtils.isNotEmpty(order.getOrderItemList())) {
            OrderItemResp orderItemResp = order.getOrderItemList().get(0);
            responseVo.setProductName(orderItemResp.getProductName());
            responseVo.setProductQuantity(orderItemResp.getProductQuantity());
            responseVo.setProductType(orderItemResp.getProductType());
            responseVo.setIntegralPrice(orderItemResp.getProductPrice().intValue());
            responseVo.setCashPrice(orderItemResp.getSalePrice().intValue());
            responseVo.setProductPicUrl(orderItemResp.getProductPicUrl());
            if (orderItemResp.getProductType() == 2) {
                entityProduct = true;
            }
        }
        if (entityProduct && CollectionUtils.isNotEmpty(order.getDeliveryContactInfoList())) {
            DeliveryContactInfoResp deliveryContactInfoResp = order.getDeliveryContactInfoList().get(0);
            responseVo.setUserName(deliveryContactInfoResp.getContactsName());
            responseVo.setMobile(deliveryContactInfoResp.getMobile());
            String addressDetail = deliveryContactInfoResp.getProvince() + deliveryContactInfoResp.getCity() + deliveryContactInfoResp.getRegion() + deliveryContactInfoResp.getAddressDetail();
            responseVo.setAddressDetail(addressDetail);
        }
        return ResponseUtil.success(responseVo);
    }


    /**
     * 失败冲正
     */
    private void createOrderFail(boolean useScoreFail, boolean orderFail, String partnerId, String memberId, String orderCode,
                                 String skuId, Integer points, String appId) {
        try {
            //扣减积分失败冲正活动库存
            if (useScoreFail || orderFail) {
                //扣减积分商品商品库存
                UpdatePointsMallStocksRequest updatePointsMallStocksRequest = new UpdatePointsMallStocksRequest();
                updatePointsMallStocksRequest.setMemberId(memberId);
                updatePointsMallStocksRequest.setChangeType(2);
                updatePointsMallStocksRequest.setRemark("积分兑换");
                updatePointsMallStocksRequest.setTransTime(DateUtil.convert2String(new Date(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
                updatePointsMallStocksRequest.setTransNo(orderCode);
                ProductStockRequest productStockRequest = new ProductStockRequest();
                productStockRequest.setProductId(skuId);
                productStockRequest.setExchangeNumber(1);
                productStockRequest.setStockNumber(1);
                updatePointsMallStocksRequest.setProductStocks(Arrays.asList(productStockRequest));
                PointMallListProductInfoResponse pointMallListProductInfoResponse = pointMallProductClient.updateStock(updatePointsMallStocksRequest);
            }
            //确认订单或支付成功失败，冲正活动库存与积分
            if (orderFail) {
                UseScoreRequest userScoreRequest = new UseScoreRequest();
                userScoreRequest.setMemberId(memberId);
                userScoreRequest.setPartnerId(partnerId);
                userScoreRequest.setChangeScore(points);
                userScoreRequest.setOperationType(12);
                userScoreRequest.setOperationName("积分兑换");
                userScoreRequest.setChangeType(1);
                userScoreRequest.setOrderId(orderCode);
                userScoreRequest.setOrgCode("");
                userScoreRequest.setOrgType(1);
                userScoreRequest.setIdempotencyBussinessId(LogThreadLocal.getTrackingNo());
                userScoreRequest.setIdempotencyBussinessType("5");
                userScoreRequest.setAppId(appId);
                CustomerPropertyBaseResponse baseResponse = customerPropertyClient.useScore(userScoreRequest);
            }
        } catch (Exception e) {
            AppLogUtil.errorLog("createOrderFail_error", null, null, e);
        }
    }


    private ProductBindingCouponType convent2ProductBindingCouponType(Active active) {
        ProductBindingCouponType productBindingCouponType2 = new ProductBindingCouponType();
        productBindingCouponType2.setActivityCode(active.getActiveCode());
        productBindingCouponType2.setNum(1);
        productBindingCouponType2.setActivityName(active.getActiveName());
        return productBindingCouponType2;
    }

    private OrderItemCreateReq convent2OrderItemCreateReq(IntegralProductType productBean, String partnerId, String skuId,
                                                          Active active) {
        boolean isCoupon = productBean.getProductType() == 1;
        //积分价格
        Integer integralPrice = productBean.getIntegralPrice() == null ? 0 : productBean.getIntegralPrice();
        //现金价格（分）
        Integer cashPrice = productBean.getCashPrice() == null ? 0 : productBean.getCashPrice();
        Integer settlementAmount = integralPrice + cashPrice;
        OrderItemCreateReq orderItemCreateReq = new OrderItemCreateReq();
        orderItemCreateReq.setPartnerId(partnerId);
        orderItemCreateReq.setSalePrice(cashPrice.longValue());
        orderItemCreateReq.setProductPrice(integralPrice.longValue());
        orderItemCreateReq.setSettlementPrice(settlementAmount.longValue());
        orderItemCreateReq.setProductId(skuId);
        orderItemCreateReq.setProductSpec(skuId);
        orderItemCreateReq.setProductName(productBean.getProductName());
        orderItemCreateReq.setProductSpecName(productBean.getProductName());
        orderItemCreateReq.setProductType(productBean.getProductType());
        if (CollectionUtils.isNotEmpty(productBean.getPictureList())) {
            orderItemCreateReq.setProductPicUrl(productBean.getPictureList().get(0));
        }
        orderItemCreateReq.setProductSeq(1);
        if (productBean.getEntityProductInfo() != null) {
            orderItemCreateReq.setProductCode(productBean.getEntityProductInfo().getProductId());
            orderItemCreateReq.setThirdProductId(productBean.getEntityProductInfo().getProductId());
            orderItemCreateReq.setProductPicUrl(productBean.getEntityProductInfo().getPicture());
        }
        if (isCoupon) {
            //添加商品绑定的券
            OrderProductAddInfoDto orderProductAddInfoDto = new OrderProductAddInfoDto();
            List<ProductBindingCouponType> productBindingCoupons = new ArrayList<>();
            productBindingCoupons.add(convent2ProductBindingCouponType(active));
            orderProductAddInfoDto.setProductBindingCoupons(productBindingCoupons);
            orderItemCreateReq.setExtInfo(JSONObject.toJSONString(orderProductAddInfoDto));
        }
        orderItemCreateReq.setProductQuantity(1);
        return orderItemCreateReq;
    }

    private OrderSettlementCreateReq convent2OrderSettlementCreateReq(IntegralProductType productBean) {
        OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
        orderSettlementCreateReq.setNumber(productBean.getIntegralPrice());
        orderSettlementCreateReq.setProductSeq(1);
        orderSettlementCreateReq.setExternalObjectId("");
        //商家优惠
        orderSettlementCreateReq.setShopDiscountAmount(0L);
        //结算金额
        orderSettlementCreateReq.setSettlementAmount(productBean.getIntegralPrice().longValue());
        //是否线上 false:不是 true:是
        orderSettlementCreateReq.setIsOnline(true);
        orderSettlementCreateReq.setSettlementType(OrderSettlementType.POINTS.getIndex());
        return orderSettlementCreateReq;
    }

    private CreateOrderRequest convent2NEWCreateOrderRequest(Integer orderClient, AssortmentCustomerInfoVo userLoginInfoDto,
                                                             String shopId, String cardCode,
                                                             String channel, Integer bizType,
                                                             IntegralProductType productBean, String skuId,
                                                             Active active, WeixinDeliveryAddressDto weixinDeliveryAddress) {
        CreateOrderRequest request = new CreateOrderRequest();
        String partnerId = userLoginInfoDto.getPartnerId();
        request.setOrderClient(orderClient);
        request.setPartnerId(partnerId);
        request.setStoreId(shopId);
        request.setStoreName("虚拟门店");
        request.setThirdStoreId("");
        //买券虚拟订单  不管APP卖券还是平台，依旧保留传入6
        request.setBizType(bizType);
        //1:线上支付 2:线下支付
        request.setPayType(1);
        request.setUserId(userLoginInfoDto.getMemberId());
        request.setUserName(userLoginInfoDto.getNickName());
        request.setOrderState(1);
        request.setPayState(1);
        if (StringUtils.isNotBlank(cardCode)) {
            request.setPayChannel("10102");
            request.setPayChannelName("储值卡支付");
        }
        //积分价格
//        Integer integralPrice = productBean.getIntegralPrice() == null ? 0 : productBean.getIntegralPrice();
        //现金价格（分）
        Integer cashPrice = productBean.getCashPrice() == null ? 0 : productBean.getCashPrice();
//        Integer settlementAmount = integralPrice + cashPrice;
        //订单原始金额，单位分
        //用户在界面上看到的支付金额
        request.setSettlementAmount(cashPrice.longValue());
        //实际支付现金金额，扣除支付自生优惠，单位分`
        request.setActualPayAmount(cashPrice.longValue());
        request.setOriginalAmount(cashPrice.longValue());
        request.setOrderType(OrderType.GENERAL_DINE_IN.getIndex());
        //商品信息赋值
        OrderItemCreateReq orderItemCreateReq = convent2OrderItemCreateReq(productBean, partnerId, skuId, active);
        request.setOrderItemList(Arrays.asList(orderItemCreateReq));
        //积分优惠
        OrderSettlementCreateReq orderSettlementCreateReq = convent2OrderSettlementCreateReq(productBean);
        request.setOrderSettlementDetailList(Arrays.asList(orderSettlementCreateReq));
        //收货人信息转换
        List<DeliveryContactInfoCreateReq> deliveryContactInfoList = new ArrayList<>();
        DeliveryContactInfoCreateReq deliveryContactInfoCreateReq = new DeliveryContactInfoCreateReq();
        //地址类型 1:订单地址 2:售后单地址 3:配送员信息
        deliveryContactInfoCreateReq.setRelateObjectType(1);
        //联系方式类型 1:取件 2:收件
        deliveryContactInfoCreateReq.setInfoType(1);
        deliveryContactInfoCreateReq.setContactsName(userLoginInfoDto.getNickName());
        deliveryContactInfoCreateReq.setMobile(userLoginInfoDto.getMobile());
        deliveryContactInfoCreateReq.setLatitude(null);
        deliveryContactInfoCreateReq.setLongitude(null);
        deliveryContactInfoCreateReq.setAddressDetail(null);
        deliveryContactInfoCreateReq.setProvince(null);
        deliveryContactInfoCreateReq.setCity(null);
        deliveryContactInfoCreateReq.setRegion(null);
        if (weixinDeliveryAddress != null) {
            deliveryContactInfoCreateReq.setContactsName(weixinDeliveryAddress.getUserName());
            deliveryContactInfoCreateReq.setMobile(weixinDeliveryAddress.getTelNumber());
            deliveryContactInfoCreateReq.setProvince(weixinDeliveryAddress.getProvinceName());
            deliveryContactInfoCreateReq.setCity(weixinDeliveryAddress.getCityName());
            deliveryContactInfoCreateReq.setRegion(weixinDeliveryAddress.getCountyName());
            deliveryContactInfoCreateReq.setAddressDetail(weixinDeliveryAddress.getDetailInfo());
        }
        deliveryContactInfoList.add(deliveryContactInfoCreateReq);
        request.setDeliveryContactInfoList(deliveryContactInfoList);
        request.setOperator(userLoginInfoDto.getNickName());
        request.setAppId(userLoginInfoDto.getWxAppId());
        request.setPayChannel(channel);
        return request;

    }


}
