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.RedisKeyConstant;
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.ConfirmOrderDto;
import cn.freemud.entities.dto.QueryOrdersResponseDto;
import cn.freemud.entities.dto.delivery.WeixinDeliveryAddressDto;
import cn.freemud.entities.dto.order.FacePayResponseDto;
import cn.freemud.entities.dto.pay.PayOrderDto;
import cn.freemud.entities.dto.pay.PayProductDto;
import cn.freemud.entities.dto.pay.UnifiedOrderRequestDto;
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.PaymentNewClient;
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.db.AssortmentOpenPlatformIappWxappStore;
import com.freemud.api.assortment.datamanager.entity.db.AssortmentOpenPlatformPartnerConfig;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.api.assortment.datamanager.manager.AssortmentOpenPlatformIappWxappStoreManager;
import com.freemud.api.assortment.datamanager.manager.AssortmentOpenPlatformPartnerConfigManager;
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.enums.PayChannelType;
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 com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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;
    @Autowired
    private PaymentNewClient paymentNewClient;
    @Autowired
    private AssortmentOpenPlatformPartnerConfigManager openPlatformPartnerConfigManager;
    @Autowired
    private AssortmentOpenPlatformIappWxappStoreManager assortmentOpenPlatformIappWxappStoreManager;


    @Value("${saas.reverseNotifyiDcUrl}")
    private String reverseNotifyiDcUrl;


    @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 openId = userLoginInfoDto.getOpenId();
        String appId = userLoginInfoDto.getAppId();
        String skuId = "";
        if (CollectionUtils.isNotEmpty(createOrderVo.getProducts())) {
            skuId = createOrderVo.getProducts().get(0).getSkuId();
        }
        String clientCode = "";
        String storeId = getPiontProductPayStoreId(appId,clientCode);
        //查询商品信息并且校验用户是否能购买　/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, "积分商城暂不支持现金兑换");
//        }
        Integer points = integralProductType.getIntegralPrice();
        Integer cashPrice = integralProductType.getCashPrice();
        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(), "创建订单异常");
        }
        OrderInfoReqs result = createOrderResponseDto.getResult();
        String orderCode = result.getOrderCode();

        CreateOrderResponseVo createOrderResponseVo = new CreateOrderResponseVo();
        //线上现金支付，创建预支付订单，唤起支付
        com.freemud.application.sdk.api.base.BaseResponse<FacePayResponseDto> response = null;
        if (!Objects.equals(1, exchangeType) && cashPrice != null && cashPrice > 0) {
            UnifiedOrderRequestDto requestDto = convert2UnifiedOrderRequestDto(result,openId,cashPrice);
            response = paymentNewClient.unifiedOrder(requestDto);
            if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, response.getCode())) {
                return ResponseUtil.error(createOrderResponseDto.getCode(), "支付异常");
            }
            if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS, response.getData().getResultCode())) {
                return ResponseUtil.error(createOrderResponseDto.getCode(), "支付异常," + response.getData().getResultMsg());
            }
            createOrderResponseVo.setOid(orderCode);
            createOrderResponseVo.setWxappId(result.getAppId());
            createOrderResponseVo.setFmId(response.getData().getFmId());
            String payOrderDto = response.getData().getPayOrder();
            PayOrderDto payOrder = JSONObject.parseObject(payOrderDto,PayOrderDto.class);
            if(payOrder != null){
                createOrderResponseVo.setTimestamp(payOrder.getTimestamp());
                createOrderResponseVo.setNonceStr(payOrder.getNonceStr());
                createOrderResponseVo.setPackageX(payOrder.getPackageX());
                createOrderResponseVo.setSignType(payOrder.getSignType());
                createOrderResponseVo.setSign(payOrder.getSign());
                createOrderResponseVo.setOrderStr(payOrder.getAliPayOrder());
            }
        }

        //扣减积分商品商品库存
        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 (points != null && points > 0 ) {
            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(), "扣减积分失败");
            }
        }
        if(exchangeType == 1){
            BaseResponse baseResponse = orderPaySuccess(createOrderResponseDto.getResult());
            if(!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, baseResponse.getCode())){
                return baseResponse;
            }
            createOrderResponseVo.setOid(orderCode);
        }
        return ResponseUtil.success(createOrderResponseVo);
    }

    @Override
    public String paySuccessCallback(PaysuccessNoticeMessage message,OrderInfoReqs orderInfo) {
        BaseResponse baseResponse = orderPaySuccess(orderInfo);
        if(!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, baseResponse.getCode())){
            return refundFaileMessage(baseResponse.getMessage());
        }
        return newSendPaySuccessNoticeMessage();
    }


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

    }



    /**
     * 预支付接口获取类型
     *
     * @return
     */
    private String getFoodOrderType(Integer orderType) {
        //1=外卖 4=自提，5=堂食
        //qr_order（店内扫码点餐）,pre_order（预点到店自提）,home_delivery （外送到家）
        String foodOrderType;
        switch (orderType) {
            case 1:
                foodOrderType = "home_delivery";
                break;
            case 4:
                foodOrderType = "pre_order";
                break;
            case 5:
            default:
                foodOrderType = "qr_order";
                break;
        }
        return foodOrderType;
    }

    /**
     * 获取商户支付超时时间
     *
     * @param partnerId 商户Id
     * @return 超时时间
     */
    private String getPartnerPayOvertime(String partnerId) {
        return Optional.ofNullable(openPlatformPartnerConfigManager.selectPartnerConfigByPartnerKey(partnerId, RedisKeyConstant.PARTNER_PAY_OVERTIME))
                .orElseGet(() -> {
                    AssortmentOpenPlatformPartnerConfig config = new AssortmentOpenPlatformPartnerConfig();
                    config.setPartnerValue("30");
                    openPlatformPartnerConfigManager.addPartnerConfig(partnerId, RedisKeyConstant.PARTNER_PAY_OVERTIME, config);
                    return config;
                }).getPartnerValue();
    }


    private Long getPayClientCode(String wxAppId, String storeId, String payCode,String orderClient){
        //抖音支付的payCode = 10066
        if (Objects.equals(OrderClientType.TIKTOKPAY.getIndex().toString(),orderClient)) {
            payCode = PayChannelType.TIKTOKPAY.getEbcode();
        }

        AssortmentOpenPlatformIappWxappStore wxAppStore = assortmentOpenPlatformIappWxappStoreManager.selectWxappStoreByWxAppIdAndStoreId(wxAppId, storeId,payCode);

        payCode = wxAppStore != null && StringUtils.isNotBlank(wxAppStore.getPayCode())?wxAppStore.getPayCode():null;
        String clientCode = wxAppStore != null && StringUtils.isNotBlank(wxAppStore.getClientCode()) ? wxAppStore.getClientCode() : "0";

        return Long.parseLong(clientCode);
    }


    private String getPiontProductPayStoreId(String wxAppId,String clientCode){

        AssortmentOpenPlatformIappWxappStore wxAppStore = assortmentOpenPlatformIappWxappStoreManager.selectIappWxappStoreByWxAppIdAndAggregationType(wxAppId, "9");

        String storeId = wxAppStore != null && StringUtils.isNotBlank(wxAppStore.getStoreId())?wxAppStore.getStoreId():null;
        clientCode = wxAppStore != null && StringUtils.isNotBlank(wxAppStore.getClientCode()) ? wxAppStore.getClientCode() : "0";

        return storeId;
    }


    private UnifiedOrderRequestDto convert2UnifiedOrderRequestDto(OrderInfoReqs orderInfo,String openId, Integer cashPrice){

        String partnerId = orderInfo.getPartnerId();
        String storeId = orderInfo.getStoreId();
        String appId = orderInfo.getAppId();

        //现金支付唤起线上支付
        UnifiedOrderRequestDto requestDto = new UnifiedOrderRequestDto();
        requestDto.setTransId(orderInfo.getOrderCode());
        requestDto.setPartnerId(partnerId);
        requestDto.setStoreId(storeId);
        requestDto.setAmount(cashPrice.longValue());

        String businessDate = DateUtil.convert2String(new Date(), "yyyyMMdd");
        requestDto.setBusinessDate(businessDate);
        requestDto.setClientCode(getPayClientCode(appId,storeId,null,null));
        requestDto.setFoodOrderType(getFoodOrderType(1));
        requestDto.setNotifyUrl(reverseNotifyiDcUrl);
        requestDto.setOpenId(openId);
        requestDto.setPayTimeOutTime(getPartnerPayOvertime(partnerId));
        List<PayProductDto> productBeans = new ArrayList<>();
        String payProductName ="";
        if (CollectionUtils.isNotEmpty(orderInfo.getOrderItemList())) {

            for (OrderItemResp orderProductBean : orderInfo.getOrderItemList()){
                PayProductDto productBean = new PayProductDto();
                productBean.setId(orderProductBean.getProductId());
                productBean.setQuantity(orderProductBean.getProductQuantity());
//                productBean.setSeq(orderProductBean.getProductSeq());
//                productBean.setSalesType("NORMAL");
                productBean.setPrice(orderProductBean.getProductPrice().longValue());
                if(StringUtils.isNotBlank(payProductName)){
                    payProductName = orderProductBean.getProductName();
                }else if(payProductName.endsWith("...")){
                    //不处理
                }else {
                    payProductName = payProductName + "...";
                }
                productBean.setName(orderProductBean.getProductName());
                productBeans.add(productBean);
            }
        }
        requestDto.setBody(payProductName);
        return requestDto;
    }


    private BaseResponse orderPaySuccess(OrderInfoReqs orderInfo){
        String nickName= orderInfo.getUserName();
        String orderCode = orderInfo.getOrderCode();
        String partnerId =orderInfo.getPartnerId();
        String memberId = orderInfo.getUserId();
        String skuId = orderInfo.getOrderItemList().get(0).getProductId();
        boolean isCoupon = orderInfo.getOrderItemList().get(0).getProductType() == 1;
        Integer points = orderInfo.getOrderPayItemCreateReqList().get(0).getPayAmount().intValue();
        String appId =orderInfo.getAppId();
        //订单完成　（失败：失败冲正活动库存）
        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(orderInfo);
            }
        } 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(), "更新订单异常");
        }
        return ResponseUtil.success();
    }

    /**
     * 支付后通知确认返回信息
     */
    public String newSendPaySuccessNoticeMessage() {
        Map<String, Object> map = Maps.newTreeMap();
        map.put("code", 100);
        map.put("message", "success");
        Gson gson = new Gson();
        return gson.toJson(map);
    }

    /**
     * 退款中回调失败返回信息
     */
    public String refundFaileMessage(String errorMes) {
        Map<String, Object> map = Maps.newTreeMap();
        map.put("code", 102);
        map.put("message", "failed:" + errorMes);
        Gson gson = new Gson();
        return gson.toJson(map);
    }

}
