package cn.freemud.service.impl;

import cn.freemud.adapter.CreateOrderAdapter;
import cn.freemud.adapter.LightApplicationConvertToAssortmentSdkAdapter;
import cn.freemud.adapter.OrderAdapter;
import cn.freemud.amp.service.SendCouponService;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.base.util.DateUtil;
import cn.freemud.constant.CommonRedisKeyConstant;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.Active;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.order.CreatePrepayRequestDto;
import cn.freemud.entities.dto.product.GetValidateProductInfoDto;
import cn.freemud.entities.dto.product.ProductInfo;
import cn.freemud.entities.dto.product.ValidateProductInfosDto;
import cn.freemud.entities.dto.promotion.CalculationDiscountGoodsDto;
import cn.freemud.entities.dto.promotion.CalculationDiscountRequestDto;
import cn.freemud.entities.vo.CreateOrderVo;
import cn.freemud.entities.vo.NgsSellCouponCreateOrderVo;
import cn.freemud.entities.vo.PaysuccessNoticeMessage;
import cn.freemud.entities.vo.SellCouponCreateOrderVo;
import cn.freemud.enums.*;
import cn.freemud.enums.integralproduct.IntegralProductStatusEnum;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.manager.BuyProductOnceManager;
import cn.freemud.redis.RedisCache;
import cn.freemud.service.CouponService;
import cn.freemud.service.OrderFactoryService;
import cn.freemud.service.business.OrderBusinessService;
import cn.freemud.service.thirdparty.PromotionDiscountClient;
import cn.freemud.service.thirdparty.StoreItemClient;
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.vo.AssortmentCustomerInfoVo;
import com.freemud.application.sdk.api.base.SDKCommonBaseContextWare;
import com.freemud.application.sdk.api.constant.ResponseResultEnum;
import com.freemud.application.sdk.api.couponcenter.online.domain.ActiveDetailVO;
import com.freemud.application.sdk.api.couponcenter.online.domain.AppKeyVO;
import com.freemud.application.sdk.api.couponcenter.online.request.ActiveBatchQueryRequest;
import com.freemud.application.sdk.api.couponcenter.online.request.PartnerRequest;
import com.freemud.application.sdk.api.couponcenter.online.service.FMActiveSdkService;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.log.ThirdPartyLog;
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.OrderType;
import com.freemud.application.sdk.api.ordercenter.enums.*;
import com.freemud.application.sdk.api.ordercenter.request.OrderChangeStateReq;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest;
import com.freemud.application.sdk.api.ordercenter.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.OrderBaseResp;
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.service.OrderSdkService;
import com.freemud.application.sdk.api.productcenter.request.product.GetProductInfoRequest;
import com.freemud.application.sdk.api.productcenter.response.menu.GetMenuCategoryInfoResponse;
import com.freemud.application.sdk.api.productcenter.response.product.GetProductInfosResponse;
import com.freemud.application.sdk.api.productcenter.service.MenuService;
import com.freemud.application.sdk.api.promotioncenter.request.promotion.ActivityUpdateStockRequest;
import com.freemud.application.sdk.api.promotioncenter.response.PromotionResponseDTO;
import com.freemud.application.sdk.api.stockapi.request.UpdateStocksRequest;
import com.freemud.application.sdk.api.stockapi.service.StockSdkService;
import com.freemud.application.sdk.api.storecenter.request.StoreInfoRequest;
import com.freemud.application.sdk.api.storecenter.request.vo.GetOrgTreeListRequest;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import com.freemud.sdk.api.assortment.order.adapter.OrderSdkAdapter;
import com.freemud.sdk.api.assortment.order.enums.StockChangeType;
import com.freemud.sdk.api.assortment.order.request.order.*;
import com.freemud.sdk.api.assortment.order.response.order.BaseOrderResponse;
import com.freemud.sdk.api.assortment.order.response.order.CreateOrderResponse;
import com.freemud.sdk.api.assortment.order.response.order.PayAccessResponse;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.freemud.sdk.api.assortment.order.domain.ResponseCodeConstant.RESPONSE_SUCCESS_STR;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: SellCouponOrderServiceImpl
 * @Package cn.freemud.service.impl
 * @Description:
 * @author: ping1.wu
 * @date: 2020/5/21 17:49
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */

@Service
public class SellCouponOrderServiceImpl implements OrderFactoryService {

    @Autowired
    private CheckOrder checkOrder;
    @Autowired
    private MenuService menuService;
    @Autowired
    private OrderSdkService orderSdkService;
    //聚合订单服务
    @Autowired
    private OrderCenterSdkService orderCenterSdkService;
    @Autowired
    private OrderServiceImpl orderservice;
    @Autowired
    private StoreCenterService storeCenterService;
    @Autowired
    private OrderAdapter orderAdapter;
    @Autowired
    private CreateOrderAdapter createOrderAdapter;
    @Autowired
    private OrderSdkAdapter orderSdkAdapter;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SendCouponService sendCouponService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private StockSdkService stockSdkService;
    @Value("${coupon.app.id}")
    private String appId;
    @Autowired
    private StoreItemClient storeItemClient;

    @Value("#{${ngs.virtual.store.idmap:null}}")
    private Map<String, String> storeIdMap;
    @Value("${ngs.partnerId.easy}")
    private String easyPartnerId;
    @Value("${ngs.partnerId.supermarket}")
    private String supermarketPartnerId;


    @Value("#{'${buyProductOnce.partnerId}'.split(',')}")
    private List<String> buyProductOncePartnerIds;


    private final String SUCCESS = "100";

    private final String ngsCouponProductId = "76161384";
    @Autowired
    private OrderBusinessService orderBusinessService;

    @Autowired
    private BuyProductOnceManager buyProductOnceManager;

    @Autowired
    private PromotionDiscountClient promotionDiscountClient;

    @Autowired
    private PayServiceImpl payService;


    /**
     * 抖音卖券
     */
    @Override
    public BaseResponse createOrder(CreateOrderVo requestVo) {
        if (StringUtils.isEmpty(requestVo.getSaleCouponPhone())) {
            // 买券手机号必填，否则无法发券
            return ResponseUtil.error(ResponseCodeConstant.RESPONSE_ERROR_STR, "请填写手机号");
        }
        // 查询用户信息
        AssortmentCustomerInfoVo userLoginInfoDto = checkOrder.checkOrderByMemberNew(requestVo.getSessionId());
        String trackingNo = LogThreadLocal.getTrackingNo();
        String partnerId = userLoginInfoDto.getPartnerId();
        String userId = userLoginInfoDto.getMemberId();
        String wxAppId = userLoginInfoDto.getWxAppId();
        if(CollectionUtils.isEmpty(requestVo.getProducts())){
            return ResponseUtil.error(ResponseCodeConstant.RESPONSE_ERROR_STR, "无商品信息");
        }
        String skuId = requestVo.getProducts().get(0).getSkuId();
        //10-抖音卖券门店
        AssortmentOpenPlatformIappWxappStore wxAppStore = payService.getIappWxappStoreInfo(wxAppId,"10");
        if ((wxAppStore == null || wxAppStore.getClientCode() == null)) {
            return ResponseUtil.error(ResponseCodeConstant.RESPONSE_ERROR_STR, "支付门店未配置");
        }
        String storeId = wxAppStore.getStoreId();
        //查询门店信息
        StoreInfoRequest storeInfoRequest = new StoreInfoRequest(partnerId, storeId,null);
        StoreResponse storeResponse = storeCenterService.getStoreInfo(storeInfoRequest, trackingNo);
        if (storeResponse == null || storeResponse.getStatusCode() != 100 || storeResponse.getBizVO() == null) {
            throw new ServiceException(ResponseResult.STORE_NOT_FOUND);
        }

        GetProductInfoDto getProductInfoDto = new GetProductInfoDto();
        getProductInfoDto.setPartnerId(partnerId);
        getProductInfoDto.setShopId(storeId);
        getProductInfoDto.setProductInfoType(2);
        getProductInfoDto.setProductIds(Arrays.asList(skuId));
        getProductInfoDto.setChannel(BusinessTypeEnum.getByType(requestVo.getMenuType()).getCode());
        ProductInfosDto productInfosDto = storeItemClient.listProductInfos(getProductInfoDto);
        if (!ResponseCodeConstant.RESPONSE_SUCCESS.equals(productInfosDto.getErrcode()) || CollectionUtils.isEmpty(productInfosDto.getData().getProducts())) {
            AppLogUtil.infoLog("查询商品信息失败，getProductInfoDto，baseResponse",getProductInfoDto,productInfosDto);
            return ResponseUtil.error(ResponseResult.STORE_ITEM_CHECK_INVAILD);
        }

        //卖券订单biztype默认传入6
        BaseResponse createOrderRequestResponse = checkOrderCoupon(userLoginInfoDto, storeResponse, trackingNo, requestVo.getMenuType(), BizTypeEnum.SALE_COUPON.getBizType(), partnerId, storeId, skuId,requestVo.getCardCode());
        if (createOrderRequestResponse == null || !ResponseResult.SUCCESS.getCode().equals(createOrderRequestResponse.getCode()) || createOrderRequestResponse.getResult() == null) {
            return createOrderRequestResponse;
        }

        CreateOrderRequest createOrderRequest = (CreateOrderRequest) createOrderRequestResponse.getResult();

        OrderBaseResp<OrderInfoReqs> orderInfoReqsBaseResponse = orderSdkService.createOrder(createOrderRequest, trackingNo);
        CreateOrderResponse createOrderResponse = orderSdkAdapter.convent2NEWOrderInfoReqs(orderInfoReqsBaseResponse);
        if (createOrderResponse == null || createOrderResponse.getErrcode() != 100) {
            return ResponseUtil.error(ResponseResult.ORDER_CREATE_ERROR);
        }else{
            OrderBeanV1 orderBean = createOrderResponse.getData();
            if(productInfosDto.getData().getProducts().get(0).getStockLimit() == 1){
                CreateOrderProductRequest productRequest = new CreateOrderProductRequest();
                productRequest.setSpecification(skuId);
                productRequest.setHasStockProudct(true);
                productRequest.setNumber(1);
                UpdateStocksRequest updateStocksRequest = orderSdkAdapter.getUpdateProductStock(
                        orderBean, Arrays.asList(productRequest), StockChangeType.REDUCE,requestVo.getMenuType());
                com.freemud.application.sdk.api.base.BaseResponse baseResponse = stockSdkService.reducesStocks(updateStocksRequest, "");
                ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(),
                        "updateStock", JSONObject.toJSONString(updateStocksRequest), JSONObject.toJSONString(baseResponse));
                if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, baseResponse.getCode())) {
                    //TODO 失败取消订单
                    CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
                            AfterSalesType.SYSTEM_CANCEL, "商品库存不足", "", null);
                    BaseOrderResponse orderResponse = orderCenterSdkService.orderCancel(cancelOrderRequest);
                    return ResponseUtil.error(baseResponse.getCode(),"商品库存不足");
                }
            }
        }

        //创建支付
        CreatePrepayRequestDto createPrepayRequestDto = new CreatePrepayRequestDto();
        createPrepayRequestDto.setPartnerId(partnerId);
        createPrepayRequestDto.setTransId(orderInfoReqsBaseResponse.getResult().getOrderCode());
        createPrepayRequestDto.setWxAppId(userLoginInfoDto.getWxAppId());
        createPrepayRequestDto.setOpenId(userLoginInfoDto.getOpenId());
        createPrepayRequestDto.setCardCode(requestVo.getCardCode());
        createPrepayRequestDto.setPayCode(null);
        createPrepayRequestDto.setFatherOrderBean(createOrderResponse.getData());
        createPrepayRequestDto.setProductOrderBean(createOrderResponse.getData());
        createPrepayRequestDto.setTotalAmount(createOrderRequest.getSettlementAmount());
        createPrepayRequestDto.setCardAmount(0);
        createPrepayRequestDto.setChannel(PayChannelType.TIKTOKPAY.getEbcode());

        OrderExtInfoDto orderExtInfoDto = new OrderExtInfoDto();
        orderExtInfoDto.setOpenid(userLoginInfoDto.getOpenId());
        orderExtInfoDto.setAppid(userLoginInfoDto.getWxAppId());
        orderExtInfoDto.setSessionId(requestVo.getSessionId());
        orderExtInfoDto.setVersion(requestVo.getVersion());
        // 扩展字段中存储 sessionKey
        orderExtInfoDto.setSessionKey(userLoginInfoDto.getSessionKey());
        orderExtInfoDto.setFormId(requestVo.getFormId());
        orderExtInfoDto.setFromAppId(userLoginInfoDto.getWxAppId());
        orderExtInfoDto.setSaleCouponPhone(requestVo.getSaleCouponPhone());

        createPrepayRequestDto.setOrderExtInfoDTO(orderExtInfoDto);
        return ResponseUtil.success(payService.createPrepayOrder(createPrepayRequestDto));
    }

    /**
     * 卖券订单创建
     */
    public BaseResponse createOrder(SellCouponCreateOrderVo requestVo){
        // 查询用户信息
        AssortmentCustomerInfoVo userLoginInfoDto = checkOrder.checkOrderByMemberNew(requestVo.getSessionId());
        // 如果用户适用SVC 卡支付，则校验svc卡,
        checkOrder.checkMemberSvcCard(userLoginInfoDto.getPartnerId(), userLoginInfoDto.getMemberId(), requestVo);
        String trackingNo = LogThreadLocal.getTrackingNo();
        String partnerId = userLoginInfoDto.getPartnerId();
        String storeId = requestVo.getShopId();
        String userId = userLoginInfoDto.getMemberId();
        //查询门店信息
        StoreInfoRequest storeInfoRequest = new StoreInfoRequest(partnerId, storeId,null);
        StoreResponse storeResponse = storeCenterService.getStoreInfo(storeInfoRequest, trackingNo);
        if (storeResponse == null || storeResponse.getStatusCode() != 100 || storeResponse.getBizVO() == null) {
            throw new ServiceException(ResponseResult.STORE_NOT_FOUND);
        }
        StoreResponse.BizVO storeResponseDto = storeResponse.getBizVO();
        // 查询门店信息 营业时间、营业状态，服务器当前时间在营业时间内 点餐桌号
        checkOrder.checkOrderByStore(storeResponseDto);


        GetProductInfoDto getProductInfoDto = new GetProductInfoDto();
        getProductInfoDto.setPartnerId(partnerId);
        getProductInfoDto.setShopId(storeId);
        getProductInfoDto.setProductInfoType(2);
        getProductInfoDto.setProductIds(Arrays.asList(requestVo.getSkuId()));
        getProductInfoDto.setChannel(BusinessTypeEnum.getByType(requestVo.getMenuType()).getCode());
        ProductInfosDto productInfosDto = storeItemClient.listProductInfos(getProductInfoDto);
        if (!ResponseCodeConstant.RESPONSE_SUCCESS.equals(productInfosDto.getErrcode()) || CollectionUtils.isEmpty(productInfosDto.getData().getProducts())) {
            AppLogUtil.infoLog("查询商品信息失败，getProductInfoDto，baseResponse",getProductInfoDto,productInfosDto);
            return ResponseUtil.error(ResponseResult.STORE_ITEM_CHECK_INVAILD);
        }

        //通过商户号配置进阿波罗，识别哪些商户走仅限一次卖券业务 wanghanghang 0610
        //【P0】【业务 / 米食】【B端 / 万象 / 活动下架】商户618活动：一元买虚拟商品特殊处理活动下架，删除特殊增加字段 wanghanghang
        //处理方式，阿波罗配置商户改成空。没必要删除代码。保留后续此类活动还可继续使用
        if (buyProductOncePartnerIds != null && buyProductOncePartnerIds.contains(partnerId)) {
            try {
                ResponseResult checkRequest =  buyProductOnceManager.checkBuyProductOnce(productInfosDto.getData().getProducts(),partnerId,userId);
                if(!checkRequest.equals(ResponseResult.SUCCESS)){
                    return ResponseUtil.error(checkRequest);
                }
            }catch (Exception e){
                AppLogUtil.infoLog("校验用户每人每单限购一次异常",getProductInfoDto,productInfosDto);
            }
        }

        //卖券订单biztype默认传入6
        BaseResponse createOrderRequestResponse = checkOrderCoupon(userLoginInfoDto, storeResponse, trackingNo, requestVo.getMenuType(), 6, partnerId, storeId, requestVo.getSkuId(),requestVo.getCardCode());
        if (createOrderRequestResponse == null || !ResponseResult.SUCCESS.getCode().equals(createOrderRequestResponse.getCode()) || createOrderRequestResponse.getResult() == null) {
            return createOrderRequestResponse;
        }

        CreateOrderRequest createOrderRequest = (CreateOrderRequest) createOrderRequestResponse.getResult();
        //标准化平台虚拟商品特价活动计算，不包含蜜雪APP买虚拟商品
        List<ActivityUpdateStockRequest.StockBeanDto> stockBeanDtos = calculationDiscount(partnerId, storeId, userLoginInfoDto.getMemberId(), productInfosDto.getData().getProducts().get(0), createOrderRequest);

        OrderBaseResp<OrderInfoReqs> orderInfoReqsBaseResponse = orderSdkService.createOrder(createOrderRequest, trackingNo);
        CreateOrderResponse createOrderResponse = orderSdkAdapter.convent2NEWOrderInfoReqs(orderInfoReqsBaseResponse);
        if (createOrderResponse == null || createOrderResponse.getErrcode() != 100) {
            return ResponseUtil.error(ResponseResult.ORDER_CREATE_ERROR);
        }else{
            OrderBeanV1 orderBean = createOrderResponse.getData();
            if(productInfosDto.getData().getProducts().get(0).getStockLimit() == 1){
                CreateOrderProductRequest productRequest = new CreateOrderProductRequest();
                productRequest.setSpecification(requestVo.getSkuId());
                productRequest.setHasStockProudct(true);
                productRequest.setNumber(1);
                UpdateStocksRequest updateStocksRequest = orderSdkAdapter.getUpdateProductStock(
                        orderBean, Arrays.asList(productRequest), StockChangeType.REDUCE,requestVo.getMenuType());
                com.freemud.application.sdk.api.base.BaseResponse baseResponse = stockSdkService.reducesStocks(updateStocksRequest, "");
                ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(),
                        "updateStock", JSONObject.toJSONString(updateStocksRequest), JSONObject.toJSONString(baseResponse));
                if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, baseResponse.getCode())) {
                    //TODO 失败取消订单
                    CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
                            AfterSalesType.SYSTEM_CANCEL, "商品库存不足", "", null);
                    BaseOrderResponse orderResponse = orderCenterSdkService.orderCancel(cancelOrderRequest);
                    //异常清理掉key
                    //        //【P0】【业务 / 米食】【B端 / 万象 / 活动下架】商户618活动：一元买虚拟商品特殊处理活动下架，删除特殊增加字段 7.13 wanghanghang
//                    buyProductOnceManager.removeCheckBuyProductOnceKey(partnerId,userId,orderBean.getProductList().get(0).getProductId());
                    return ResponseUtil.error(baseResponse.getCode(),"商品库存不足");
                }
            }
            if(CollectionUtils.isNotEmpty(stockBeanDtos)){
                // 扣减活动库存
                ActivityUpdateStockRequest activityUpdateStockRequest = orderSdkAdapter.convert2ActivityUpdateStockRequest(orderBean, stockBeanDtos);
                // 原逻辑只检测扣减库存不为空时调用，现改为扣减库存不为空或参加活动不为空时调用
                if (activityUpdateStockRequest != null && (CollectionUtils.isNotEmpty(activityUpdateStockRequest.getStock()) || CollectionUtils.isNotEmpty(activityUpdateStockRequest.getActivityList()))) {
                    PromotionResponseDTO activityResponse = promotionDiscountClient.subtractStock(activityUpdateStockRequest);
                    if (!ObjectUtils.equals(RESPONSE_SUCCESS_STR, activityResponse.getStatusCode())) {
                        // 失败取消订单
                        CancelOrderRequest cancelOrderRequest = orderSdkAdapter.convent2CancelOrderRequest(orderBean.getOid(), orderBean.getCompanyId(),
                                AfterSalesType.SYSTEM_CANCEL, "活动库存不足", "", null);
                        BaseOrderResponse orderResponse = orderCenterSdkService.orderCancel(cancelOrderRequest);
                        return ResponseUtil.error(ResponseResult.ORDER_CREATE_ERROR.getCode(),"活动库存不足");
                    }
                }
            }

        }

        //创建支付
        CreatePrepayRequestDto createPrepayRequestDto = new CreatePrepayRequestDto();
        createPrepayRequestDto.setPartnerId(partnerId);
        createPrepayRequestDto.setTransId(orderInfoReqsBaseResponse.getResult().getOrderCode());
        createPrepayRequestDto.setWxAppId(userLoginInfoDto.getWxAppId());
        createPrepayRequestDto.setOpenId(userLoginInfoDto.getOpenId());
//        createPrepayRequestDto.setFaceCode(null);
        createPrepayRequestDto.setCardCode(requestVo.getCardCode());
        createPrepayRequestDto.setPayCode(null);
        createPrepayRequestDto.setFatherOrderBean(createOrderResponse.getData());
        createPrepayRequestDto.setProductOrderBean(createOrderResponse.getData());
        createPrepayRequestDto.setTotalAmount(createOrderRequest.getSettlementAmount());
        createPrepayRequestDto.setCardAmount(0);
        createPrepayRequestDto.setChannel(requestVo.getChannel());
        OrderExtInfoDto orderExtInfoDto = new OrderExtInfoDto();
        String deliveryHoursDayStart = "";
        String deliveryHoursDayEnd = "";
        if (StringUtils.isNotBlank(storeResponseDto.getDeliveryHoursDay())) {
            String[] days = storeResponseDto.getDeliveryHoursDay().split("-");
            if (days.length == 2) {
                deliveryHoursDayStart = DateUtil.convert2String(new Date(), DateUtil.FORMAT_yyyyMMdd_date) + " " + days[0] + ":00";
//                deliveryHoursDayEnd = DateUtil.convert2String(new Date(), DateUtil.FORMAT_yyyyMMdd_date) + " " + days[1] + ":00";
            }
        }
        orderExtInfoDto.setDeliveryHoursDayStart(deliveryHoursDayStart);
        orderExtInfoDto.setDeliveryHoursDayEnd(deliveryHoursDayEnd);
        orderExtInfoDto.setOpenid(userLoginInfoDto.getOpenId());
        orderExtInfoDto.setAppid(userLoginInfoDto.getWxAppId());
        orderExtInfoDto.setSessionId(requestVo.getSessionId());
        Integer serviceTime = storeResponseDto.getServiceTime();
        if (Objects.equals(serviceTime, null)) {
            serviceTime = 50;
        }
        orderExtInfoDto.setServiceTime(serviceTime);
        orderExtInfoDto.setVersion(requestVo.getVersion());
        // 扩展字段中存储 sessionKey
        orderExtInfoDto.setSessionKey(userLoginInfoDto.getSessionKey());
        orderExtInfoDto.setFormId(requestVo.getFormId());
        orderExtInfoDto.setFromAppId(userLoginInfoDto.getWxAppId());
        orderExtInfoDto.setUnDistribution(requestVo.getUnDistribution());
        createPrepayRequestDto.setOrderExtInfoDTO(orderExtInfoDto);
        return ResponseUtil.success(payService.createPrepayOrder(createPrepayRequestDto));
    }


    /**
     * 效验虚拟商品活动信息
     * @param userLoginInfoDto
     * @param storeResponse
     * @param trackingNo
     * @param menuType
     * @param bizType
     * @param partnerId
     * @param storeId
     * @param skuId
     * @param cardCode
     * @return
     */
    public BaseResponse checkOrderCoupon(AssortmentCustomerInfoVo userLoginInfoDto,
                                         StoreResponse storeResponse,
                                         String trackingNo,
                                         String menuType,
                                         Integer bizType,
                                         String partnerId,
                                         String storeId,
                                         String skuId,String cardCode) {

        //校验虚拟商品是否在门店菜单
        GetValidateProductInfoDto getProductInfoDto = new GetValidateProductInfoDto();
        getProductInfoDto.setPartnerId(partnerId);
        getProductInfoDto.setStoreId(storeId);
        getProductInfoDto.setChannel(menuType);
        List<String> productIds = new ArrayList<>();
        productIds.add(skuId);
        getProductInfoDto.setProductIds(productIds);
        ValidateProductInfosDto productInfosDto = storeItemClient.validateShopContainProduct(getProductInfoDto);
        if (!Objects.equals(productInfosDto.getErrcode(), Integer.valueOf(ResponseResult.SUCCESS.getCode()))
                || productInfosDto.getData() ==null
                || CollectionUtils.isEmpty(productInfosDto.getData().getSuccessList())){
            return ResponseUtil.error(ResponseResult.STORE_ITEM_CHECK_VAILD_ERROR);
        }

        GetProductInfoRequest request = new GetProductInfoRequest();
        request.setChannel(menuType);
        request.setPartnerId(partnerId);
        request.setProductInfoType(ProductInfoType.ALL.getCode());
        request.setShopId(storeId);
        request.setProductIds(productIds);
        //获取商品（里面的活动）
        com.freemud.application.sdk.api.base.BaseResponse<GetProductInfosResponse> productInfosByIds = menuService.getProductInfosByIds(request, trackingNo);
        if (!ResponseCodeConstant.RESPONSE_SUCCESS_STR.equals(productInfosByIds.getCode()) || productInfosByIds.getData() == null || CollectionUtils.isEmpty(productInfosByIds.getData().getProducts())) {
            return ResponseUtil.error(ResponseResultEnum.GET_PRODUCT_INFOS_ERROR.getCode(), ResponseResultEnum.GET_PRODUCT_INFOS_ERROR.getMessage());
        }
        //效验商品券是否有效
        List<GetMenuCategoryInfoResponse.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean.ProductBindingCouponType> productBindingCoupons = productInfosByIds.getData().getProducts().get(0).getProductBindingCouponTypes();
        if (CollectionUtils.isEmpty(productBindingCoupons)) {
            return ResponseUtil.error(ResponseResult.STORE_ITEM_CHECK_INVAILD);
        }
        // 产品确认 暂时不需要改逻辑
//        List<GetMenuCategoryInfoResponse.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean> products = productInfosByIds.getData().getProducts();
//
//        for (GetMenuCategoryInfoResponse.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean product : products) {
//            Integer status = product.getStatus();
//            if (!Objects.equals(status, IntegralProductStatusEnum.STATUS_2.getCode())) {
//                return ResponseUtil.error(ResponseResult.COUPON_INVAILD.getCode(),"您需要购买的券包，包含的优惠券券编号"+skuId+"包含的商品已失效，请联系门店尽快处理");
//            }
//        }
        List<String> activityCodes = new ArrayList<>();
        for (GetMenuCategoryInfoResponse.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean.ProductBindingCouponType productBindingCouponType : productBindingCoupons) {
            activityCodes.add(productBindingCouponType.getActivityCode());
        }
        //批量查询活动详情
        List<ActiveDetailVO> activeDetailVOS = batchQueryActivityInfo(partnerId, activityCodes, trackingNo);
        if (CollectionUtils.isEmpty(activeDetailVOS) || activityCodes.size() != activeDetailVOS.size()) {
            return ResponseUtil.error(ResponseResult.STORE_ITEM_CHECK_INVAILD);
        }
        //优惠券是否失效
        Date now = new Date();
        for (ActiveDetailVO activeDetailVO : activeDetailVOS) {
            if (activeDetailVO.getEffectiveEndTime() != null && activeDetailVO.getEffectiveEndTime().before(now)) {
                return ResponseUtil.error(ResponseResult.COUPON_INVAILD.getCode(),"您需要购买的券包，包含的优惠券券编号"+activeDetailVO.getActiveCode()+"已过期，请联系门店尽快处理");
            }
            // endDate   领券结束时间 校验  当前时间小鱼endDate
            if (activeDetailVO.getEndDate() != null && activeDetailVO.getEndDate().before(now)) {
                return ResponseUtil.error(ResponseResult.COUPON_INVAILD.getCode(),"您需要购买的券包，包含的优惠券券编号"+activeDetailVO.getActiveCode()+"已过期，请联系门店尽快处理");
            }
            // state = 1  ||  2  可以买
            if (activeDetailVO.getState() !=null) {
                Integer state = activeDetailVO.getState();
                if (!Objects.equals(state,1) && !Objects.equals(state,2)) {
                    return ResponseUtil.error(ResponseResult.COUPON_INVAILD.getCode(),"您需要购买的券包，包含的优惠券券编号"+activeDetailVO.getActiveCode()+"已失效，请联系门店尽快处理");
                }
            }
        }
        //转换CreateOrderRequest对象
        CreateOrderRequest createOrderRequest = convent2NEWCreateOrderRequest(userLoginInfoDto,
                productInfosByIds.getData(),
                activeDetailVOS,
                storeResponse.getBizVO(),storeId,cardCode,skuId,menuType,bizType);
        return ResponseUtil.success(createOrderRequest);
    }




    public BaseResponse ngsCouponOrderCreate(NgsSellCouponCreateOrderVo requestVo){
        // 查询用户信息、校验svc卡
        AssortmentCustomerInfoVo userLoginInfoDto = checkOrder.getMemberNew(requestVo.getSessionId());
        String trackingNo = LogThreadLocal.getTrackingNo();
        String partnerId = userLoginInfoDto.getPartnerId();
        // 构建创建订单入参
        CreateOrderRequest createOrderRequest = ngsConvent2NEWCreateOrderRequest(requestVo,userLoginInfoDto);
        OrderBaseResp<OrderInfoReqs> orderInfoReqsBaseResponse = orderSdkService.createOrder(createOrderRequest, trackingNo);
        CreateOrderResponse createOrderResponse = orderSdkAdapter.convent2NEWOrderInfoReqs(orderInfoReqsBaseResponse);
        if(createOrderResponse == null || createOrderResponse.getErrcode() != 100){
            return ResponseUtil.error(ResponseResult.ORDER_CREATE_ERROR);
        }
        //创建支付
        CreatePrepayRequestDto createPrepayRequestDto = new CreatePrepayRequestDto();
        createPrepayRequestDto.setPartnerId(partnerId);
        createPrepayRequestDto.setTransId(orderInfoReqsBaseResponse.getResult().getOrderCode());
        createPrepayRequestDto.setWxAppId(userLoginInfoDto.getWxAppId());
        createPrepayRequestDto.setOpenId(userLoginInfoDto.getOpenId());
        createPrepayRequestDto.setCardCode(requestVo.getCardCode());
        createPrepayRequestDto.setPayCode(null);
        createPrepayRequestDto.setFatherOrderBean(createOrderResponse.getData());
        createPrepayRequestDto.setProductOrderBean(createOrderResponse.getData());
        createPrepayRequestDto.setTotalAmount(createOrderRequest.getSettlementAmount());
        createPrepayRequestDto.setCardAmount(0);
        OrderExtInfoDto orderExtInfoDto = new OrderExtInfoDto();
        String deliveryHoursDayStart = "";
        String deliveryHoursDayEnd = "";
        orderExtInfoDto.setDeliveryHoursDayStart(deliveryHoursDayStart);
        orderExtInfoDto.setDeliveryHoursDayEnd(deliveryHoursDayEnd);
        orderExtInfoDto.setOpenid(userLoginInfoDto.getOpenId());
        orderExtInfoDto.setAppid(userLoginInfoDto.getWxAppId());
        orderExtInfoDto.setSessionId(requestVo.getSessionId());
        Integer serviceTime = 0;
        if (Objects.equals(serviceTime, null)) {
            serviceTime = 50;
        }
        orderExtInfoDto.setServiceTime(serviceTime);
        orderExtInfoDto.setVersion(requestVo.getVersion());
        // 扩展字段中存储 sessionKey
        orderExtInfoDto.setSessionKey(userLoginInfoDto.getSessionKey());
        orderExtInfoDto.setFromAppId(userLoginInfoDto.getWxAppId());

        String date = DateUtil.convert2String(new Date(), "yyyyMMdd");
        String key = this.getFolwNo(requestVo.getAppId(), date);

        int flowno = 0;
        RedisTemplate redisTemplate = redisCache.getRedisTemplate();

        if (redisTemplate.opsForValue().setIfAbsent(key, 0)) {
            redisTemplate.expire(key, 24, TimeUnit.HOURS);
        } else {
            flowno = redisTemplate.opsForValue().increment(key, 1).intValue();
        }
        String stationid = getStationId(date, requestVo.getAppId(), flowno);

        orderExtInfoDto.setStationId(stationid);

        createPrepayRequestDto.setOrderExtInfoDTO(orderExtInfoDto);
        return ResponseUtil.success(payService.createPrepayOrder(createPrepayRequestDto));

    }

    private String getStationId(String date, String appid, int flowno) {
        String stationid = "";
        int length = String.valueOf(flowno).length();
        if (easyPartnerId.equals(appid)){
            stationid = date + "6600000001";
            for (int i = 0; i < 5 - length; i++){
                stationid += "0";
            }
            stationid += flowno;
        } else if (supermarketPartnerId.equals(appid)) {
            stationid = date + "9988800001";
            for (int i = 0; i < 5 - length; i++){
                stationid += "0";
            }
            stationid += flowno;
        }
        return stationid;
    }

    private String getFolwNo(String partnerId, String date){
        return CommonRedisKeyConstant.NGS_FLOWNO_PARTNER_DATE_NO + ":" + partnerId + ":" + date;
    }

    /**
     * 批量查询活动详情
     *
     * @param partnerId
     * @param activityCodes
     * @param trackingNo
     * @return
     */
    private List<ActiveDetailVO> batchQueryActivityInfo(String partnerId, List<String> activityCodes, String trackingNo) {
        String appKey = getAppKey(partnerId, trackingNo);
        if (StringUtils.isEmpty(appKey)) {
            return null;
        }
        ActiveBatchQueryRequest activeBatchQueryRequest = new ActiveBatchQueryRequest();
        //去重
        List<String> activeCodes = new ArrayList<>(new HashSet(activityCodes));
        activeBatchQueryRequest.setActiveCode(activeCodes);
        activeBatchQueryRequest.setAppSecret(appKey);
        activeBatchQueryRequest.setPartnerId(Integer.parseInt(partnerId));
        FMActiveSdkService fmActiveSdkService = SDKCommonBaseContextWare.getBean(FMActiveSdkService.class);
        com.freemud.application.sdk.api.base.BaseResponse<List<ActiveDetailVO>> batchQueryResponse = fmActiveSdkService.batchQueryActivityInfo(activeBatchQueryRequest, trackingNo);
        if (batchQueryResponse == null || !SUCCESS.equals(batchQueryResponse.getCode()) || CollectionUtils.isEmpty(batchQueryResponse.getData())) {
            return null;
        }

        return batchQueryResponse.getData();
    }

    /**
     * 查询组织机构
     * @param partnerId
     * @param storeId
     * @return
     */
    private List<String> getOrgIds(String partnerId, String storeId) {
        GetOrgTreeListRequest request = new GetOrgTreeListRequest();
        request.setPartnerId(partnerId);
        request.setStoreCode(storeId);
        StoreCenterService storeCenterService = SDKCommonBaseContextWare.getBean(StoreCenterService.class);
        com.freemud.application.sdk.api.base.BaseResponse<List<String>> orgList = storeCenterService.getOrgList(request, LogThreadLocal.getTrackingNo());
        if (orgList != null && SUCCESS.equals(orgList.getCode())) {
            return orgList.getData();
        }
        return Collections.EMPTY_LIST;
    }


    /**
     * 获取商户秘钥
     *
     * @param partnerId
     * @param trackingNo
     * @return
     */
    private String getAppKey(String partnerId, String trackingNo) {
        RedisCache redisCache = SDKCommonBaseContextWare.getBean(RedisCache.class);
        String  key = "kgd:coupon:appKey:partner:";
        String appKey = redisCache.getValue(key + partnerId);
        if (StringUtils.isEmpty(appKey)) {
            PartnerRequest partnerRequest = new PartnerRequest();
            partnerRequest.setPartnerId(Integer.parseInt(partnerId));
            partnerRequest.setAppId(appId);
            FMActiveSdkService fmActiveSdkService = SDKCommonBaseContextWare.getBean(FMActiveSdkService.class);
            com.freemud.application.sdk.api.base.BaseResponse<AppKeyVO> appKeyVOBaseResponse = fmActiveSdkService.getAppKey(partnerRequest, trackingNo);
            if (appKeyVOBaseResponse == null || !"100".equals(appKeyVOBaseResponse.getCode())
                    || appKeyVOBaseResponse.getData() == null || StringUtils.isEmpty(appKeyVOBaseResponse.getData().getAppKey())) {
                return null;
            }
            appKey = appKeyVOBaseResponse.getData().getAppKey();
            redisCache.save(key + partnerId, appKey);
        }
        return appKey;
    }

    /**
     * 转换对象，从购买优惠券业务提出重写
     * @param userLoginInfoDto
     * @param productInfosResponse
     * @param activeDetailVOS
     * @param storeInfo
     * @param shopId
     * @param cardCode
     * @param skuId
     * @param channel
     * @param bizType
     * @return
     */
    private CreateOrderRequest convent2NEWCreateOrderRequest(AssortmentCustomerInfoVo userLoginInfoDto,
                                                             GetProductInfosResponse productInfosResponse,List<ActiveDetailVO> activeDetailVOS,
                                                             StoreResponse.BizVO storeInfo,
                                                             String shopId,
                                                             String cardCode,
                                                             String skuId,
                                                             String channel,
                                                             Integer bizType){
        CreateOrderRequest request = new CreateOrderRequest();
        Integer orderClient = OrderClientType.SAAS.getIndex();
        request.setPayChannel(PayChannelType.WECHAT.getIndex().toString());
        request.setPayChannelType(PayChannelType.WECHAT.getIndex());
        if(UserLoginChannelEnum.ALIPAY.getCode().equals(userLoginInfoDto.getChannel())){
            orderClient = OrderClientType.ALIPAY.getIndex();
            request.setPayChannel(PayChannelType.ALIPAY.getIndex().toString());
            request.setPayChannelType(PayChannelType.ALIPAY.getIndex());
        }
        if(UserLoginChannelEnum.APP.getCode().equals(userLoginInfoDto.getChannel())){
            orderClient = OrderClientType.APP.getIndex();
        }
        //抖音小程序
        if("5".equalsIgnoreCase(userLoginInfoDto.getChannel())) {
            request.setPayChannel(PayChannelType.TIKTOKPAY.getIndex().toString());
            request.setPayChannelType(PayChannelType.TIKTOKPAY.getIndex());
            orderClient = OrderClientType.TIKTOKPAY.getIndex();
        }
        String partnerId = userLoginInfoDto.getPartnerId();
        request.setOrderClient(orderClient);
        request.setPartnerId(partnerId);
        request.setStoreId(shopId);
        //买券虚拟订单  不管APP卖券还是平台，依旧保留传入6
        request.setBizType(bizType);
        //1:线上支付 2:线下支付
        request.setPayType(1);
        request.setUserId(userLoginInfoDto.getMemberId());
        request.setUserName(userLoginInfoDto.getNickName());
        request.setStoreName(storeInfo.getStoreName());
        request.setThirdStoreId(storeInfo.getThirdPartCode());
        request.setOrderState(1);
        request.setPayState(1);
        if(StringUtils.isNotBlank(cardCode)){
            request.setPayChannel("10102");
            request.setPayChannelName("储值卡支付");
        }
        GetMenuCategoryInfoResponse.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean productBean = productInfosResponse.getProducts().get(0);
        //订单原始金额，单位分
        //用户在界面上看到的支付金额
        request.setSettlementAmount(productBean.getFinalPrice());
        //实际支付现金金额，扣除支付自生优惠，单位分`
        request.setActualPayAmount(productBean.getFinalPrice());
        request.setOriginalAmount(productBean.getOriginalPrice());
        request.setOrderType(OrderType.GENERAL_DINE_IN.getIndex());
        //商品信息转换
        List<OrderItemCreateReq> orderItemList = new ArrayList<>();
        OrderItemCreateReq orderItemCreateReq = new OrderItemCreateReq();
        orderItemCreateReq.setSalePrice(productBean.getFinalPrice());
        orderItemCreateReq.setProductPrice(productBean.getOriginalPrice());
        orderItemCreateReq.setSettlementPrice(productBean.getFinalPrice());
        orderItemCreateReq.setPartnerId(partnerId);
        orderItemCreateReq.setProductId(skuId);
        orderItemCreateReq.setProductSpec(skuId);
        orderItemCreateReq.setProductName(productBean.getName());
        orderItemCreateReq.setProductSpecName(productBean.getName());
        orderItemCreateReq.setProductPicUrl(productBean.getPicture());
        orderItemCreateReq.setProductSeq(1);
        orderItemCreateReq.setProductCode(productBean.getProductCode());
        orderItemCreateReq.setThirdProductId(productBean.getCustomerCode());
        orderItemCreateReq.setProductQuantity(1);
        orderItemCreateReq.setOriginalProductType(productBean.getType());

        OrderProductAddInfoDto orderProductAddInfoDto = new OrderProductAddInfoDto();
        List<ProductBindingCouponType> productBindingCoupons = new ArrayList<>();
        for (GetMenuCategoryInfoResponse.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean.ProductBindingCouponType productBindingCouponType : productBean.getProductBindingCouponTypes()){
            for (ActiveDetailVO activeDetailVO : activeDetailVOS){
                if(productBindingCouponType.getActivityCode().equals(activeDetailVO.getActiveCode())){
                    ProductBindingCouponType productBindingCouponType2 = new ProductBindingCouponType();
                    productBindingCouponType2.setActivityCode(productBindingCouponType.getActivityCode());
                    productBindingCouponType2.setNum(productBindingCouponType.getNum());
                    productBindingCouponType2.setActivityName(activeDetailVO.getActiveName());
                    productBindingCoupons.add(productBindingCouponType2);
                    break;
                }
            }
        }
        orderProductAddInfoDto.setProductBindingCoupons(productBindingCoupons);
        orderItemCreateReq.setExtInfo(JSONObject.toJSONString(orderProductAddInfoDto));
        orderItemList.add(orderItemCreateReq);

        //商品信息赋值
        request.setOrderItemList(orderItemList);
        //收货人信息转换
        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);
        deliveryContactInfoList.add(deliveryContactInfoCreateReq);
        request.setDeliveryContactInfoList(deliveryContactInfoList);
        //保存门店渠道信息
        request.setOrderExtended(orderAdapter.saveStoreInfo(storeInfo));
        request.setOperator(userLoginInfoDto.getNickName());
        request.setAppId(userLoginInfoDto.getWxAppId());
        return request;

    }




    private CreateOrderRequest ngsConvent2NEWCreateOrderRequest(NgsSellCouponCreateOrderVo requestVo, AssortmentCustomerInfoVo userLoginInfoDto){



        CreateOrderRequest request = new CreateOrderRequest();
        Integer orderClient = OrderClientType.SAAS.getIndex();
        if(UserLoginChannelEnum.ALIPAY.getCode().equals(userLoginInfoDto.getChannel())){
            orderClient = OrderClientType.ALIPAY.getIndex();
        }
        if(UserLoginChannelEnum.APP.getCode().equals(userLoginInfoDto.getChannel())){
            orderClient = OrderClientType.APP.getIndex();
        }
        String partnerId = userLoginInfoDto.getPartnerId();
        String requestVoAppId = requestVo.getAppId();

        request.setOrderClient(orderClient);
        request.setPartnerId(partnerId);
        request.setStoreId(storeIdMap.get(requestVoAppId));
        //买券虚拟订单
        request.setBizType(6);
        //1:线上支付 2:线下支付
        request.setPayType(1);
        request.setUserId(userLoginInfoDto.getMemberId());
        request.setUserName(userLoginInfoDto.getNickName());
        request.setStoreName("虚拟门店");
        request.setThirdStoreId("");
        request.setOrderState(1);
        request.setPayState(1);
        if(StringUtils.isNotBlank(requestVo.getCardCode())){
            request.setPayChannel("10102");
            request.setPayChannelName("储值卡支付");
        }
        // TODO 商品信息 从券码查
        // TODO 通过活动号查询金额
        String activityCode = requestVo.getActivityCode();
        BatchQueryActivityInfoRequestDto queryActivityInfoRequestDto = new BatchQueryActivityInfoRequestDto();
        queryActivityInfoRequestDto.setActiveCode(Arrays.asList(activityCode));
        queryActivityInfoRequestDto.setPartnerId(Integer.valueOf(partnerId));
        BatchQueryActivityInfoResponseDto batchQueryActivityInfoResponseDto = couponService.batchQueryActivityInfo(queryActivityInfoRequestDto);
        Active active = batchQueryActivityInfoResponseDto.getActivities().get(0);

        // GetMenuCategoryInfoResponse.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean productBean = productInfosResponse.getProducts().get(0);
        //订单原始金额，单位分
        //用户在界面上看到的支付金额


        request.setSettlementAmount(active.getSalePrice().longValue());
        //实际支付现金金额，扣除支付自生优惠，单位分`
        request.setActualPayAmount(active.getSalePrice().longValue());
        request.setOriginalAmount(active.getVoucherFaceValue().longValue());
        request.setOrderType(OrderType.GENERAL_DINE_IN.getIndex());
        //商品信息转换
        List<OrderItemCreateReq> orderItemList = new ArrayList<>();
        OrderItemCreateReq orderItemCreateReq = new OrderItemCreateReq();
        orderItemCreateReq.setSalePrice(active.getSalePrice().longValue());
        orderItemCreateReq.setProductPrice(active.getVoucherFaceValue().longValue());
        orderItemCreateReq.setSettlementPrice(active.getSalePrice().longValue());
        orderItemCreateReq.setPartnerId(partnerId);

        orderItemCreateReq.setProductId(activityCode);
        orderItemCreateReq.setProductSpec(activityCode);
        orderItemCreateReq.setProductName(active.getActiveName());
        orderItemCreateReq.setProductSpecName(active.getActiveName());
        orderItemCreateReq.setProductSeq(1);
        orderItemCreateReq.setProductCode(activityCode);
        orderItemCreateReq.setThirdProductId("");
        orderItemCreateReq.setProductQuantity(1);

        OrderProductAddInfoDto orderProductAddInfoDto = new OrderProductAddInfoDto();
        List<ProductBindingCouponType> productBindingCoupons = new ArrayList<>();
        ProductBindingCouponType productBindingCouponType2 = new ProductBindingCouponType();
        productBindingCouponType2.setActivityCode(active.getActiveCode());
        productBindingCouponType2.setNum(active.getAccountSendOutAmount());
        productBindingCouponType2.setActivityName(active.getActiveName());
        productBindingCoupons.add(productBindingCouponType2);
        orderProductAddInfoDto.setProductBindingCoupons(productBindingCoupons);
        orderItemCreateReq.setExtInfo(JSONObject.toJSONString(orderProductAddInfoDto));
        orderItemList.add(orderItemCreateReq);

        //商品信息赋值
        request.setOrderItemList(orderItemList);
        //收货人信息转换
        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);
        deliveryContactInfoList.add(deliveryContactInfoCreateReq);
        request.setDeliveryContactInfoList(deliveryContactInfoList);
        //保存门店渠道信息
        request.setOperator(userLoginInfoDto.getNickName());
        request.setAppId(userLoginInfoDto.getWxAppId());
        return request;

    }

    /**
     *
     * @param message
     * @param confirmOrderDto
     * @param orderBeans
     * @return
     */
    public String paySuccessCallback(PaysuccessNoticeMessage message, ConfirmOrderDto confirmOrderDto, Map<String, OrderBeanV1> orderBeans) {
        OrderBeanV1 orderBean = orderBeans.get(OrderBeanType.SAASORDER.getCode());

        ConfirmOrderRequest var1 = LightApplicationConvertToAssortmentSdkAdapter.confirmOrderDtoConvertToConfirmOrderRequest(confirmOrderDto, orderBeans.get(OrderBeanType.MERMBERORDER.getCode()));
        var1.setPartnerId(orderBean.getCompanyId());
        var1.setUserId(orderBean.getUserId());
        var1.setStoreId(orderBean.getShopId());
        var1.setOrderType(orderBean.getType());
        var1.setProductOrderCode(orderBean.getOid());
        var1.setPayDate(DateUtil.convert2String(new Date(), "yyyy-MM-dd HH:mm:ss"));
        var1.setPayTransId(message.getOut_trade_no());
        var1.setOperator(orderBean.getUserName());
        var1.setEndTransId(message.getEndTransId());
        var1.setExtInfo(orderBean.getExtInfo());
        if(orderBean.getGmtExpect() != null && orderBean.getGmtExpect() != 0){
            var1.setExpectTime(DateUtil.convert2String(new Date(orderBean.getGmtExpect()),DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        }
        try {
            // 订单支付成功
            PayAccessResponse payAccessResponse = orderBusinessService.payAccess(var1);
        }catch (Exception e){
            AppLogUtil.errorLog("sellCouponPayAccessError",JSONObject.toJSONString(var1),null,e);
        }
        //支付成功直接完成
        OrderChangeStateReq request = new OrderChangeStateReq();
        request.setOrderCode(orderBean.getOid());
        request.setOrderState(NewOrderStatus.COMPLETE.getIndex());
        request.setOperator(orderBean.getUserName());
        request.setRemark("已完成");
        OrderBaseResp updateOrderStateResp = orderSdkService.updateOrderState(request, LogThreadLocal.getTrackingNo());
        orderSdkAdapter.convent2BaseOrderResponse(updateOrderStateResp);
        Map<String, Object> map = Maps.newTreeMap();
        map.put("code", 100);
        map.put("message", "success");
        return JSONObject.toJSONString(map);
    }


    /**
     * 查询促销优惠，赋值订单金额，商品优惠后金额，优惠记录
     */
    private List<ActivityUpdateStockRequest.StockBeanDto> calculationDiscount(String partnerId,String storeId,String userId,ProductInfo products,CreateOrderRequest createOrderRequest){
        CalculationDiscountRequestDto calculationDiscountRequestDto = new CalculationDiscountRequestDto();
        calculationDiscountRequestDto.setStoreId(storeId);
        calculationDiscountRequestDto.setPartnerCode(partnerId);
        calculationDiscountRequestDto.setUserId(userId);
        List<CalculationDiscountGoodsDto> discountGoodsDtoList = new ArrayList<>();
        CalculationDiscountGoodsDto discountGoodsDto = new CalculationDiscountGoodsDto();
        discountGoodsDto.setGoodsId(products.getPid());
        discountGoodsDto.setSpuId(products.getPid());
        discountGoodsDto.setGoodsQuantity(1);
        discountGoodsDto.setOriginalPrice(products.getFinalPrice().intValue());
        discountGoodsDtoList.add(discountGoodsDto);
        calculationDiscountRequestDto.setGoods(discountGoodsDtoList);

        //买券包调促销指定只计算限时特价    [2,21]
        calculationDiscountRequestDto.setActivityTypes(Arrays.asList(2,21));
        calculationDiscountRequestDto.setVer(1);
        ActivityCalculationDiscountResponseDto activityCalculationDiscountResponseDto = promotionDiscountClient.calculationDiscountSharing(calculationDiscountRequestDto);
        if (!ResponseResult.SUCCESS.getCode().equals(activityCalculationDiscountResponseDto.getStatusCode()) || activityCalculationDiscountResponseDto.getResult() == null) {
            return null;
        }
        ActivityCalculationDiscountResponseDto.CalculationDiscountResult result = activityCalculationDiscountResponseDto.getResult();
        if(CollectionUtils.isEmpty(result.getDiscounts())){
            return null;
        }
        if(CollectionUtils.isNotEmpty(result.getGoods())){
            for (ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods good : result.getGoods()){
                if(good.getGoodsId().equals(products.getPid())){
                    if(CollectionUtils.isEmpty(good.getDiscounts())){
                        return null;
                    }
                    List<ActivityCalculationDiscountResponseDto.CalculationDiscountResult.Goods.GoodsDiscount> discounts = good.getDiscounts();
                    OrderSettlementCreateReq orderSettlementCreateReq = new OrderSettlementCreateReq();
                    Long discount = discounts.get(0).getDiscount();
                    orderSettlementCreateReq.setProductId(products.getPid());
                    orderSettlementCreateReq.setSettlementType(createOrderAdapter.getOrderSettlementType(discounts.get(0).getType()));
                    orderSettlementCreateReq.setSettlementAmount(products.getFinalPrice()-discount);
                    orderSettlementCreateReq.setShopDiscountAmount(discount);
                    orderSettlementCreateReq.setNumber(1);
                    orderSettlementCreateReq.setShopAmount(products.getFinalPrice()-discount);
                    orderSettlementCreateReq.setExternalObjectId(discounts.get(0).getActivityCode());
                    orderSettlementCreateReq.setIsOnline(true);
                    orderSettlementCreateReq.setExternalObjectName(discounts.get(0).getActivityName());
                    orderSettlementCreateReq.setNote(result.getDiscounts().get(0).getActivityName());
                    List<OrderSettlementCreateReq> orderSettlementCreateReqList = new ArrayList<>();
                    orderSettlementCreateReqList.add(orderSettlementCreateReq);
                    createOrderRequest.setOrderSettlementDetailList(orderSettlementCreateReqList);
                    createOrderRequest.setSettlementAmount(result.getTotalAmount());
                    createOrderRequest.setActualPayAmount(result.getTotalAmount());
                    createOrderRequest.getOrderItemList().get(0).setSettlementPrice(products.getFinalPrice()-discount);
                    createOrderRequest.getOrderItemList().get(0).setProductSharePrice(discount);
                }
            }
            return result.getStocks();
        }
        return null;
    }

    /**
     * 抖音卖券支付成功回调
     * 走自己的发券mq，支持失败补偿
     * @param orderBeans
     * @return
     */
    public String paySuccessCallbackForTiktok(PaysuccessNoticeMessage message, ConfirmOrderDto confirmOrderDto, Map<String, OrderBeanV1> orderBeans) {
        String result = this.paySuccessCallback(message, confirmOrderDto, orderBeans);
        OrderBeanV1 orderBean = orderBeans.get(OrderBeanType.SAASORDER.getCode());
        OrderInfoReqs orderInfo = new OrderInfoReqs();
        orderInfo.setOrderCode(orderBean.getOid());
        orderInfo.setPartnerId(orderBean.getCompanyId());
        orderInfo.setAppId(orderBean.getAppId());
        orderInfo.setBizType(orderBean.getBizType());
        // 拓展字段中有卖券手机号
        orderInfo.setExtInfo(orderBean.getExtInfo());
        // 支付渠道，用于识别抖音卖的订单
        orderInfo.setPayChannelType(orderBean.getPayChannelType());
        List<OrderItemResp> orderItemList = new ArrayList<>();
        for (ProductBeanV1 productBean : orderBean.getProductList()) {
            OrderItemResp orderItemResp = new OrderItemResp();
            // 这里存的是虚拟商品信息
            orderItemResp.setExtInfo(productBean.getExtInfo());
            orderItemList.add(orderItemResp);
        }
        orderInfo.setOrderItemList(orderItemList);
        //发券mq
        sendCouponService.sendCouponMq(orderInfo);
        return result;
    }
}
