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.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.OrderBeanType;
import cn.freemud.enums.ResponseResult;
import cn.freemud.enums.UserLoginChannelEnum;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.redis.RedisCache;
import cn.freemud.service.CouponService;
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.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.enums.NewOrderStatus;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.application.sdk.api.ordercenter.enums.OrderType;
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.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.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.request.order.ConfirmOrderRequest;
import com.freemud.sdk.api.assortment.order.request.order.OrderProductAddInfoDto;
import com.freemud.sdk.api.assortment.order.request.order.ProductBindingCouponType;
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.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.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;

/**
 * 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
@Slf4j
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;


    @Value("${coupon.app.id}")
    private String appId;

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


    private final String SUCCESS = "100";

    private final String ngsCouponProductId = "76161384";

    /**
     * 卖券订单创建
     */
    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();
        //查询门店信息
        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);

        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);
            }
        }

        CreateOrderRequest createOrderRequest = convent2NEWCreateOrderRequest(requestVo,userLoginInfoDto,productInfosByIds.getData(),activeDetailVOS,storeResponse.getBizVO());
        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.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);
    }


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

    private CreateOrderRequest convent2NEWCreateOrderRequest(SellCouponCreateOrderVo requestVo,AssortmentCustomerInfoVo userLoginInfoDto,
                                                             GetProductInfosResponse productInfosResponse,List<ActiveDetailVO> activeDetailVOS,
                                                             StoreResponse.BizVO storeInfo){
        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();
        request.setOrderClient(orderClient);
        request.setPartnerId(partnerId);
        request.setStoreId(requestVo.getShopId());
        //买券虚拟订单
        request.setBizType(6);
        //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(requestVo.getCardCode())){
            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(requestVo.getSkuId());
        orderItemCreateReq.setProductSpec(requestVo.getSkuId());
        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());
        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(ngsCouponProductId);
        orderItemCreateReq.setProductSpec(ngsCouponProductId);
        orderItemCreateReq.setProductName("卖券虚拟商品");
        orderItemCreateReq.setProductSpecName("卖券虚拟商品");
        orderItemCreateReq.setProductSeq(1);
        orderItemCreateReq.setProductCode(ngsCouponProductId);
        orderItemCreateReq.setThirdProductId("");
        orderItemCreateReq.setProductQuantity(1);

        OrderProductAddInfoDto orderProductAddInfoDto = new OrderProductAddInfoDto();
        List<ProductBindingCouponType> productBindingCoupons = new ArrayList<>();
        ProductBindingCouponType productBindingCouponType2 = new ProductBindingCouponType();
        productBindingCouponType2.setActivityCode(active.getActiveCode());
        productBindingCouponType2.setNum(1);
        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 = orderCenterSdkService.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;
    }

}
