package cn.freemud.service.impl;

import cn.freemud.adapter.PointsMallOrderAdapter;
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.delivery.WeixinDeliveryAddressDto;
import cn.freemud.entities.dto.order.FacePayResponseDto;
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.StatisticalScoreRequestVo;
import cn.freemud.entities.dto.user.StatisticalScoreResponse;
import cn.freemud.entities.dto.user.UseScoreRequest;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.CouponActiveStateEnum;
import cn.freemud.enums.ChannelEnum;
import cn.freemud.enums.OrderBeanType;
import cn.freemud.enums.ResponseResult;
import cn.freemud.enums.integralproduct.ExchangeTypeEnum;
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.BeanUtil;
import cn.freemud.utils.ResponseUtil;
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.membercenter.request.ReturnScoreRequest;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.entities.v1.ProductBeanV1;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
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.UpdateOrderReq;
import com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest;
import com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderPayItemResp;
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.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.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@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;
    @Autowired
    private PointsMallOrderAdapter pointsMallOrderAdapter;


    @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 memberId = userLoginInfoDto.getMemberId();
        String openId = userLoginInfoDto.getOpenId();
        String appId = userLoginInfoDto.getAppId();
        String channel = createOrderVo.getChannel();
        String skuId = "";
        if (CollectionUtils.isNotEmpty(createOrderVo.getProducts())) {
            skuId = createOrderVo.getProducts().get(0).getSkuId();
        }

        //查询商品信息并且校验用户是否能购买　/product/listProductInfo　查询积分商品详情，可根据入参校验商品
        PointMallListProductInfoRequest productInfoRequest = pointsMallOrderAdapter.convent2PointMallListProductInfoRequest(partnerId, memberId, skuId);
        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);

        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, "收货地址异常");
        }
        String storeId = "99999";
        AssortmentOpenPlatformIappWxappStore wxAppStore = getPointProductPayStoreInfo(appId);
        if ((wxAppStore == null && !ExchangeTypeEnum.TYPE_1.getCode().equals(exchangeType))) {
            return ResponseUtil.error(ResponseCodeConstant.RESPONSE_ERROR_STR, "支付门店未配置");
        }
        if (wxAppStore != null) {
            storeId = wxAppStore.getStoreId();
        }
        Active active = null;
        if (isCoupon) {
            String activityCode = integralProductType.getCouponCode();

            BatchQueryActivityInfoRequestDto queryActivityInfoRequestDto = new BatchQueryActivityInfoRequestDto();
            queryActivityInfoRequestDto.setActiveCode(Arrays.asList(activityCode));
            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);
            Date couponValidEnd = getCouponValidEnd(active);
            //券商品查询券活动信息校验券有效
            //只有1和2能发，一般没有2
            List<Integer> canSendCoupon = Arrays.asList(CouponActiveStateEnum.STATE_1.getCode(),CouponActiveStateEnum.STATE_2.getCode());
            if(!canSendCoupon.contains(active.getState()) || couponValidEnd == null){
                return ResponseUtil.error(ResponseCodeConstant.RESPONSE_ERROR_STR, "优惠券异常");
            }
            //券已过期
            if(getCouponValidEnd(active).before(new Date())){
                return ResponseUtil.error(ResponseCodeConstant.RESPONSE_ERROR_STR, "优惠券已过期，无法兑换");
            }
        }

        if (!ExchangeTypeEnum.TYPE_2.getCode().equals(exchangeType)) {
            //查询积分信息
            StatisticalScoreRequestVo statisticalScoreRequest = new StatisticalScoreRequestVo();
            statisticalScoreRequest.setPartnerId(userLoginInfoDto.getPartnerId());
            statisticalScoreRequest.setMemberId(userLoginInfoDto.getMemberId());
            CustomerPropertyBaseResponse<StatisticalScoreResponse> statisticalScoreResponse = customerPropertyClient.statisticalScore(statisticalScoreRequest);
            if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, statisticalScoreResponse.getCode())) {
                return ResponseUtil.error(statisticalScoreResponse.getCode(), "查询积分异常");
            }
            if (statisticalScoreResponse.getData() != null && statisticalScoreResponse.getData().getCurrentScore() < points) {
                return ResponseUtil.error(statisticalScoreResponse.getCode(), "积分不足");
            }
        }
        //创建订单
        CreateOrderRequest createOrderRequest = pointsMallOrderAdapter.convent2NEWCreateOrderRequest(OrderClientType.I_MEMBER.getIndex(), userLoginInfoDto,
                storeId, "", "", 4, integralProductType, skuId, active, weixinDeliveryAddress);
        OrderBaseResp<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();
        createOrderResponseVo.setOid(orderCode);
        //线上现金支付，创建预支付订单，唤起支付
        com.freemud.application.sdk.api.base.BaseResponse<FacePayResponseDto> response = null;
        if (!Objects.equals(ExchangeTypeEnum.TYPE_1.getCode(), exchangeType) && cashPrice != null && cashPrice > 0) {
            Long payClientCode = Long.parseLong(wxAppStore.getClientCode());
            UnifiedOrderRequestDto requestDto = pointsMallOrderAdapter.convert2UnifiedOrderRequestDto(result, openId, cashPrice,
                    payClientCode, reverseNotifyiDcUrl, getPartnerPayOvertime(partnerId));
            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());
            }
            //唤起支付返回参数
            pointsMallOrderAdapter.convent2CreateOrderResponseVo(createOrderResponseVo, appId, response.getData());
        }
        //保存支付信息
        BaseResponse baseResponse1 = updateOrder(orderCode, points, cashPrice, partnerId, storeId, createOrderResponseVo.getFmId(), channel);
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, baseResponse1.getCode())) {
            return ResponseUtil.error(createOrderResponseDto.getCode(), "更新订单异常");
        }
        //扣减积分商品商品库存
        UpdatePointsMallStocksRequest updatePointsMallStocksRequest = pointsMallOrderAdapter.convent2UpdatePointsMallStocksRequest(partnerId, memberId, skuId, orderCode);
        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 = pointsMallOrderAdapter.convent2UseScoreRequest(partnerId, memberId, appId, orderCode, points);
            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 (ExchangeTypeEnum.TYPE_1.getCode().equals(exchangeType)) {
            BaseResponse response1 = orderPaySuccess(createOrderResponseDto.getResult(), points, false);
            if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, response1.getCode())) {
                return response1;
            }
        }
        return ResponseUtil.success(createOrderResponseVo);
    }

    private BaseResponse updateOrder(String orderCode, Integer integralPrice, Integer cashPrice, String partnerId,
                                     String shopId, String fmId, String channel) {
        BaseResponse response = new BaseResponse();
        if (integralPrice > 0 || cashPrice > 0) {
            List<OrderPayItemResp> orderPayItemList = new ArrayList<>();
            if (integralPrice > 0) {
                OrderPayItemResp payItem = new OrderPayItemResp();
                payItem.setPartnerId(partnerId);
                payItem.setStoreId(shopId);
                payItem.setPayChannelType(PayChannelType.POINTS.getIndex().intValue());
                payItem.setPayChannelName(PayChannelType.POINTS.getName());
                payItem.setPayAmount(new BigDecimal(integralPrice));
                orderPayItemList.add(payItem);
            }
            if (cashPrice > 0) {
                OrderPayItemResp payItem = new OrderPayItemResp();
                payItem.setPartnerId(partnerId);
                payItem.setStoreId(shopId);
                if (ChannelEnum.TYPE_1.getCode().equals(channel)) {
                    payItem.setPayChannelType(PayChannelType.WECHAT.getIndex().intValue());
                    payItem.setPayChannelName(PayChannelType.WECHAT.getName());
                } else if (ChannelEnum.TYPE_5.getCode().equals(channel)) {
                    payItem.setPayChannelType(PayChannelType.TIKTOKPAY.getIndex().intValue());
                    payItem.setPayChannelName(PayChannelType.TIKTOKPAY.getName());
                } else {
                    payItem.setPayChannelType(PayChannelType.ALIPAY.getIndex().intValue());
                    payItem.setPayChannelName(PayChannelType.ALIPAY.getName());
                }
                payItem.setPayAmount(new BigDecimal(cashPrice));
                payItem.setFmTradeNo(fmId);
                orderPayItemList.add(payItem);
            }
            UpdateOrderReq request = new UpdateOrderReq();
            request.setOrderCode(orderCode);
//        request.setExtInfo(orderEdit.getExtInfo());
            request.setOrderPayItem(orderPayItemList);
//        request.setPayChannel(orderEdit.getPayChannel());
//        request.setPayChannelName(orderEdit.getPayChannelName());
//        request.setPayChannelType(orderEdit.getPayChannelType());
            OrderBaseResp baseResponse = orderSdkService.editOrder(request, LogThreadLocal.getTrackingNo());
            if (baseResponse != null) {
                response.setCode(baseResponse.getCode());
                response.setMessage(baseResponse.getMessage());
            }
        }
        return response;
    }


    @Override
    public String paySuccessCallback(PaysuccessNoticeMessage message, Map<String, OrderBeanV1> orderBeans) {
        OrderBeanV1 orderBean = orderBeans.get(OrderBeanType.SAASORDER.getCode());
        OrderInfoReqs orderInfo = new OrderInfoReqs();
        orderInfo.setUserName(orderBean.getUserName());
        orderInfo.setOrderCode(orderBean.getOid());
        orderInfo.setPartnerId(orderBean.getCompanyId());
        orderInfo.setUserId(orderBean.getUserId());
        orderInfo.setOrderPayItemCreateReqList(orderBean.getOrderPayItem());
        orderInfo.setAppId(orderBean.getAppId());
        orderInfo.setBizType(orderBean.getBizType());
        List<OrderItemResp> orderItemList = new ArrayList<>();
        for (ProductBeanV1 productBean : orderBean.getProductList()) {
            OrderItemResp orderItemResp = new OrderItemResp();
            BeanUtil.convertBean(productBean, orderItemResp);
            orderItemList.add(orderItemResp);
        }
        orderInfo.setOrderItemList(orderItemList);
        BaseResponse baseResponse = orderPaySuccess(orderInfo, 0, true);
        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, -2);
            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));
        }
        OrderBaseResp<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 -> {
            if (order != null){
                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.setPartnerId(partnerId);
                updatePointsMallStocksRequest.setMemberId(memberId);
                updatePointsMallStocksRequest.setChangeType(1);
                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) {
                ReturnScoreRequest userScoreRequest = new ReturnScoreRequest();
                userScoreRequest.setMemberId(memberId);
                userScoreRequest.setPartnerId(partnerId);
                userScoreRequest.setOperationType(1);
                userScoreRequest.setOrderId(orderCode);
                CustomerPropertyBaseResponse baseResponse = customerPropertyClient.returnScore(userScoreRequest);
            }
        } catch (Exception e) {
            AppLogUtil.errorLog("createOrderFail_error", null, null, e);
        }
    }


    /**
     * 获取商户支付超时时间
     *
     * @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);
//        String clientCode = wxAppStore != null && StringUtils.isNotBlank(wxAppStore.getClientCode()) ? wxAppStore.getClientCode() : "0";
//        return Long.parseLong(clientCode);
//    }


    /**
     * 获取门店支付信息
     */
    private AssortmentOpenPlatformIappWxappStore getPointProductPayStoreInfo(String wxAppId) {
        AssortmentOpenPlatformIappWxappStore wxAppStore = assortmentOpenPlatformIappWxappStoreManager.selectIappWxappStoreByWxAppIdAndAggregationType(wxAppId, "9");
        return wxAppStore;
    }


    //共用支付成功方法
    private BaseResponse orderPaySuccess(OrderInfoReqs orderInfo, Integer points, Boolean isCash) {
        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;
        String appId = orderInfo.getAppId();

//        //扣减积分　(失败：失败冲正活动库存)
//        if (!isCash && points != null && points > 0) {
//            UseScoreRequest userScoreRequest = pointsMallOrderAdapter.convent2UseScoreRequest(partnerId, memberId, appId, orderCode, points);
//            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(), "扣减积分失败");
//            }
//        }

        //订单完成　(失败：失败冲正活动库存)
        OrderBaseResp 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(), "更新订单异常");
        }
//        //有现金支付,扣减积分
//        if (isCash && CollectionUtils.isNotEmpty(orderInfo.getOrderPayItemCreateReqList())) {
//            List<OrderPayItemResp> collect = orderInfo.getOrderPayItemCreateReqList().stream().filter(orderPayItemResp ->
//                    orderPayItemResp.getPayChannelType().equals(PayChannelType.POINTS.getIndex().intValue())).collect(Collectors.toList());
//            if (CollectionUtils.isNotEmpty(collect)) {
//                points = collect.get(0).getPayAmount().intValue();
//                UseScoreRequest userScoreRequest = pointsMallOrderAdapter.convent2UseScoreRequest(partnerId, memberId, appId, orderCode, points);
//                CustomerPropertyBaseResponse baseResponse = customerPropertyClient.useScore(userScoreRequest);
//                if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, baseResponse.getCode())) {
//                    return ResponseUtil.error(baseResponse.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);
    }

    /**
     * 获取券的有效结束时间
     */
    private Date getCouponValidEnd(Active activeInfo){
        Date returnDate = null;
        if (activeInfo.getEffective() != null && activeInfo.getEffective() > 0) { // 根据固定时长来计算 天来计算
            int delayTimes = activeInfo.getFromDayEffective() != null ? activeInfo.getFromDayEffective() : 0;
            int validityPeriod = activeInfo.getEffective() != null ? activeInfo.getEffective() : 1;
            if (activeInfo.getEffectiveStart() != null && activeInfo.getEffectiveEnd() != null) {
                // 有效期为0  默认传1天，做兼容处理
                Date effectiveStart = activeInfo.getEffectiveStart();
                Date effectiveEnd = activeInfo.getEffectiveEnd();
                Date date = new Date();
                Date startDate = cn.freemud.base.util.DateUtil.addDays(date, delayTimes);
                Date endDate = cn.freemud.base.util.DateUtil.addDays(date, (delayTimes + validityPeriod));
                if (startDate.before(effectiveStart)) {
                    startDate = effectiveStart;
                }
                if (endDate.after(effectiveEnd)) {
                    endDate = effectiveEnd;
                }
                returnDate = endDate;
            } else {
                // 有效期为0  默认传1天，做兼容处理
                returnDate = DateUtil.addDays(new Date(), (delayTimes + validityPeriod - 1));
            }
        } else {
            returnDate = activeInfo.getEffectiveEndTime();
        }
        return returnDate;
    }


}
