package cn.freemud.service.impl;

import cn.freemud.adapter.LightApplicationConvertToAssortmentSdkAdapter;
import cn.freemud.adapter.OrderAdapter;
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.vo.GetMemberCouponRequestVo;
import cn.freemud.entities.vo.NgsSellCouponCreateOrderVo;
import cn.freemud.entities.vo.PaysuccessNoticeMessage;
import cn.freemud.entities.vo.SellCouponCreateOrderVo;
import cn.freemud.enums.BusinessTypeEnum;
import cn.freemud.enums.OrderBeanType;
import cn.freemud.enums.ResponseResult;
import cn.freemud.enums.UserLoginChannelEnum;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.manager.BuyProductOnceManager;
import cn.freemud.redis.RedisCache;
import cn.freemud.service.CouponService;
import cn.freemud.service.business.OrderBusinessService;
import cn.freemud.service.thirdparty.StoreItemClient;
import cn.freemud.utils.LogUtil;
import cn.freemud.utils.ResponseUtil;
import com.alibaba.fastjson.JSONObject;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.application.sdk.api.base.SDKCommonBaseContextWare;
import com.freemud.application.sdk.api.constant.ResponseResultEnum;
import com.freemud.application.sdk.api.couponcenter.online.domain.ActiveDetailVO;
import com.freemud.application.sdk.api.couponcenter.online.domain.AppKeyVO;
import com.freemud.application.sdk.api.couponcenter.online.domain.DetailVO;
import com.freemud.application.sdk.api.couponcenter.online.request.ActiveBatchQueryRequest;
import com.freemud.application.sdk.api.couponcenter.online.request.CouponDetailRequest;
import com.freemud.application.sdk.api.couponcenter.online.request.PartnerRequest;
import com.freemud.application.sdk.api.couponcenter.online.response.CouponDetailResponse;
import com.freemud.application.sdk.api.couponcenter.online.service.FMActiveSdkService;
import com.freemud.application.sdk.api.couponcenter.online.service.OnlineCouponSdkService;
import com.freemud.application.sdk.api.log.ApiLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.log.ThirdPartyLog;
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.*;
import com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
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.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.response.order.QueryOrdersResponse;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import com.freemud.sdk.api.assortment.order.util.LockUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
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.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
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 {

    @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 OrderSdkAdapter orderSdkAdapter;
    @Autowired
    private RedisCache redisCache;
    @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;

    /**
     * 卖券订单创建
     */
    public BaseResponse createOrder(SellCouponCreateOrderVo requestVo){
        // 查询用户信息、校验svc卡
        AssortmentCustomerInfoVo userLoginInfoDto = checkOrder.checkOrderByMemberNew(requestVo.getSessionId(), requestVo.getCardCode());
        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())) {
            ApiLog.info("查询商品信息失败，getProductInfoDto，baseResponse",getProductInfoDto,productInfosDto);
            return ResponseUtil.error(productInfosDto.getCode().toString(),"商品不存在");
        }

        //通过商户号配置进阿波罗，识别哪些商户走仅限一次卖券业务 wanghanghang 0610
        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){
                ApiLog.info("校验用户每人每单限购一次异常",getProductInfoDto,productInfosDto);
            }
        }


//        GetProductInfoRequest request = new GetProductInfoRequest();
//        request.setChannel(requestVo.getMenuType());
//        request.setPartnerId(partnerId);
//        request.setProductInfoType(2);
//        request.setShopId(storeId);
//        request.setProductIds(Lists.newArrayList(requestVo.getSkuId()));
//        //获取商品（里面的活动）
//        com.freemud.application.sdk.api.base.BaseResponse<GetProductInfosResponse> productInfosByIds = menuService.getProductInfosByIds(request, trackingNo);
//        if(!SUCCESS.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<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);
//            }

//        }

        //卖券订单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();
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<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{
            QueryOrdersResponse.DataBean.OrderBean 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
                    buyProductOnceManager.removeCheckBuyProductOnceKey(partnerId,userId,orderBean.getProductList().get(0).getProductId());
                    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.setFaceCode(null);
        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 = "";
        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());

        createPrepayRequestDto.setOrderExtInfoDTO(orderExtInfoDto);
        return orderservice.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) {
        GetProductInfoRequest request = new GetProductInfoRequest();
        request.setChannel(menuType);
        request.setPartnerId(partnerId);
        request.setProductInfoType(2);
        request.setShopId(storeId);
        request.setProductIds(Lists.newArrayList(skuId));
        //获取商品（里面的活动）
        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<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);
            }
        }
        //转换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);
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<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 orderservice.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();
        if(UserLoginChannelEnum.ALIPAY.getCode().equals(userLoginInfoDto.getChannel())){
            orderClient = OrderClientType.ALIPAY.getIndex();
        }
        if(UserLoginChannelEnum.APP.getCode().equals(userLoginInfoDto.getChannel())){
            orderClient = OrderClientType.APP.getIndex();
        }
        //抖音小程序
        if("5".equalsIgnoreCase(channel)) {
            request.setPayChannel(PayChannelType.TIKTOKPAY.getIndex().toString());
            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);

        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());
        if("5".equalsIgnoreCase(channel)){
            request.setPayChannelType(PayChannelType.TIKTOKPAY.getIndex());
        }
        request.setPayChannel(channel);
        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, QueryOrdersResponseDto.DataBean.OrderBean> orderBeans) {
        QueryOrdersResponseDto.DataBean.OrderBean orderBean = orderBeans.get(OrderBeanType.SAASORDER.getCode());

        ConfirmOrderRequest var1 = LightApplicationConvertToAssortmentSdkAdapter.confirmOrderDtoConvertToConfirmOrderRequest(confirmOrderDto, orderBeans.get(OrderBeanType.MERMBERORDER.getCode()));
        var1.setPartnerId(orderBean.getCompanyId());
        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());
        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){
            LogUtil.error(LogThreadLocal.getTrackingNo(),"sdkPayAccessError",JSONObject.toJSONString(var1),null,e);
        }
        //支付成功直接完成
        OrderChangeStateReq request = new OrderChangeStateReq();
        request.setOrderCode(orderBean.getOid());
        request.setOrderState(NewOrderStatus.COMPLETE.getIndex());
        request.setOperator(orderBean.getUserName());
        request.setRemark("已完成");
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse 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);
    }




    /**
     * 查询券详情
     *
     * @param partnerId
     * @param codes
     * @param trackingNo
     * @return
     */
    private List<DetailVO> getCouponsDetail(String partnerId, String storeId, List<String> codes, String trackingNo) {
        String appKey = getAppKey(partnerId, trackingNo);
        if (StringUtils.isEmpty(appKey)) {
            return null;
        }
        CouponDetailRequest couponDetailRequest = new CouponDetailRequest();
        couponDetailRequest.setCodes(codes);
        couponDetailRequest.setMerchantId(partnerId);
        couponDetailRequest.setPartnerId(partnerId);
        // 券码新增参数：组织机构
        couponDetailRequest.setChannelIdList(this.getOrgIds(partnerId, storeId));
        OnlineCouponSdkService onlineCouponSdkService = SDKCommonBaseContextWare.getBean(OnlineCouponSdkService.class);
        com.freemud.application.sdk.api.base.BaseResponse<CouponDetailResponse> couponDetailResponse = onlineCouponSdkService.allDetail(couponDetailRequest, appKey, trackingNo);
        if (couponDetailResponse == null || !SUCCESS.equals(couponDetailResponse.getCode()) || couponDetailResponse.getData() == null || CollectionUtils.isEmpty(couponDetailResponse.getData().getDetails())) {
            return null;
        }
        return couponDetailResponse.getData().getDetails();
    }

    private Long pointToFen(double price) {
        DecimalFormat df = new DecimalFormat("#.00");
        price = Double.valueOf(df.format(price));
        long money = (long) (price * 100);
        return money;
    }

}
