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

import cn.freemud.adapter.*;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.base.util.DateUtil;
import cn.freemud.constant.OrderRefundConstant;
import cn.freemud.constant.RedisKeyConstant;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.bo.CreateOrderBONew;
import cn.freemud.entities.dto.PayAccessResponse;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.activity.PayGiftCheckAndJoinResponseDto;
import cn.freemud.entities.dto.activity.PayGiftCheckAndJoinResponseObj;
import cn.freemud.entities.dto.activity.PayGitCheckAndJoinRequestDto;
import cn.freemud.entities.dto.blacklist.BlacklistDto;
import cn.freemud.entities.dto.coupon.CheckAndCancelRequest;
import cn.freemud.entities.dto.coupon.CheckAndCancelResponseDTO;
import cn.freemud.entities.dto.coupon.CouponResponseDTO;
import cn.freemud.entities.dto.delivery.*;
import cn.freemud.entities.dto.ecology.SendMessageRequest;
import cn.freemud.entities.dto.openplatform.QueryInvoiceConfigRequest;
import cn.freemud.entities.dto.order.*;
import cn.freemud.entities.dto.pay.InvoiceCreateRequest;
import cn.freemud.entities.dto.pay.OrderInvoiceRequest;
import cn.freemud.entities.dto.product.AttributeValue;
import cn.freemud.entities.dto.product.GroupDetail;
import cn.freemud.entities.dto.product.ProductAttributeGroup;
import cn.freemud.entities.dto.product.ProductGroup;
import cn.freemud.entities.dto.promotion.QueryHistoryGroupVO;
import cn.freemud.entities.dto.shoppingCart.CollageOrderDto;
import cn.freemud.entities.dto.shoppingCart.NewShoppingCartClearDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.dto.store.GetStoreListbyCodesRequest;
import cn.freemud.entities.dto.store.StoreBaseResponseDto;
import cn.freemud.entities.dto.store.StoreListResponse;
import cn.freemud.entities.dto.store.StoreMixResponseDto;
import cn.freemud.entities.dto.user.UserBaseResponsDTO;
import cn.freemud.entities.dto.user.UserCouponCheckRequest;
import cn.freemud.entities.vo.*;
import cn.freemud.entities.vo.order.*;
import cn.freemud.enums.*;
import cn.freemud.handler.MemberBlacklistHandler;
import cn.freemud.handler.WeChatLiveMsgHandle;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.management.entities.dto.request.BatchOrderRefundV2Request;
import cn.freemud.management.entities.dto.request.order.OrderManagerRequest;
import cn.freemud.management.entities.dto.request.pay.PayRefundRequestDto;
import cn.freemud.management.entities.dto.response.activity.GroupWorkRefundResponse;
import cn.freemud.management.entities.dto.response.pay.OrderRefundResponse;
import cn.freemud.management.entities.dto.response.pay.PayBatchRefundResponse;
import cn.freemud.management.entities.dto.response.pay.PayRefundResponse;
import cn.freemud.management.enums.AfterSalesApplyClientEnum;
import cn.freemud.management.enums.AfterSalesRefunStateEnum;
import cn.freemud.management.enums.SettlementTypeEnum;
import cn.freemud.management.intercept.OrderServiceException;
import cn.freemud.management.service.adapter.OrderManagerAdapter;
import cn.freemud.management.service.handle.ActivityHandle;
import cn.freemud.management.service.handle.OrderVerifyHandle;
import cn.freemud.management.service.handle.PaymentHandle;
import cn.freemud.management.service.handle.StockHandle;
import cn.freemud.manager.OrderManager;
import cn.freemud.manager.OrderTackCodeManager;
import cn.freemud.manager.SpellGroupOrderDataManager;
import cn.freemud.redis.RedisCache;
import cn.freemud.service.CouponActivityService;
import cn.freemud.service.Orderservice;
import cn.freemud.service.business.OrderBusinessService;
import cn.freemud.service.customer.MemberInfoManager;
import cn.freemud.service.order.OrderRelationFactory;
import cn.freemud.service.order.OrderRelationService;
import cn.freemud.service.thirdparty.*;
import cn.freemud.utils.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freemud.api.assortment.datamanager.entity.db.AssortmentCloudPrinter;
import com.freemud.api.assortment.datamanager.entity.db.AssortmentOpenPlatformPartnerConfig;
import com.freemud.api.assortment.datamanager.entity.db.AssortmentOpenPlatformWxappAuthorizer;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.api.assortment.datamanager.enums.IappIdType;
import com.freemud.api.assortment.datamanager.manager.AssortmentCloudPrinterManager;
import com.freemud.api.assortment.datamanager.manager.AssortmentOpenPlatformPartnerConfigManager;
import com.freemud.api.assortment.datamanager.manager.AssortmentOpenPlatformWxappAuthorizerManager;
import com.freemud.api.assortment.datamanager.manager.customer.AssortmentCustomerInfoManager;
import com.freemud.api.assortment.datamanager.meal.MealCacheManager;
import com.freemud.application.sdk.api.constant.ResponseConstant;
import com.freemud.application.sdk.api.constant.ResponseResultEnum;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.common.OrderAndShoppingCommonRedisKey;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.entities.v1.RefundBeanV1;
import com.freemud.application.sdk.api.ordercenter.enums.*;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.OrderStatusV1;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.OrderTypeV1;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.*;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.OrderStatusV1;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.OrderTypeV1;
import com.freemud.application.sdk.api.ordercenter.request.*;
import com.freemud.application.sdk.api.ordercenter.request.carpark.ParkingOrderCreateReq;
import com.freemud.application.sdk.api.ordercenter.response.BaseDownLoadResponse;
import com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp;
import com.freemud.application.sdk.api.ordercenter.response.OrderCountResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.AfterSalesOrderResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderSettlementResp;
import com.freemud.application.sdk.api.ordercenter.service.OrderDownLoadSdkService;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
import com.freemud.application.sdk.api.storecenter.request.GetListByCodesRequest;
import com.freemud.application.sdk.api.storecenter.response.GetListByCodesResponse;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import com.freemud.application.sdk.api.structure.request.PushMessageNoticeDto;
import com.freemud.application.sdk.api.structure.service.MessageCenterClient;
import com.freemud.sdk.api.assortment.message.enums.MessageEventType;
import com.freemud.sdk.api.assortment.message.request.MessagePushOrderTemplateRequest;
import com.freemud.sdk.api.assortment.message.request.MessageTemplateRequest;
import com.freemud.sdk.api.assortment.message.service.IMessageTemplatePushService;
import com.freemud.sdk.api.assortment.order.constant.OrderRedisKeyConstant;
import com.freemud.sdk.api.assortment.order.entities.OrderRefundConfigEntity;
import com.freemud.sdk.api.assortment.order.enums.AutoOrderConfigTime;
import com.freemud.sdk.api.assortment.order.enums.OperationClientEnum;
import com.freemud.sdk.api.assortment.order.enums.QueryOrderAccountType;
import com.freemud.sdk.api.assortment.order.enums.StoreDeliveryMethod;
import com.freemud.sdk.api.assortment.order.request.order.*;
import com.freemud.sdk.api.assortment.order.response.order.*;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import com.freemud.sdk.api.assortment.order.util.LockUtils;
import com.freemud.sdk.api.assortment.order.vo.ProductGroupVo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
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.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.util.StringUtil;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static cn.freemud.constant.OrderRefundConstant.ALLOW_REFUND;


@Service
public class OrderServiceImpl implements Orderservice {

    private final Integer RESPONSE_SUCCESS_CODE = 100;
    private static final Integer MULITI_RESPONSE = 200;
    private static final String SUCCESS = "SUCCESS";

    private static Gson gson = new Gson();


    /**
     * coco商户
     */
//    @Value("#{'${coco.partnerId}'.split(',')}")
//    private List<String> cocoPartnerId;
    @Value("#{'${hls.partnerId}'.split(',')}")
    private List<String> hlsPartnerId;
    @Value("#{'${order.delete.partnerId}'.split(',')}")
    private List<String> deletePartnerId;
    @Value("#{'${order.not.automatic.twist.partnerId}'.split(',')}")
    private List<String> notAutomaticTwistPartnerId;
    @Value("${order.not.automatic.twist.time}")
    private Integer notAutomaticTwistTime;

    @Value("${query.order.es:true}")
    private Boolean queryOrderEs;


    @Autowired
    private AssortmentCloudPrinterManager cloudPrinterManager;
    @Autowired
    private FMAssistantCloudPrintClient fmAssistantCloudPrintClient;
    @Autowired
    private MessageCenterClient messageNoticeClient;
    @Autowired
    private PromotionActivityClient promotionActivityClient;
    @Autowired
    private ShoppingCartClient shoppingCartClient;
    @Autowired
    private CustomerApplicationClient customerApplicationClient;
    @Autowired
    private ItemServiceImpl itemService;
    @Autowired
    private CouponActivityService couponActivityService;
    @Autowired
    private MessageNoticeAdapter messageNoticeAdapter;
    @Autowired
    private OrderAdapter orderAdapter;
    @Autowired
    private CouponAdapter couponAdapter;
    @Autowired
    private MealCacheManager mealCacheManager;
    //聚合订单服务
    @Autowired
    private OrderCenterSdkService orderCenterSdkService;
    //门店SDK
    @Autowired
    private StoreCenterService storeCenterService;
    @Autowired
    @Qualifier("messageTemplatePushOrderService")
    private IMessageTemplatePushService<MessagePushOrderTemplateRequest> messageTemplatePushService;
    @Autowired
    private AssortmentCustomerInfoManager customerInfoManager;
    @Autowired
    private CheckOrder checkOrder;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ActivityApplicationClient activityApplicationClient;
    @Autowired
    private AssortmentOpenPlatformWxappAuthorizerManager wxappAuthorizerManager;
    @Autowired
    private OrderAdapterServiceImpl orderAdapterService;
    @Autowired
    private OrderSdkService orderSdkService;
    @Autowired
    private OrderDownLoadSdkService orderDownLoadSdkService;
    @Autowired
    private DeliveryFeiginClient deliveryFeiginClient;

    @Autowired
    private EcologyAdminApplicationClient ecologyAdminApplicationClient;

    @Autowired
    private AssortmentOpenPlatformPartnerConfigManager openPlatformPartnerConfigManager;

    @Autowired
    private OrderRelationFactory orderRelationFactory;

    @Autowired
    private SpellGroupOrderDataManager spellGroupOrderDataManager;

    @Autowired
    private ActivityHandle activityHandle;

    @Autowired
    private OrderTackCodeManager orderTackCodeManager;

    @Autowired
    private OrderBusinessService orderBusinessService;

    @Autowired
    private OrderManager orderManager;
    @Autowired
    private MemberInfoManager memberInfoManager;

    @Autowired
    private OrderServiceClient orderServiceClient;

    @Autowired
    OrderInvoiceAdapter orderInvoiceAdapter;

    @Autowired
    private OrderQueueService orderQueueService;
    @Autowired
    private PayServiceImpl payServiceImpl;
    @Autowired
    private ComPayClient comPayClient;
    @Autowired
    private MicroOpenplatformClient microOpenplatformClient;

    @Autowired
    private WeChatLiveMsgHandle weChatLiveMsgHandle;

    @Autowired
    private StoreClient storeClient;

    @Autowired
    private CouponOnlineClient couponOnlineClient;
    @Autowired
    private CustomerExtendClient customerExtendClient;
    @Autowired
    private OrderVerifyHandle orderVerifyHandle;
    @Autowired
    private PaymentHandle paymentHandle;
    @Autowired
    private StockHandle stockHandle;

    @Autowired
    private MemberBlacklistHandler memberBlacklistHandler;

    @Autowired
    private OrderManagerAdapter orderManagerAdapter;

    @Value("${sellcoupon.test.order.refund.fail:}")
    private Integer testOrderRefundFail;
//    @Override
//    public BaseResponse checkBeforeCreateOrder(CheckBeforeCreateOrderRequestVo requestVo) {
//        String trackingNo = LogThreadLocal.getTrackingNo();
//        AssortmentCustomerInfoVo userInfo = customerInfoManager.getCustomerInfoByObject(requestVo.getSessionId());
//        if (userInfo == null || StringUtils.isEmpty(userInfo.getMemberId())) {
//            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
//        }
//        StoreResponse storeResponse = checkOrder.getStoreInfo(requestVo.getPartnerId(), requestVo.getShopId(), trackingNo);
//        if (storeResponse == null || storeResponse.getBizVO() == null) {
//            return ResponseUtil.error(ResponseResult.STORE_NOT_FOUND);
//        }
//        StoreResponse.BizVO storeInfo = storeResponse.getBizVO();
//        CheckBeforeCreateOrderResponseVo responseVo = new CheckBeforeCreateOrderResponseVo();
//        Integer maxOrderQuantity = storeInfo.getMaxOrderQuantity();
//        if (maxOrderQuantity == null) {
//            maxOrderQuantity = 100;
//        }
//        // 调用文顺接口获取队列长度
//        BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
//        baseQueryOrderRequest.setPartnerId(requestVo.getPartnerId());
//        baseQueryOrderRequest.setShopId(requestVo.getShopId());
//        baseQueryOrderRequest.setTrackingNo(trackingNo);
//        BaseOrderResponse queryStoreOrderQuantity = orderCenterSdkService.queryStoreOrderQuantity(baseQueryOrderRequest);
//        QueryStoreOrderQuantityResponseDto responseDto = new QueryStoreOrderQuantityResponseDto();
//        BeanUtil.convertBean(queryStoreOrderQuantity, responseDto);
//
//        if (!RESPONSE_SUCCESS_CODE.equals(responseDto.getErrcode())) {
//            return ResponseUtil.error(ResponseResult.ORDER_QUERY_QUANTITYR_ERROR);
//        }
//        Integer lineNumber = Integer.parseInt(responseDto.getData());
//        // 判断最大接单量和队列长度的关系
//        if (maxOrderQuantity > lineNumber) {
//            responseVo.setWhetherMaxOrderQuantity(false);
//            responseVo.setBeforeNumber(lineNumber);
//            responseVo.setWarningInfo("");
//        } else {
//            responseVo.setWhetherMaxOrderQuantity(true);
//            String beforeMessage = "您前面排队超过";
//            String afterMessage = "单，出餐时间稍长，是否继续提交？";
//            responseVo.setBeforeNumber(lineNumber);
//            responseVo.setWarningInfo(beforeMessage + lineNumber + afterMessage);
//        }
//        return ResponseUtil.success(responseVo);
//    }

    // 原来saas
    @Override
    public BaseResponse createOrder(CreateOrderBONew createOrderBO) {
        //创建订单前参数校验与数据获取
        BaseResponse checkResponse = checkOrder.checkCreateOrderInfo(createOrderBO);
        if (checkResponse != null && !ResponseResult.SUCCESS.getCode().equals(checkResponse.getCode())) {
            return checkResponse;
        }
        //创建订单调用集成，不区分订单类型
        BaseResponse createOrderOperateDtoResponse = this.sdkCreateOrder(createOrderBO);
        if (createOrderOperateDtoResponse == null || !ResponseResult.SUCCESS.getCode().equals(createOrderOperateDtoResponse.getCode()) || createOrderOperateDtoResponse.getResult() == null) {
            return createOrderOperateDtoResponse;
        }
        CreateOrderOperateDto createOrderOperateDto = (CreateOrderOperateDto) createOrderOperateDtoResponse.getResult();
        //创建支付
        CreatePrepayRequestDto createPrepayRequestDto = orderAdapter.convertToCreatePrepayRequestDto(createOrderBO, createOrderOperateDto);
        return ResponseUtil.success(payServiceImpl.createPrepayOrder(createPrepayRequestDto));
    }

    @Override
    public String paySuccessCallback(PaysuccessNoticeMessage message, ConfirmOrderDto confirmOrderDto, Map<String, OrderBeanV1> orderBeans) {
        OrderBeanV1 orderBean = orderBeans.get(OrderBeanType.SAASORDER.getCode());
        String oid = StringUtils.isNotEmpty(orderBean.getParentCode()) && !"0".equals(orderBean.getParentCode()) ? orderBean.getParentCode() : orderBean.getOid();
        String partnerId = orderBean.getCompanyId();
        String userId = orderBean.getUserId();
        String storeId = orderBean.getShopId();
        orderBean.setPayVoucher(message.getOut_trade_no());
        //编辑订单信息，获取openid，用于退款
        String extInfo = orderBean.getExtInfo();
        OrderExtInfoDto orderExtInfoDto = null;
        String wxappid = "";
        String sessionId = "";
        String openid = "";
        String ruleId = "";
        String payCode = "";
        if (StringUtils.isNotBlank(extInfo)) {
            orderExtInfoDto = gson.fromJson(extInfo, OrderExtInfoDto.class);
            if (orderExtInfoDto != null && StringUtils.isNotBlank(orderExtInfoDto.getOpenid())) {
                openid = orderExtInfoDto.getOpenid();
                wxappid = orderExtInfoDto.getAppid();
                sessionId = orderExtInfoDto.getSessionId();
                ruleId = orderExtInfoDto.getRuleId();
            }
            if (orderExtInfoDto != null && StringUtils.isNotBlank(orderExtInfoDto.getPayCode())
                    && Arrays.asList(PayChannel.ALIPAY.getCode(), PayChannel.WXPAY.getCode()).contains(orderExtInfoDto.getPayCode())) {
                payCode = orderExtInfoDto.getPayCode();
            }
        }
        // 如果订单状态不是未支付，返回信息
        if (!PayStatus.NOT_PAY.getCode().equals(orderBean.getPayStatus()) || !NewOrderStatus.PENDING_PAYMENT.getIndex().equals(orderBean.getStatusV2())) {
            return sendPaySuccessNoticeMessage();
        }

        String takeCode;
        String daySeq;
        PayAccessResponse payAccessResponse;
        ConfirmOrderRequest var1 = LightApplicationConvertToAssortmentSdkAdapter.confirmOrderDtoConvertToConfirmOrderRequest(confirmOrderDto, orderBeans.get(OrderBeanType.MERMBERORDER.getCode()));
        var1.setPartnerId(partnerId);
        var1.setUserId(userId);
        var1.setStoreId(storeId);
        var1.setOrderType(orderBean.getOrderType());
        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.setMealCodeRule(getMealCodeRule(wxappid));
        if (StringUtils.isNotBlank(payCode)) {
            var1.setPayChannel(payCode);
            //fisherman 看着会出现NPE 就给修改了下
            PayChannel byCode = PayChannel.getByCode(payCode);
            var1.setPayChannelName(Objects.isNull(byCode) ? null : byCode.getDesc());
        }
        if (orderBean.getGmtExpect() != null && orderBean.getGmtExpect() != 0) {
            var1.setExpectTime(DateUtil.convert2String(new Date(orderBean.getGmtExpect()), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        }
        //合阔pos 商户不接单自动退款时间
        if (CollectionUtils.isNotEmpty(notAutomaticTwistPartnerId) && notAutomaticTwistPartnerId.contains(partnerId)) {
            var1.setNotAutomaticTwistTime(notAutomaticTwistTime);
        }
        String pickUpGoodsNo = orderTackCodeManager.generateTackCode(orderBean.getOrderType(), partnerId, storeId, var1, OrderTackCodeFactory.getByOrderClient(orderBean.getOrderClient()).getGenerateTackCodeFunc());
        var1.setPickUpGoodsNo(pickUpGoodsNo);
        // 订单支付成功
        var1.setExtInfo(extInfo);
        com.freemud.sdk.api.assortment.order.response.order.PayAccessResponse payAccessRes = orderBusinessService.payAccess(var1);
        String string2 = JSONObject.toJSONString(payAccessRes);
        JSONObject jsonObject2 = JSONObject.parseObject(string2);
        payAccessResponse = jsonObject2.toJavaObject(PayAccessResponse.class);
        // 添加幂等处理，若订单是已支付成功状态，直接返回成功
        if (!RESPONSE_SUCCESS_CODE.equals(payAccessResponse.getErrcode())) {
            OrderBeanV1 saasOrder = getOrderBeanByOrderId(confirmOrderDto.getOrderId()).get(OrderBeanType.SAASORDER.getCode());
            if (saasOrder != null && (!PayStatus.NOT_PAY.getCode().equals(saasOrder.getPayStatus()) || !NewOrderStatus.PENDING_PAYMENT.getIndex().equals(saasOrder.getStatusV2()))) {
                return sendPaySuccessNoticeMessage();
            }
            //orderRefund(orderBean, "订单异常退款", openid, oid);
            return gson.toJson(message);
        }
        // TODO 订单序号替换取餐码显示
        takeCode = payAccessResponse.getData().getTakeCode();
        daySeq = payAccessResponse.getData().getDaySeq();

        if (null != orderBean.getMarketingType() && MarketTypeEnum.COLLAGE.getIndex().byteValue() == orderBean.getMarketingType()) {
            // 更新拼单购物车状态
            CollageOrderDto collageOrderDto = new CollageOrderDto();
            collageOrderDto.setSessionId(StringUtils.isBlank(sessionId) ? oid : sessionId);
            collageOrderDto.setPartnerId(partnerId);
            collageOrderDto.setShopId(storeId);
            collageOrderDto.setCreateCollageUserId(userId);
            collageOrderDto.setOrderCode(oid);
            collageOrderDto.setStatus(1);
            shoppingCartClient.updateCollageOrder(collageOrderDto);
        } else {
            //TODO 清空购物车
            NewShoppingCartClearDto newShoppingCartClearDto = new NewShoppingCartClearDto();
            newShoppingCartClearDto.setPartnerId(partnerId);
            newShoppingCartClearDto.setShopId(storeId);
            newShoppingCartClearDto.setUserId(userId);
            newShoppingCartClearDto.setAppId(wxappid);
            newShoppingCartClearDto.setSessionId(sessionId);
            newShoppingCartClearDto.setOperationType(1);
            // fisherman 清楚 爱马哥蛋糕预定 类型购物车 bizType = 7
            newShoppingCartClearDto.setBizType(orderBean.getBizType());
            //shoppingCartClient.clearShoppingCart(newShoppingCartClearDto);

            /**
             主要 根据 ShoppingCartNewServiceImpl   次要 ShoppingCartMallServiceImpl
             这里不处理商城
             根据sessionId 判断是否是 围餐 , 标准点餐
             看看围餐 是不是也可以 直接处理
             */
            AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(sessionId);
            if (Objects.nonNull(userLoginInfoDto)) {
                String iappId = userLoginInfoDto.getIappId();
                if (IappIdType.WC_XCX.getCode().equals(iappId)) {
                    // 围餐依然调用接口处理
                    shoppingCartClient.clearShoppingCart(newShoppingCartClearDto);
                } else {
                    // saas订单, 直接订单服务清空购物车
                    redisCache.delete(OrderAndShoppingCommonRedisKey.getShoppingCartGoodsKey(partnerId, storeId, userId, orderBean.getBizType()));
                }
            }
        }

        if (StringUtils.isNotBlank(daySeq) && orderExtInfoDto != null && !OrderTypeV1.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
            String storeAddress = StringUtils.isNotBlank(orderBean.getAddress()) ? orderBean.getAddress() : "";
            orderBean.setAddress(storeAddress);
            orderBean.setOtherCode(takeCode);
            //发送支付成功模板消息
            this.sendPaySuccessMessage(orderBean);
        }
        // 有云打印机 打印小票，杯贴
        try {
            List<AssortmentCloudPrinter> storePrinters = cloudPrinterManager.getStorePrintersNew(partnerId, storeId);
            if (null != storePrinters && storePrinters.size() > 0) {
                boolean printerStatus = false;
                for (AssortmentCloudPrinter cloudPrinter : storePrinters) {
                    if (null != cloudPrinter.getStatus() && cloudPrinter.getStatus() == 1) {
                        printerStatus = true;
                    }
                }
                //在线打印
                if (printerStatus) {
                    OrderPrintDto orderPrintDto = orderAdapter.convert2OrderPrintDto(orderBean);
                    orderPrintDto.setDaySeq(daySeq);
                    orderPrintDto.setOtherCode(takeCode);
                    orderQueueService.asynchronousPrint(orderPrintDto);
                }
            }
        } catch (Exception e) {
            AppLogUtil.errorLog("cloudPrint_error", null, null, e);
        }

        // 开通会员卡
        if (StringUtils.isNotBlank(ruleId)) {
            this.activateMemberCard(partnerId, ruleId, oid, userId, storeId, orderBean.getShopName());
        }
        //支付回调成功标记
        redisCache.save(RedisKeyConstant.KGD_PAYMENT_CALLBACK_FMID + message.getOut_trade_no(), message.getOut_trade_no(), 10L, TimeUnit.MINUTES);
        if (message.getSource() != null && message.getSource().equals(PaySuccessSource.OUTSIDE.getSource())) {
            verificationCoupon(message.getTrans_id(), message.getThirdPartTradeNo());
        }
        return sendPaySuccessNoticeMessage();
    }

    public Map<String, OrderBeanV1> getOrderBeanByOrderId(String orderId) {
        // 订单查询：若结果集只有一个orderBean，则为普通订单，否则为会员卡订单（父子订单）
        Map<String, OrderBeanV1> result = new HashMap<>();
        QueryRelationOrderByIdResponseDto queryOrderByIdResponseDto = getQueryRelationOrderByIdResponseDto(orderId);
        if (CollectionUtils.isEmpty(queryOrderByIdResponseDto.getData())) {
            return result;
        }
        if (1 == queryOrderByIdResponseDto.getData().size()) {
            result.put(OrderBeanType.SAASORDER.getCode(), queryOrderByIdResponseDto.getData().get(0));
        } else {
            List<OrderBeanV1> saasOrderBeans = queryOrderByIdResponseDto.getData().stream().filter(order -> order.getBizType().equals(1)).collect(Collectors.toList());
            List<OrderBeanV1> memberOrderBeans = queryOrderByIdResponseDto.getData().stream().filter(order -> order.getBizType().equals(3) && !order.getIsParent()).collect(Collectors.toList());
            List<OrderBeanV1> fatherOrderBeans = queryOrderByIdResponseDto.getData().stream().filter(order -> order.getBizType().equals(2) && order.getIsParent()).collect(Collectors.toList());
            result.put(OrderBeanType.SAASORDER.getCode(), CollectionUtils.isNotEmpty(saasOrderBeans) ? saasOrderBeans.get(0) : null);
            result.put(OrderBeanType.MERMBERORDER.getCode(), CollectionUtils.isNotEmpty(memberOrderBeans) ? memberOrderBeans.get(0) : null);
            result.put(OrderBeanType.FATHERORDER.getCode(), CollectionUtils.isNotEmpty(fatherOrderBeans) ? fatherOrderBeans.get(0) : null);
        }
        return result;
    }

    /**
     * 开通会员卡
     *
     * @param partnerId 商户号
     * @param ruleId    会员规则ID
     * @param oid       订单号
     * @param userId    用户ID
     * @param storeId   门店id
     * @param shopName  门店名称
     */
    private void activateMemberCard(String partnerId, String ruleId, String oid, String userId, String storeId, String shopName) {
        PurchasePaidRequestDto purchasePaidRequestDto = new PurchasePaidRequestDto();
        purchasePaidRequestDto.setPartnerId(partnerId);
        purchasePaidRequestDto.setOperatorType(0);
        purchasePaidRequestDto.setRuleId(ruleId);
        purchasePaidRequestDto.setOrderId(oid);
        purchasePaidRequestDto.setMemberId(userId);
        purchasePaidRequestDto.setPromoteStoreId(storeId);
        purchasePaidRequestDto.setPromoteStoreName(shopName);
        // 尝试三次开通会员卡，中途成功则跳出
        int count = 3;
        for (int i = 1; i <= count; i++) {
            BaseResponse baseResponse = customerApplicationClient.purchasePaid(purchasePaidRequestDto);
            // 不以响应码为判断是否开通会员卡成功的标准
            if (baseResponse != null && "SUCCESS".equals(baseResponse.getResult())) {
                break;
            }
            // 尝试开通会员卡失败三次
            if (i >= count) {
                AppLogUtil.infoLog("尝试开通会员卡失败" + count + "次", JSON.toJSONString(purchasePaidRequestDto), JSON.toJSONString(baseResponse));
            }
        }
    }

    @Override
    public String newPaySuccessCallback(NewPaysuccessNoticeMessage newMessage) {
        PaysuccessNoticeMessage message = new PaysuccessNoticeMessage();
        message.setResult_code(StringUtils.isBlank(newMessage.getResultCode()) ? 0 : Integer.valueOf(newMessage.getResultCode()));
        message.setOut_trade_no(StringUtils.isBlank(newMessage.getTransactionCode()) ? "" : newMessage.getTransactionCode());
        message.setTrans_id(StringUtils.isBlank(newMessage.getTransId()) ? "" : newMessage.getTransId());
        message.setTotal_fee(newMessage.getTotalAmount() == null ? 0 : newMessage.getTotalAmount());
        message.setOpenid(StringUtils.isBlank(newMessage.getOpenId()) ? "" : newMessage.getOpenId());
        message.setPlatform_coupon(newMessage.getPlatformCoupon() == null ? 0 : newMessage.getPlatformCoupon());
        message.setMerchant_coupon(newMessage.getMerchantCoupon() == null ? 0 : newMessage.getMerchantCoupon());
        message.setPaid_no(newMessage.getThirdPartTradeNo());
        message.setEndTransId(newMessage.getEndTransId());
        message.setPlatformMchId(newMessage.getPlatformMchId());
        message.setTerminalId(newMessage.getAppId());
        message.setRuleId(newMessage.getRuleId());
        message.setSource(PaySuccessSource.OUTSIDE.getSource());
        message.setThirdPartTradeNo(newMessage.getThirdPartTradeNo());
        message.setSvcPayItems(newMessage.getPayItems());
        String res = orderAdapterService.paySuccessCallback(message);
        JSONObject jsonObject = JSONObject.parseObject(res);
        if (jsonObject.containsKey("code")) {
            Integer code = (Integer) jsonObject.get("code");
            if (Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_0, code) || Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS, code)) {
                return newSendPaySuccessNoticeMessage();
            } else {
                return res;
            }
        }
        return orderAdapter.newSendPayFailedMessage();
    }

    private String verificationCoupon(String transId, String thirdPartTradeNo) {
        String orderId = redisCache.getValue(RedisUtil.getPaymentTransIdOrderKey(transId));
        if (StringUtils.isNotBlank(orderId)) {
            transId = orderId;
        }
        QueryRelationOrderByIdResponseDto queryOrderByIdResponseDto = getQueryRelationOrderByIdResponseDto(transId);
        if (queryOrderByIdResponseDto.getData() == null || !Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS, queryOrderByIdResponseDto.getErrcode())) {
            return refundFaileMessage("order query fail" + queryOrderByIdResponseDto);
        }
        OrderBeanV1 orderBean = new OrderBeanV1();
        if (1 == queryOrderByIdResponseDto.getData().size()) {
            orderBean = queryOrderByIdResponseDto.getData().get(0);
        } else {
            List<OrderBeanV1> orderBeans = queryOrderByIdResponseDto.getData().stream().filter(order -> order.getBizType().equals(1)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(orderBeans)) {
                orderBean = orderBeans.get(0);
            }
        }
        orderBean.setThirdPartTradeNo(thirdPartTradeNo);
        //核销券
        BaseResponse baseResponse = couponActivityService.verificationCoupon(orderBean, CouponReqType.WRITEOFF);
        return "核销券码返回结果" + baseResponse.getCode() + "," + baseResponse.getMessage();
    }

    @Override
    public String refundNotifyCallback(RefundNotifyCallbackRequestVo requestVo) {
        //混合支付需要从换从中获取订单号码，正常支付TransId = orderId
        String orderId = redisCache.getValue(RedisUtil.getPaymentTransIdOrderKey(requestVo.getTransId()));
        if (StringUtils.isNotEmpty(orderId)) {
            requestVo.setTransId(orderId);
        }
        String trackingNo = LogThreadLocal.getTrackingNo();
        if (StringUtils.isBlank(requestVo.getTransId())) {
            //订单号不能为空
            return refundFaileMessage("transId is can not empty");
        }
        Integer refundStatus = requestVo.getRefundStatus();
        if (!Objects.equals(refundStatus, ResponseCodeConstant.RESPONSE_SUCCESS)) {
            //只有退款成功更新状态.其他情况不处理
            return refundFaileMessage("pay refundStatus is not 100,refundStatus=" + refundStatus);
        }
        //查询订单详情
        QueryRelationOrderByIdResponseDto queryOrderByIdResponseDto = getQueryRelationOrderByIdResponseDto(requestVo.getTransId());
        if (queryOrderByIdResponseDto.getData() == null || !Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS, queryOrderByIdResponseDto.getErrcode())) {
            return refundFaileMessage("order query fail " + queryOrderByIdResponseDto);
        }

        OrderBeanV1 orderBean = new OrderBeanV1();
        if (1 == queryOrderByIdResponseDto.getData().size()) {
            orderBean = queryOrderByIdResponseDto.getData().get(0);
        } else {
            List<OrderBeanV1> orderBeans = queryOrderByIdResponseDto.getData().stream().filter(order -> order.getBizType().equals(1)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(orderBeans)) {
                orderBean = orderBeans.get(0);
            }
        }
        if (Objects.equals(NewOrderStatus.CLOSED.getIndex(), orderBean.getStatusV2())) {
            return newSendPaySuccessNoticeMessage();
        }
        //无售后单，退款回掉取消订单，冲正库存等
        if (CollectionUtils.isEmpty(orderBean.getRefundList())) {
            return cancelOrder(orderBean);
        }
        //订单状态
        Integer orderRefundStatus = orderBean.getRefundList().get(0).getStatus();
        if (!Objects.equals(RefundStatus.ALREADY_REFUND.getCode(), orderRefundStatus)) {
            //不是退款中处理不处理
            return refundFaileMessage("order status is not 3,status=" + orderRefundStatus);
        }
        String afterSalesCode = orderBean.getRefundList().get(orderBean.getRefundList().size() - 1).getRid();
        //退款流水号
        BaseQueryOrderRequest request = new BaseQueryOrderRequest();
        request.setPartnerId(requestVo.getPartnerId());
        request.setOrderId(requestVo.getTransId());
        request.setAfterSalesCode(afterSalesCode);
        request.setRefundSerialNo(requestVo.getRefundId());
        request.setOperator("admin");
        request.setTrackingNo(trackingNo);
        request.setOperationClient(OperationClientEnum.STATE_6.getIndex());
        request.setRefundState(AfterSalesRefunStateEnum.STATE_4.getIndex());
        BaseOrderResponse response = orderCenterSdkService.orderRefundComplete(request);
        if (response == null || !Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS, response.getErrcode())) {
            return refundFaileMessage("orderRefundComplete fail" + response);
        }
        return newSendPaySuccessNoticeMessage();
    }

    public QueryRelationOrderByIdResponseDto getQueryRelationOrderByIdResponseDto(String oid) {
        QueryRelatedOrderByCodeRequest baseQueryOrderRequest = new QueryRelatedOrderByCodeRequest();
        baseQueryOrderRequest.setOrderCode(oid);
        baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        QueryRelatedOrderByCodeResp queryOrderByIdResponse;
        queryOrderByIdResponse = orderCenterSdkService.queryRelatedOrderByCode(baseQueryOrderRequest);
        String string = JSONObject.toJSONString(queryOrderByIdResponse);
        JSONObject jsonObject = JSONObject.parseObject(string);
        QueryRelationOrderByIdResponseDto queryOrderByIdResponseDto = jsonObject.toJavaObject(QueryRelationOrderByIdResponseDto.class);
        String orderString = JSONObject.toJSONString(queryOrderByIdResponse.getOrderBeanList());
        queryOrderByIdResponseDto.setData(JSONArray.parseArray(orderString, OrderBeanV1.class));
        return queryOrderByIdResponseDto;
    }

    @Override
    public BaseResponse queryOrders(QueryOrderVo queryOrderVo) {
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(queryOrderVo.getSessionId());
        if (userLoginInfoDto == null || StringUtils.isBlank(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        if (StringUtils.isBlank(queryOrderVo.getStartDate())) {
            if (isQueryEs(queryOrderVo.getQueryOrderStatus()) && queryOrderEs) {
                queryOrderVo.setStartDate(DateUtil.convert2String(DateUtil.addMonths(new Date(), -3), "yyyy-MM-dd"));
            } else {
                //只有发票相关的查询2个月
                if (queryOrderVo.getNeedInvoice() != null) {
                    queryOrderVo.setStartDate(DateUtil.convert2String(DateUtil.addMonths(new Date(), -2), "yyyy-MM-dd"));
                } else {
                    queryOrderVo.setStartDate(DateUtil.convert2String(DateUtil.addMonths(new Date(), -3), "yyyy-MM-dd"));
                }
            }

        }
        if (StringUtils.isBlank(queryOrderVo.getEndDate())) {
            queryOrderVo.setEndDate(DateUtil.convert2String(new Date(), "yyyy-MM-dd"));
        }
        if (queryOrderVo.getQueryOrderStatus() == null) {
            return ResponseUtil.error(ResponseResult.PARAMETER_MISSING.getCode(), "查询订单状态不能为空");
        }
//        if (queryOrderVo.getQueryOrderType() != null) {
//            if (OrderType.getByCode(queryOrderVo.getQueryOrderType()) == null) {
//                return ResponseUtil.error(ResponseResult.PARAMETER_MISSING.getCode(), "查询订单类型不存在");
//            }
//        }
        String partnerId = queryOrderVo.getPartnerId();
        String startDateStr = queryOrderVo.getStartDate() + " 00:00:00";
        String endDateStr = queryOrderVo.getEndDate() + " 23:59:59";
        Date startDate = DateUtil.convert2Date(startDateStr, "yyyy-MM-dd HH:mm:ss");
        if (startDate == null) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "查询订单开始时间格式不正确");
        }
        Date endDate = DateUtil.convert2Date(endDateStr, "yyyy-MM-dd HH:mm:ss");
        if (endDate == null) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "查询订单结束时间格式不正确");
        }

        Date checkStartDate = DateUtil.convert2Date(startDateStr, "yyyy-MM-dd");
        Date checkEndDate = DateUtil.convert2Date(new Date(), "yyyy-MM-dd");
        if (checkStartDate.getTime() < DateUtil.addMonths(checkEndDate, -3).getTime()) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "只能查询3个月内的订单信息");
        }


        String userId = userLoginInfoDto.getMemberId();
        QueryOrderDto queryOrderDto = BeanUtil.convertBean(queryOrderVo, QueryOrderDto::new);
        queryOrderDto.setPartnerId(queryOrderVo.getPartnerId());
        queryOrderDto.setStartDate(startDateStr);
        queryOrderDto.setEndDate(endDateStr);
        String channelType = this.getQueryOrderChannelType(queryOrderVo, userLoginInfoDto);
        QueryOrdersRequest queryOrdersRequest = orderAdapter.convent2QueryOrdersDto(queryOrderDto, userId, channelType);
        queryOrdersRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        queryOrdersRequest.setNeedInvoice(queryOrderVo.getNeedInvoice());
        // 查询支持查询会员合并后的所有订单
        List<String> memberIds = memberInfoManager.getMemberAllIds(partnerId, userId);
        queryOrdersRequest.setUserIds(memberIds);
        // clean userId value,use userIds field
        queryOrdersRequest.setUserId(null);
        if (Objects.equals(QueryOrderStatus.REFUND_BILL.getCode(), queryOrderVo.getQueryOrderStatus())) {
            queryOrdersRequest.setPayStatus(new Integer[]{3});//发票其他订单查询已退款
        }
        QueryOrdersResponse queryOrderResponse;
        // 订单要查3个月的，如果查询的订单状态是待取餐、未支付，则查实时，否则，查es
        if (isQueryEs(queryOrderVo.getQueryOrderStatus()) && queryOrderEs) {
            OrderConditionsReq es = new OrderConditionsReq();
            es.setPartnerId(queryOrderVo.getPartnerId());
            es.setUserId(userId);
            es.setStartTimestamp(DateTimeUtil.parseDate(startDateStr, DateTimeUtil.YYYY_MM_DD_HH_MM_SS).getTime() / 1000);
            es.setEndTimestamp(DateTimeUtil.parseDate(endDateStr, DateTimeUtil.YYYY_MM_DD_HH_MM_SS).getTime() / 1000);
            es.setPageNum(queryOrderVo.getPageNumber());
            es.setPageSize(queryOrderVo.getPageSize());
            es.setMarketingType(queryOrderVo.getMarketingType());
            OrderConditionsReq queryEs = orderAdapter.convent2QueryOrdersDtoES(es, userId, channelType, queryOrderVo.getQueryOrderStatus(), queryOrderVo.getQueryOrderType(), queryOrderVo.getQueryPayStatus());
            queryEs.setNeedInvoice(queryOrderVo.getNeedInvoice());
            queryEs.setUserIds(memberIds);
            BaseDownLoadResponse<List<OrderInfoReqs>> response = orderDownLoadSdkService.queryOrderByConditions(queryEs, LogThreadLocal.getTrackingNo());

            queryOrderResponse = orderAdapter.conventEs2queryOrderResponse(response);
        } else {
            queryOrderResponse = orderCenterSdkService.queryOrders(queryOrdersRequest);
        }

        if (queryOrderResponse == null || !RESPONSE_SUCCESS_CODE.equals(queryOrderResponse.getErrcode())) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode());
        }
        Map<String, Object> responseMap = Maps.newTreeMap();
        //用户无订单数据
        if (queryOrderResponse.getData() == null || queryOrderResponse.getData().getCount() == 0) {
            responseMap.put("count", 0);
            responseMap.put("list", new ArrayList<QueryOrderResponseVo>());
            return ResponseUtil.success(responseMap);
        }
        List<OrderBeanV1> ordersOld = queryOrderResponse.getData().getOrders();
        List<OrderBeanV1> orders = new ArrayList<>();
        Set<String> shopIds = new HashSet<>();
        // 过滤待支付订单
        if (CollectionUtils.isNotEmpty(ordersOld)) {
            for (OrderBeanV1 orderBean : ordersOld) {
                if (!(NewOrderStatus.PENDING_PAYMENT.getIndex().equals(orderBean.getStatusV2()) || PayStatus.NOT_PAY.getCode().equals(orderBean.getPayStatus()))) {
                    shopIds.add(orderBean.getShopId());
                }
                //围餐过滤掉未唤起支付的订单
                if (OrderChannelType.IWC.getCode().equals(channelType) && NewOrderStatus.PENDING_PAYMENT.getIndex().equals(orderBean.getStatusV2()) && PayStatus.NOT_PAY.getCode().equals(orderBean.getPayStatus())) {
                    // 如果已经唤起了支付则不再进行促销计算
                    boolean prePayLock = mealCacheManager.getOrderCreatePreParmentLock(userLoginInfoDto.getPartnerId(), userLoginInfoDto.getStoreId(), userLoginInfoDto.getTableNumber());
                    if (prePayLock) {
                        //已唤起支付
                        orders.add(orderBean);
                    }
                } else {
                    orders.add(orderBean);
                }
            }
        }
        String storeCodes = "";
        for (String shopId : shopIds) {
            storeCodes = shopId + "," + storeCodes;
        }
        GetStoreListbyCodesRequest request = new GetStoreListbyCodesRequest();
        request.setPartnerId(partnerId);
        request.setStoreCodes(storeCodes);
        // 查询多个门店信息
        StoreBaseResponseDto<StoreListResponse> storeBaseResponseDto = storeClient.getListByCodes(request);
        Map<String, cn.freemud.entities.dto.store.StoreResponse> storeMap = new HashMap<>();
        if (storeBaseResponseDto.getBizVO() != null && CollectionUtils.isNotEmpty(storeBaseResponseDto.getBizVO().getList())) {
            storeBaseResponseDto.getBizVO().getList().forEach(storeInfo -> {
                storeMap.put(storeInfo.getStoreCode(), storeInfo);
            });
        }
        if (CollectionUtils.isNotEmpty(orders)) {
            orders.forEach(orderBean -> {
                cn.freemud.entities.dto.store.StoreResponse storeResponseDto = storeMap.get(orderBean.getShopId());
                orderBean.setProgressBarStatus(2);
                if (storeResponseDto != null) {
                    orderBean.setShopAddress(storeResponseDto.getAddress());
                    orderBean.setShopPhone(storeResponseDto.getPhone());
                    orderBean.setShopImageUrl(storeResponseDto.getLogoUrl());
                    //默认骑手头像显示为门店首页图片
                    orderBean.setRiderPhoto(storeResponseDto.getLogoUrl());
                    orderBean.setLatitude((StringUtils.isNotBlank(storeResponseDto.getLatitude()) ? Double.valueOf(storeResponseDto.getLatitude()) : 0d));
                    orderBean.setLongitude((StringUtils.isNotBlank(storeResponseDto.getLongitude()) ? Double.valueOf(storeResponseDto.getLongitude()) : 0d));
                    orderBean.setProgressBarStatus(storeResponseDto.getProcessBarResponse() == null ? Integer.valueOf(2) : storeResponseDto.getProcessBarResponse().getStatus());
                }
                // 获取订单运单号，如果有运单则是第三方外卖单
                if (orderBean.getAddInfo() != null && StringUtils.isNotEmpty(orderBean.getAddInfo().getDeliveryId())) {
                    hasThirdDelivery(orderBean);
                }
                orderBean.setQueueIndex("");
                // 查询待取餐订单才需要查询排队人数和订单状态扭转记录
                if (QueryOrderStatus.TAKE_MEAL.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                    String returnWords = "";
                    Integer productSum = 0; //件数
                    Long pickUpTime = 0L; //预计
                    Integer totalSumTime = 0;
                    String progress = "0"; //进度
                    Integer orderProgressBarStatus = 2;
                    try {
                        if (null != storeResponseDto) {
                            String configurationStr = storeResponseDto.getConfiguration();
                            if (StringUtils.isNotEmpty(configurationStr)) {
                                StoreResponse.Configuration configuration = JSONObject.parseObject(configurationStr).toJavaObject(StoreResponse.Configuration.class);
                                if (null != configuration) {
                                    orderProgressBarStatus = configuration.getOrderProgressBarStatus();
                                    ; //默认关闭
                                    //订单状态为已接单并且无售后单展示进度条
                                    if (NewOrderStatus.ACCEPTED.getIndex() == orderBean.getStatusV2() && null == orderBean.getAfterSalesOrderResp() && null != orderProgressBarStatus && null != configuration.getTurnOnTimeOfMaking()) {
                                        // 查询订单的排队人数
                                        QueryLineUpOrderReq queryLineUpOrderReq = new QueryLineUpOrderReq();
                                        queryLineUpOrderReq.setPartnerId(orderBean.getCompanyId());
                                        queryLineUpOrderReq.setStoreId(orderBean.getShopId());
                                        queryLineUpOrderReq.setStartTime(DateUtil.addHours(new Date(orderBean.getGmtCreate()), -24).getTime());
                                        queryLineUpOrderReq.setEndTime(orderBean.getGmtCreate());
                                        // 取餐排队人数查询代码去除
                                        QueryLineUpResponse response = orderCenterSdkService.queryLineUpOrder(queryLineUpOrderReq);
                                        if (RESPONSE_SUCCESS_CODE.equals(response.getErrcode())) {
                                            if (null == response.getOrderCodes()) {
                                                progress = "100";
                                                returnWords = "";
                                            } else {
                                                List<String> orderCodeList = response.getOrderCodes();
                                                if (null != orderCodeList && orderCodeList.size() > 0) {
                                                    returnWords += "前方还有 " + orderCodeList.size() + " 单";
                                                    //开启制作时间 1 ：是 ， 2 ：否"
                                                    if (1 != configuration.getTurnOnTimeOfMaking()) {
                                                        totalSumTime = orderCodeList.size() * AutoOrderConfigTime.getTime(configuration.getAutoSelfmentionTakeOrderWorkflowFinishTime()); //分钟
                                                    } else {
                                                        Integer goodsAvgTimeOfMaking = (null == configuration.getGoodsAvgTimeOfMaking() || 0 == configuration.getGoodsAvgTimeOfMaking()) ? 5 : configuration.getGoodsAvgTimeOfMaking();
                                                        productSum = orderCodeList.stream().mapToInt(product -> Integer.parseInt(product.split("-")[1])).sum();
                                                        totalSumTime = productSum * goodsAvgTimeOfMaking;
                                                        returnWords += " / " + productSum + " 件";
                                                    }
                                                    pickUpTime = DateUtil.addMinutes(new Date(orderBean.getGmtAccept()), totalSumTime).getTime();
                                                    Date date = new Date(pickUpTime);
                                                    returnWords += "，预计 " + (String.valueOf(date.getHours()).length() == 1 ? "0" + (String.valueOf(date.getHours())) : date.getHours()) + ":" + (String.valueOf(date.getMinutes()).length() == 1 ? "0" + (String.valueOf(date.getMinutes())) : date.getMinutes()) + " 可取餐";
                                                    //制餐进度（当前时间-接单时间）/总时长（制餐时长）x100%
                                                    BigDecimal progressB = new BigDecimal(DateUtil.diffMinute(new Date(orderBean.getGmtAccept()), new Date())).divide(new BigDecimal(totalSumTime), 2, BigDecimal.ROUND_HALF_UP);
                                                    progress = progressB.compareTo(new BigDecimal(1)) == 1 ? "100" : progressB.multiply(new BigDecimal(100)).toString();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        AppLogUtil.errorLog("get returnWords", "", JSONObject.toJSONString(storeResponseDto), e);
                    }
                    orderBean.setProgress(String.valueOf(progress));
                    orderBean.setReturnWords(returnWords);
                    orderBean.setOrderProgressBarStatus(orderProgressBarStatus);
                    //以下代码为老代码，不确定还在不在用，就留着了
                    // 查询订单的排队人数
                    BaseQueryOrderRequest var1 = new BaseQueryOrderRequest();
                    var1.setOrderId(orderBean.getOid());
                    var1.setTrackingNo(LogThreadLocal.getTrackingNo());
                    // 取餐排队人数查询代码去除

                    // 查询订单的操作状态
                    BaseQueryOrderRequest var2 = new BaseQueryOrderRequest();
                    var2.setOrderId(orderBean.getOid());
                    var2.setTrackingNo(LogThreadLocal.getTrackingNo());
                    OrderStatusTrackingInfoResponse orderStatusTrackingInfoResponse = orderCenterSdkService.getOrderStatusTrackingInfoByOid(var2);

                    String string = JSONObject.toJSONString(orderStatusTrackingInfoResponse);
                    JSONObject jsonObject = JSONObject.parseObject(string);
                    OrderStatusTrackingInfoDto orderStatusTrackingInfoByOid = jsonObject.toJavaObject(OrderStatusTrackingInfoDto.class);
                    if (RESPONSE_SUCCESS_CODE.equals(orderStatusTrackingInfoByOid.getErrcode())) {
                        orderStatusTracking(orderBean, orderStatusTrackingInfoByOid);
                    }
                }

            });
        }
        List<QueryOrderResponseVo> queryOrderResponseVos = orderAdapter.convent2QueryOrderResponseVos(orders, userLoginInfoDto.getWxAppId(), userLoginInfoDto.getIappId());

        if (QueryOrderStatus.TAKE_MEAL.getCode().intValue() == queryOrderVo.getQueryOrderStatus()) {
            queryOrderResponseVos.forEach(queryOrderResponseVo -> {
                try {
                    // 判断是否有裂变活动 订单扩展信息判断必须有wxappid
                    // 查询门店下有没有 裂变活动
                    Long orderTime = DateUtil.convert2Date(queryOrderResponseVo.getOrderCreateTime(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS).getTime();
                    cn.freemud.entities.dto.store.StoreResponse bizVO = storeMap.get(queryOrderResponseVo.getShopId());
                    String activityId = isShareActivity(queryOrderVo.getPartnerId(), queryOrderResponseVo.getShopId()
                            , queryOrderResponseVo.getWxappid()
                            , orderTime == null ? 0 : orderTime
                            , queryOrderResponseVo.getOid()
                            , userId
                            , queryOrderVo.getSessionId()
                            , bizVO.getParentId());
                    // 取红包图片
                    queryOrderResponseVo.setRedpacketsPicture(getRedpacketsPicture(activityId));
                    queryOrderResponseVo.setActivityId(activityId);

                    // coco订单不考略是否查询待取餐的订单，直接调用支付有礼活动
                    // 所以在这个地方排除掉coco，在下边单独实现
                    //参与支付有礼活动
//                    if (!cocoPartnerId.contains(queryOrderVo.getPartnerId())) {
                    joinPayGift(queryOrderVo.getSessionId(), queryOrderResponseVo, partnerId, queryOrderVo.getPayGiftVer());
//                    }

                } catch (Exception e) {
                    AppLogUtil.errorLog("queryOrders_activity_error", gson.toJson(queryOrderResponseVo), gson.toJson(e), e);
                }
            });
        }

        // coco订单参与支付有礼活动
//        if (cocoPartnerId.contains(queryOrderVo.getPartnerId())) {
//            queryOrderResponseVos.forEach(queryOrderResponseVo -> {
//                try {
//                    joinPayGift(queryOrderVo.getSessionId(), queryOrderResponseVo, partnerId, null);
//
//                } catch (Exception e) {
//                    AppLogUtil.errorLog("coco_queryOrders_activity_error", gson.toJson(queryOrdersDto), gson.toJson(queryOrderResponseVo), e);
//                }
//            });
//        }

        for (QueryOrderResponseVo orderResponseVo : queryOrderResponseVos) {
            if (MarketTypeEnum.GROUPB.getIndex().byteValue() == orderResponseVo.getMarketingType() && StringUtils.isNotEmpty(orderResponseVo.getSpellGroupCode())
                    && orders.get(0).getApportionDetails() != null) {
                QueryHistoryGroupVO querySpellGroupVo = spellGroupOrderDataManager.queryHistoryByGroupId(orderResponseVo.getSpellGroupCode(),
                        partnerId, userId);
                orderResponseVo.setSpellGroup(querySpellGroupVo);
            }
        }

        responseMap.put("count", queryOrderResponse.getData() == null ? 0 : queryOrderResponse.getData().getCount());
        responseMap.put("list", queryOrderResponseVos);
        //只有有订单时才显示用户自定义取餐信息
        if (CollectionUtils.isNotEmpty(queryOrderResponseVos)) {
            responseMap.put("definitionMsg", getDefinitionMsg(queryOrderVo.getPartnerId()));
        }
        return ResponseUtil.success(responseMap);
    }

    @Override
    public BaseResponse queryOrdersNew(QueryOrderVo queryOrderVo) {
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(queryOrderVo.getSessionId());
        if (userLoginInfoDto == null || StringUtils.isBlank(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        if (StringUtils.isBlank(queryOrderVo.getStartDate())) {
            if (isQueryEs(queryOrderVo.getQueryOrderStatus()) && queryOrderEs) {
                queryOrderVo.setStartDate(DateUtil.convert2String(DateUtil.addMonths(new Date(), -3), "yyyy-MM-dd"));
            } else {
                //只有发票相关的查询2个月
                if (queryOrderVo.getNeedInvoice() != null) {
                    queryOrderVo.setStartDate(DateUtil.convert2String(DateUtil.addMonths(new Date(), -2), "yyyy-MM-dd"));
                } else {
                    queryOrderVo.setStartDate(DateUtil.convert2String(DateUtil.addMonths(new Date(), -1), "yyyy-MM-dd"));
                }
            }
        }
        if (StringUtils.isBlank(queryOrderVo.getEndDate())) {
            queryOrderVo.setEndDate(DateUtil.convert2String(new Date(), "yyyy-MM-dd"));
        }
        if (queryOrderVo.getQueryOrderStatus() == null) {
            return ResponseUtil.error(ResponseResult.PARAMETER_MISSING.getCode(), "查询订单状态不能为空");
        }
//        if (queryOrderVo.getQueryOrderType() != null) {
//            if (OrderType.getByCode(queryOrderVo.getQueryOrderType()) == null) {
//                return ResponseUtil.error(ResponseResult.PARAMETER_MISSING.getCode(), "查询订单类型不存在");
//            }
//        }
        String partnerId = queryOrderVo.getPartnerId();
        String startDateStr = queryOrderVo.getStartDate() + " 00:00:00";
        String endDateStr = queryOrderVo.getEndDate() + " 23:59:59";
        Date startDate = DateUtil.convert2Date(startDateStr, "yyyy-MM-dd HH:mm:ss");
        if (startDate == null) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "查询订单开始时间格式不正确");
        }
        Date endDate = DateUtil.convert2Date(endDateStr, "yyyy-MM-dd HH:mm:ss");
        if (endDate == null) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "查询订单结束时间格式不正确");
        }
        if (startDate.getTime() < DateUtil.addMonths(new Date(), -3).getTime()) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "只能查询3个月内的订单信息");
        }
        String userId = userLoginInfoDto.getMemberId();
        QueryOrderDto queryOrderDto = BeanUtil.convertBean(queryOrderVo, QueryOrderDto::new);
        queryOrderDto.setPartnerId(queryOrderVo.getPartnerId());
        queryOrderDto.setStartDate(startDateStr);
        queryOrderDto.setEndDate(endDateStr);
        String channelType = this.getQueryOrderChannelType(queryOrderVo, userLoginInfoDto);
        QueryOrdersRequest queryOrdersRequest = orderAdapter.convent2QueryOrdersDto(queryOrderDto, userId, channelType);

//        QueryOrdersRequest queryOrdersRequest2 = new QueryOrdersRequest();
//        BeanUtil.convertBean(queryOrdersDto, queryOrdersRequest2);
        queryOrdersRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        Integer invoiceState = 1;
        if (Objects.equals(queryOrderVo.getNeedInvoice(), false) && !Objects.equals(QueryOrderStatus.REFUND_BILL.getCode(), queryOrderVo.getQueryOrderStatus())) {
            //查询可开票，支付状态为已支付
            invoiceState = 1;
            queryOrdersRequest.setPayStatus(new Integer[]{2});
        } else if (Objects.equals(queryOrderVo.getNeedInvoice(), true)) {
            //查询已开票
            invoiceState = 2;
        }
        if (Objects.equals(QueryOrderStatus.REFUND_BILL.getCode(), queryOrderVo.getQueryOrderStatus())) {
            //查询其他
            invoiceState = 3;
        }
        queryOrdersRequest.setInvoiceState(invoiceState);
        QueryOrdersResponse queryOrderResponse = orderCenterSdkService.queryOrdersNew(queryOrdersRequest);

        if (queryOrderResponse == null || !RESPONSE_SUCCESS_CODE.equals(queryOrderResponse.getErrcode())) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode());
        }
        Map<String, Object> responseMap = Maps.newTreeMap();
        //用户无订单数据
        if (queryOrderResponse.getData() == null || queryOrderResponse.getData().getCount() == 0) {
            responseMap.put("count", 0);
            responseMap.put("list", new ArrayList<QueryOrderResponseVo>());
            return ResponseUtil.success(responseMap);
        }
        List<OrderBeanV1> ordersOld = queryOrderResponse.getData().getOrders();
        List<OrderBeanV1> orders = new ArrayList<>();
        Set<String> shopIds = new HashSet<>();
        // 过滤待支付订单
        if (CollectionUtils.isNotEmpty(ordersOld)) {
            for (OrderBeanV1 orderBean : ordersOld) {
                if (!(NewOrderStatus.PENDING_PAYMENT.getIndex().equals(orderBean.getStatusV2()) || PayStatus.NOT_PAY.getCode().equals(orderBean.getPayStatus()))) {
                    shopIds.add(orderBean.getShopId());
                }
                //围餐过滤掉未唤起支付的订单
                if (OrderChannelType.IWC.getCode().equals(channelType) && NewOrderStatus.PENDING_PAYMENT.getIndex().equals(orderBean.getStatusV2()) && PayStatus.NOT_PAY.getCode().equals(orderBean.getPayStatus())) {
                    // 如果已经唤起了支付则不再进行促销计算
                    boolean prePayLock = mealCacheManager.getOrderCreatePreParmentLock(userLoginInfoDto.getPartnerId(), userLoginInfoDto.getStoreId(), userLoginInfoDto.getTableNumber());
                    if (prePayLock) {
                        //已唤起支付
                        orders.add(orderBean);
                    }
                } else {
                    orders.add(orderBean);
                }
            }
        }
        String storeCodes = "";
        for (String shopId : shopIds) {
            storeCodes = shopId + "," + storeCodes;
        }
        GetListByCodesRequest request = new GetListByCodesRequest();
        request.setPartnerId(partnerId);
        request.setStoreCodes(storeCodes);
        // 查询多个门店信息
        GetListByCodesResponse storeInfoResponse = storeCenterService.getListByCodes(request, LogThreadLocal.getTrackingNo());
        Map<String, StoreResponse.BizVO> storeMap = new HashMap<>();
        if (storeInfoResponse != null && storeInfoResponse.getBizVO() != null && storeInfoResponse.getBizVO().getList() != null) {
            for (StoreResponse.BizVO bizVO : storeInfoResponse.getBizVO().getList()) {
                storeMap.put(bizVO.getStoreCode(), bizVO);
            }
        }
        if (CollectionUtils.isNotEmpty(orders)) {
            orders.forEach(orderBean -> {
                StoreResponse.BizVO storeResponseDto = storeMap.get(orderBean.getShopId());
                if (storeResponseDto != null) {
                    orderBean.setShopAddress(storeResponseDto.getAddress());
                    orderBean.setShopPhone(storeResponseDto.getPhone());
                    orderBean.setShopImageUrl(storeResponseDto.getLogoUrl());
                    //默认骑手头像显示为门店首页图片
                    orderBean.setRiderPhoto(storeResponseDto.getLogoUrl());
                    orderBean.setLatitude((StringUtils.isNotBlank(storeResponseDto.getLatitude()) ? Double.valueOf(storeResponseDto.getLatitude()) : 0d));
                    orderBean.setLongitude((StringUtils.isNotBlank(storeResponseDto.getLongitude()) ? Double.valueOf(storeResponseDto.getLongitude()) : 0d));
                }
                // 获取订单运单号，如果有运单则是第三方外卖单
                if (orderBean.getAddInfo() != null && StringUtils.isNotEmpty(orderBean.getAddInfo().getDeliveryId())) {
                    hasThirdDelivery(orderBean);
                }
                orderBean.setQueueIndex("");
                // 查询待取餐订单才需要查询排队人数和订单状态扭转记录
                if (QueryOrderStatus.TAKE_MEAL.getCode().equals(queryOrderDto.getQueryOrderStatus())) {
                    String returnWords = "";
                    Integer productSum = 0; //件数
                    Long pickUpTime = 0L; //预计
                    Integer totalSumTime = 0;
                    String progress = "0"; //进度
                    Integer orderProgressBarStatus = 2;
                    try {
                        if (null != storeResponseDto) {
                            String configurationStr = storeResponseDto.getConfiguration();
                            if (StringUtils.isNotEmpty(configurationStr)) {
                                StoreResponse.Configuration configuration = JSONObject.parseObject(configurationStr).toJavaObject(StoreResponse.Configuration.class);
                                if (null != configuration) {
                                    orderProgressBarStatus = configuration.getOrderProgressBarStatus();
                                    ; //默认关闭
                                    //订单状态为已接单并且无售后单展示进度条
                                    if (NewOrderStatus.ACCEPTED.getIndex() == orderBean.getStatusV2() && null == orderBean.getAfterSalesOrderResp() && null != orderProgressBarStatus && null != configuration.getTurnOnTimeOfMaking()) {
                                        // 查询订单的排队人数
                                        QueryLineUpOrderReq queryLineUpOrderReq = new QueryLineUpOrderReq();
                                        queryLineUpOrderReq.setPartnerId(orderBean.getCompanyId());
                                        queryLineUpOrderReq.setStoreId(orderBean.getShopId());
                                        queryLineUpOrderReq.setStartTime(DateUtil.addHours(new Date(orderBean.getGmtCreate()), -24).getTime());
                                        queryLineUpOrderReq.setEndTime(orderBean.getGmtCreate());
                                        // 取餐排队人数查询代码去除
                                        QueryLineUpResponse response = orderCenterSdkService.queryLineUpOrder(queryLineUpOrderReq);
                                        if (RESPONSE_SUCCESS_CODE.equals(response.getErrcode())) {
                                            if (null == response.getOrderCodes()) {
                                                progress = "100";
                                                returnWords = "";
                                            } else {
                                                List<String> orderCodeList = response.getOrderCodes();
                                                if (null != orderCodeList && orderCodeList.size() > 0) {
                                                    returnWords += "前方还有 " + orderCodeList.size() + " 单";
                                                    //开启制作时间 1 ：是 ， 2 ：否"
                                                    if (1 != configuration.getTurnOnTimeOfMaking()) {
                                                        totalSumTime = orderCodeList.size() * AutoOrderConfigTime.getTime(configuration.getAutoSelfmentionTakeOrderWorkflowFinishTime()); //分钟
                                                    } else {
                                                        Integer goodsAvgTimeOfMaking = (null == configuration.getGoodsAvgTimeOfMaking() || 0 == configuration.getGoodsAvgTimeOfMaking()) ? 5 : configuration.getGoodsAvgTimeOfMaking();
                                                        productSum = orderCodeList.stream().mapToInt(product -> Integer.parseInt(product.split("-")[1])).sum();
                                                        totalSumTime = productSum * goodsAvgTimeOfMaking;
                                                        returnWords += " / " + productSum + " 件";
                                                    }
                                                    pickUpTime = DateUtil.addMinutes(new Date(orderBean.getGmtAccept()), totalSumTime).getTime();
                                                    Date date = new Date(pickUpTime);
                                                    returnWords += "，预计 " + (String.valueOf(date.getHours()).length() == 1 ? "0" + (String.valueOf(date.getHours())) : date.getHours()) + ":" + (String.valueOf(date.getMinutes()).length() == 1 ? "0" + (String.valueOf(date.getMinutes())) : date.getMinutes()) + " 可取餐";
                                                    //制餐进度（当前时间-接单时间）/总时长（制餐时长）x100%
                                                    BigDecimal progressB = new BigDecimal(DateUtil.diffMinute(new Date(orderBean.getGmtAccept()), new Date())).divide(new BigDecimal(totalSumTime), 2, BigDecimal.ROUND_HALF_UP);
                                                    progress = progressB.compareTo(new BigDecimal(1)) == 1 ? "100" : progressB.multiply(new BigDecimal(100)).toString();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        AppLogUtil.errorLog("get returnWords", "", JSONObject.toJSONString(storeResponseDto), e);
                    }
                    orderBean.setProgress(String.valueOf(progress));
                    orderBean.setReturnWords(returnWords);
                    orderBean.setOrderProgressBarStatus(orderProgressBarStatus);
                    //以下代码为老代码，不确定还在不在用，就留着了
                    // 查询订单的排队人数
                    BaseQueryOrderRequest var1 = new BaseQueryOrderRequest();
                    var1.setOrderId(orderBean.getOid());
                    var1.setTrackingNo(LogThreadLocal.getTrackingNo());
                    // 查询订单的操作状态
                    BaseQueryOrderRequest var2 = new BaseQueryOrderRequest();
                    var2.setOrderId(orderBean.getOid());
                    var2.setTrackingNo(LogThreadLocal.getTrackingNo());
                    OrderStatusTrackingInfoResponse orderStatusTrackingInfoResponse = orderCenterSdkService.getOrderStatusTrackingInfoByOid(var2);
                    String string = JSONObject.toJSONString(orderStatusTrackingInfoResponse);
                    JSONObject jsonObject = JSONObject.parseObject(string);
                    OrderStatusTrackingInfoDto orderStatusTrackingInfoByOid = jsonObject.toJavaObject(OrderStatusTrackingInfoDto.class);
                    if (RESPONSE_SUCCESS_CODE.equals(orderStatusTrackingInfoByOid.getErrcode())) {
                        orderStatusTracking(orderBean, orderStatusTrackingInfoByOid);
                    }
                }
            });
        }
        List<QueryOrderResponseVo> queryOrderResponseVos = orderAdapter.convent2QueryOrderResponseVos(orders, userLoginInfoDto.getWxAppId(), userLoginInfoDto.getIappId());
        if (QueryOrderStatus.TAKE_MEAL.getCode().intValue() == queryOrderVo.getQueryOrderStatus()) {
            queryOrderResponseVos.forEach(queryOrderResponseVo -> {
                try {
                    // 判断是否有裂变活动 订单扩展信息判断必须有wxappid
                    // 查询门店下有没有 裂变活动
                    Long orderTime = DateUtil.convert2Date(queryOrderResponseVo.getOrderCreateTime(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS).getTime();
                    StoreResponse.BizVO bizVO = storeMap.get(queryOrderResponseVo.getShopId());
                    String activityId = isShareActivity(queryOrderVo.getPartnerId(), queryOrderResponseVo.getShopId()
                            , queryOrderResponseVo.getWxappid()
                            , orderTime == null ? 0 : orderTime
                            , queryOrderResponseVo.getOid()
                            , userId
                            , queryOrderVo.getSessionId()
                            , bizVO.getParentId());
                    // 取红包图片
                    queryOrderResponseVo.setRedpacketsPicture(getRedpacketsPicture(activityId));
                    queryOrderResponseVo.setActivityId(activityId);
                    // coco订单不考略是否查询待取餐的订单，直接调用支付有礼活动
                    // 所以在这个地方排除掉coco，在下边单独实现
                    //参与支付有礼活动
//                    if (!cocoPartnerId.contains(queryOrderVo.getPartnerId())) {
                    joinPayGift(queryOrderVo.getSessionId(), queryOrderResponseVo, partnerId, queryOrderVo.getPayGiftVer());
//                    }
                } catch (Exception e) {
                    AppLogUtil.errorLog("queryOrders_activity_error", gson.toJson(queryOrdersRequest), gson.toJson(queryOrderResponseVo), e);
                }
            });
        }
        // coco订单参与支付有礼活动
//        if (cocoPartnerId.contains(queryOrderVo.getPartnerId())) {
//            queryOrderResponseVos.forEach(queryOrderResponseVo -> {
//                try {
//                    joinPayGift(queryOrderVo.getSessionId(), queryOrderResponseVo, partnerId, null);
//
//                } catch (Exception e) {
//                    AppLogUtil.errorLog("coco_queryOrders_activity_error", gson.toJson(queryOrdersDto), gson.toJson(queryOrderResponseVo), e);
//                }
//            });
//        }
        for (QueryOrderResponseVo orderResponseVo : queryOrderResponseVos) {
            if (MarketTypeEnum.GROUPB.getIndex().byteValue() == orderResponseVo.getMarketingType() && StringUtils.isNotEmpty(orderResponseVo.getSpellGroupCode())
                    && orders.get(0).getApportionDetails() != null) {
                QueryHistoryGroupVO querySpellGroupVo = spellGroupOrderDataManager.queryHistoryByGroupId(orderResponseVo.getSpellGroupCode(),
                        partnerId, userId);
                orderResponseVo.setSpellGroup(querySpellGroupVo);
            }
        }
        responseMap.put("count", queryOrderResponse.getData() == null ? 0 : queryOrderResponse.getData().getCount());
        responseMap.put("list", queryOrderResponseVos);
        //只有有订单时才显示用户自定义取餐信息
        if (CollectionUtils.isNotEmpty(queryOrderResponseVos)) {
            responseMap.put("definitionMsg", getDefinitionMsg(queryOrderVo.getPartnerId()));
        }
        return ResponseUtil.success(responseMap);
    }

    @Override
    public BaseResponse queryCollageOrderById(Integer operation, String sessionId, String oid, String partnerId, String channel) {

        BaseResponse orderInfoRes = this.queryOrderById(operation, sessionId, oid, partnerId, channel, 0, null);

        if (null == orderInfoRes.getResult() || !String.valueOf(RESPONSE_SUCCESS_CODE).equals(orderInfoRes.getCode())) {
            return orderInfoRes;
        }

        // 根据用户聚合商品信息
        QueryCollageOrderResponseVo queryCollageOrderResponseVo = new QueryCollageOrderResponseVo();
        QueryOrderResponseVo queryOrderResponseVo = (QueryOrderResponseVo) orderInfoRes.getResult();
        List<ProductVo> productVo = queryOrderResponseVo.getProducts();
        // 根据用户id分类商品
        Map<String, List<ProductVo>> orderItemMap = productVo.stream().collect(Collectors.groupingBy(ProductVo::getUserId));
        List<UserProductVo> userProducts = new ArrayList<>();
        for (Map.Entry<String, List<ProductVo>> m : orderItemMap.entrySet()) {
            List<ProductVo> products = m.getValue();

            UserProductVo userProductVo = new UserProductVo();
            userProductVo.setUserId(products.get(0).getUserId());
            userProductVo.setOpenId(products.get(0).getOpenId());
            userProductVo.setNickName(products.get(0).getNickName());
            userProductVo.setPhotoUrl(products.get(0).getPhotoUrl());
            userProductVo.setProducts(products);
            userProducts.add(userProductVo);
        }

        queryCollageOrderResponseVo = JSONObject.parseObject(JSONObject.toJSONString(queryOrderResponseVo), QueryCollageOrderResponseVo.class);
        queryCollageOrderResponseVo.setUserProducts(userProducts);

        return ResponseUtil.success(queryCollageOrderResponseVo);

    }

    @Override
    public BaseResponse queryOrderRider(OrderRiderRequestVo requestVo) {
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(requestVo.getSessionId());
        if (userLoginInfoDto == null || StringUtils.isBlank(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
        baseQueryOrderRequest.setOrderId(requestVo.getOid());
        baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        baseQueryOrderRequest.setWithOperationHistory(1);
        QueryOrderByIdResponse response = orderCenterSdkService.queryOrderById(baseQueryOrderRequest);
        if (!RESPONSE_SUCCESS_CODE.equals(response.getErrcode()) || response.getData() == null) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR);
        }
        OrderBeanV1 orderBean = response.getData();
        if (orderBean == null || orderBean.getAddInfo() == null || StringUtils.isEmpty(orderBean.getAddInfo().getDeliveryId()) || "0".equals(orderBean.getAddInfo().getDeliveryId())) {
            return ResponseUtil.error(ResponseResult.DELIVERY_NOT_EXIST);
        }
        QueryDeliveryBaseRequest queryDeliveryBaseRequest = new QueryDeliveryBaseRequest();
        queryDeliveryBaseRequest.setDeliveryId(orderBean.getAddInfo().getDeliveryId());
        queryDeliveryBaseRequest.setOpenDistance(1);
        DeliveryBaseResponse<DeliveryStatusAndRiderPositionDto> deliveryBaseResponse = deliveryFeiginClient.getDeliveryStatusAndRiderPosition(queryDeliveryBaseRequest);
        if (RESPONSE_SUCCESS_CODE != deliveryBaseResponse.getCode() || response.getData() == null) {
            return ResponseUtil.error(ResponseResult.DELIVERY_QUERY_RIDER_ERROR);
        }
        OrderRiderResponseVo responseVo = new OrderRiderResponseVo();
        List<OrderRiderResponseVo.Operation> operationList = new ArrayList<>();
        orderBean.getOrderOperationHistoryList().stream().forEach(operationHistory -> {
            OrderRiderResponseVo.Operation operation = new OrderRiderResponseVo.Operation();
            operation.setCreateTime(DateTimeUtil.timeStampToTime(operationHistory.getCreateTime()));
            operation.setOperationDesc(operationHistory.getOperationDesc());
            operation.setOperationMethod(operationHistory.getOperationMethod());
            operation.setOperator(operationHistory.getOperator());
            operationList.add(operation);
        });
        responseVo.setOperationList(operationList);
        responseVo.setOrderId(orderBean.getOid());
        responseVo.setOrderStatus(orderBean.getStatus());
        responseVo.setStorePhone(deliveryBaseResponse.getData().getStorePhone());
        responseVo.setRiderName(deliveryBaseResponse.getData().getRiderName());
        responseVo.setRiderPhone(deliveryBaseResponse.getData().getRiderPhone());
//        responseVo.setExpressType(orderBean.getExpressType());

        if (orderBean.getAddInfo() != null && orderBean.getAddInfo().getDeliveryType() != null && StoreDeliveryMethod.THIRD.getCode().equals(orderBean.getAddInfo().getDeliveryType())
                && (DeliveryStatus.DELIVERYERROR.getCode() == orderBean.getAddInfo().getDeliverStatus() || DeliveryStatus.DELIVERYCANCEL.getCode() == orderBean.getAddInfo().getDeliverStatus())
        ) {
            responseVo.setDeliveryType(StoreDeliveryMethod.SELF.getCode());
        } else {
            responseVo.setDeliveryType(orderBean.getAddInfo() == null ? "" : orderBean.getAddInfo().getDeliveryType());
        }


        if (deliveryBaseResponse.getData().getCurrentPoint() != null) {
            String[] currentPoint = deliveryBaseResponse.getData().getCurrentPoint().split(",");
            responseVo.setRiderLongitude(currentPoint[0]);
            responseVo.setRiderLatitude(currentPoint[1]);
        }
        if (deliveryBaseResponse.getData().getStorePoint() != null) {
            String[] storePoint = deliveryBaseResponse.getData().getStorePoint().split(",");
            responseVo.setShopLongitude(storePoint[0]);
            responseVo.setShopLatitude(storePoint[1]);
        }
        //用户经纬度,改为从配送返回信息获取
        if (deliveryBaseResponse.getData().getDestPoint() != null) {
            String[] destPoint = deliveryBaseResponse.getData().getDestPoint().split(",");
            responseVo.setDestLongitude(destPoint[0]);
            responseVo.setDestLatitude(destPoint[1]);
        }
        responseVo.setDistance(deliveryBaseResponse.getData().getDistance());
        responseVo.setDuration(deliveryBaseResponse.getData().getDuration());
        responseVo.setStoreDistance(deliveryBaseResponse.getData().getStoreDistance());
        responseVo.setStoreDuration(deliveryBaseResponse.getData().getStoreDuration());

        responseVo.setDeliveryId(deliveryBaseResponse.getData().getDeliveryId());
        responseVo.setDevlieryStatus(deliveryBaseResponse.getData().getDevlieryStatus());
        return ResponseUtil.success(responseVo);
    }

    @Override
    public BaseResponse timeOutOrderRefund(TimeOutOrderVo timeOutOrderVo) {
        Map<String, OrderBeanV1> orderBeans = this.getOrderBeanByOrderId(timeOutOrderVo.getOid());
        if (MapUtils.isEmpty(orderBeans)) {
            ResponseUtil.error("404", "订单不存在");
        }
        OrderBeanV1 orderBean = orderBeans.get(OrderBeanType.SAASORDER.getCode());

        if (NewOrderStatus.CLOSED.getIndex().equals(orderBean.getStatusV2())) {
            this.timeOutRefund(orderBean);
        }
        return ResponseUtil.success();
    }

    private String getRedpacketsPicture(String activityId) {
        if (StringUtils.isNotBlank(activityId)) {
            try {
                ActivityGetByIdResponseDto activityGetByIdResponseDto = promotionActivityClient.getById(Long.valueOf(activityId));
                if (Objects.equals(activityGetByIdResponseDto.getCode(), ResponseResult.SUCCESS.getCode())
                        && activityGetByIdResponseDto.getResult() != null) {
                    return activityGetByIdResponseDto.getResult().getShareConfig().getRedpacketsPicture();
                }
            } catch (Exception e) {
                ErrorLog.errorConvertJson(OrderServiceImpl.class, "getRedpacketsPicture", e);
            }
        }
        return null;
    }

    //参与支付有礼活动
    private void joinPayGift(String sessionId, QueryOrderResponseVo queryOrderResponseVo, String partnerId, Integer payGiftVer) {
        PayGitCheckAndJoinRequestDto payGitRequestDto = new PayGitCheckAndJoinRequestDto();
        payGitRequestDto.setStoreId(queryOrderResponseVo.getShopId());
        payGitRequestDto.setSessionId(sessionId);
        payGitRequestDto.setOid(queryOrderResponseVo.getOid());
        payGitRequestDto.setPayAmount(queryOrderResponseVo.getAmount());

        // 通知支付有礼发放奖励：区分是否是储值卡支付
        if (OrderAdapter.isPayOfSVC(queryOrderResponseVo.getPayChannel())) {
            payGitRequestDto.setPayType(2);
        } else {
            payGitRequestDto.setPayType(1);//1-微信,2-储值卡
        }
        if (CollectionUtils.isNotEmpty(queryOrderResponseVo.getProducts())) {
            // add by miaohui for 20210325_华莱士紧急上线需求支付有礼须支持套餐内固定可选商品_miaohui start
            List<String> skuIds = queryOrderResponseVo.getProducts().stream().map(p -> p.getPid()).collect(Collectors.toList());
            if (hlsPartnerId != null && hlsPartnerId.contains(partnerId)) {
                // 华莱士获取支付有理促销数据时须将套餐商品内固定搭配、可选搭配商品的skuId一同传入
                queryOrderResponseVo.getProducts().forEach(productVo -> {
                    if (CollectionUtils.isNotEmpty(productVo.getSetMealProducts())) {
                        productVo.getSetMealProducts().forEach(setMealProduct -> {
                            skuIds.add(setMealProduct.getPid());
                        });
                    }
                });

            }
            payGitRequestDto.setSkuIds(skuIds);
            // add by miaohui for 20210325_华莱士紧急上线需求支付有礼须支持套餐内固定可选商品_miaohui end
        }
        if (OrderTypeV1.COLLECT_GOODS.getCode().intValue() == queryOrderResponseVo.getOrderType() || OrderTypeV1.EAT_IN.getCode().intValue() == queryOrderResponseVo.getOrderType()) {
            payGitRequestDto.setOrderWay(1);
        } else {
            payGitRequestDto.setOrderWay(2);
        }

        payGitRequestDto.setVer(payGiftVer);
        //coco业务默认传值1
//        if (cocoPartnerId.contains(partnerId)) {
//            payGitRequestDto.setVer(1);
//        }

        //fisherman  【ID1032306】 【订单聚合层】总部和区域活动可同时生效
        BaseResponse<PayGiftCheckAndJoinResponseObj> payGiftBaseResponse;
        payGiftBaseResponse = activityApplicationClient.payGiftCheckAndJoinNew(payGitRequestDto);
//        AppLogUtil.infoLog("fisherman  总部和区域活动可同时生效 ", payGitRequestDto, payGiftBaseResponse);
        if (String.valueOf(RESPONSE_SUCCESS_CODE).equals(payGiftBaseResponse.getCode()) && payGiftBaseResponse.getResult() != null) {
            PayGiftCheckAndJoinResponseObj result = payGiftBaseResponse.getResult();
            PayGiftCheckAndJoinResponseDto oldPayGift = result.getOldPayGift();
            // fisherman 版本前 原参数保留，暂不变更 向下兼容
            if (oldPayGift != null) {
                queryOrderResponseVo.setActivityName(oldPayGift.getActivityName());
                queryOrderResponseVo.setCoupons(oldPayGift.getCoupons());
                queryOrderResponseVo.setWechatCouponInfo(oldPayGift.getWechatCouponInfo());
                queryOrderResponseVo.setPayGiftReps(oldPayGift);
            }
            queryOrderResponseVo.setNewPayGift(result.getNewPayGift());
        }
    }

    private void orderStatusTracking(OrderBeanV1 orderBean, OrderStatusTrackingInfoDto orderStatusTrackingInfoByOid) {
        List<OrderStatusTrackingInfoDto.OrderStatusTrackingInfo> data = orderStatusTrackingInfoByOid.getData();
        if (CollectionUtils.isNotEmpty(data)) {
            for (OrderStatusTrackingInfoDto.OrderStatusTrackingInfo orderStatusTrackingInfo : data) {
                Integer status = orderStatusTrackingInfo.getStatus();
                String statusTime = orderStatusTrackingInfo.getStatusTime();
                switch (status) {
                    case 1:
                        orderBean.setOperateTakeOrderTime(statusTime);
                        break;
                    case 2:
                        orderBean.setOperateWaitPayTime(statusTime);
                        break;
                    case 3:
                        orderBean.setOperateReceiptTime(statusTime);
                        break;
                    case 4:
                        orderBean.setOperateDistributionTime(statusTime);
                        break;
                    case 5:
                        orderBean.setOperateCompleteTime(statusTime);
                        break;
                    case 6:
                        orderBean.setOperateCalcelTime(statusTime);
                        break;
                    case 7:
                        orderBean.setOperatePefuseTime(statusTime);
                        break;
                    case 31:
                        orderBean.setOperateCompleteMakeTime(statusTime);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    @Override
    public BaseResponse queryOrderById(Integer operation, String sessionId, String oid, String partnerId, String channel, Integer isQueryAfterPay, Integer payGiftVer) {
        AssortmentCustomerInfoVo userInfo = customerInfoManager.getCustomerInfoByObject(sessionId);
        if (userInfo == null || StringUtils.isEmpty(userInfo.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        String userId = userInfo.getMemberId();
        partnerId = userInfo.getPartnerId();
        if (StringUtils.isBlank(oid)) {
            return ResponseUtil.error(ResponseResult.PARAMETER_MISSING.getCode(), "oid不能为空");
        }
        BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
        baseQueryOrderRequest.setOrderId(oid);
        baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        // 订单详情要查询3个月前的订单
        // 先实时查询如果没有查询es
        QueryOrderByIdResponse response = orderManager.queryOrderById(baseQueryOrderRequest);

        if (!RESPONSE_SUCCESS_CODE.equals(response.getErrcode())) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR);
        }

        if (response.getData() == null && queryOrderEs) {
            // 查询es
            response = orderCenterSdkService.queryOrderByCodeES(partnerId, oid, LogThreadLocal.getTrackingNo());
        }

        if (!RESPONSE_SUCCESS_CODE.equals(response.getErrcode()) || response.getData() == null) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR);
        }
        OrderBeanV1 orderBean = response.getData();
        String storeId = orderBean.getShopId();
        GetStoreListbyCodesRequest request = new GetStoreListbyCodesRequest();
        request.setPartnerId(partnerId);
        request.setStoreCodes(storeId);
        StoreBaseResponseDto<StoreListResponse> storeBaseResponseDto = storeClient.getListByCodes(request);
        Map<String, cn.freemud.entities.dto.store.StoreResponse> storeMap = new HashMap<>();
        if (storeBaseResponseDto.getBizVO() != null && storeBaseResponseDto.getBizVO().getList() != null) {
            storeBaseResponseDto.getBizVO().getList().forEach(storeInfo -> {
                storeMap.put(storeInfo.getStoreCode(), storeInfo);
            });
        }
        String organizationId = "";
        orderBean.setProgressBarStatus(2);
        if (storeBaseResponseDto != null && storeBaseResponseDto.getBizVO() != null && CollectionUtils.isNotEmpty(storeBaseResponseDto.getBizVO().getList())) {
            cn.freemud.entities.dto.store.StoreResponse storeResponseDto = storeBaseResponseDto.getBizVO().getList().get(0);
            orderBean.setShopAddress(storeResponseDto.getAddress());
            orderBean.setShopPhone(storeResponseDto.getPhone());
            orderBean.setShopImageUrl(storeResponseDto.getLogoUrl());
            //默认骑手头像显示为门店首页图片
            orderBean.setRiderPhoto(storeResponseDto.getLogoUrl());
            orderBean.setShopPhone(storeResponseDto.getPhone());
            orderBean.setLatitude(Double.valueOf(storeResponseDto.getLatitude()));
            orderBean.setLongitude(Double.valueOf(storeResponseDto.getLongitude()));
            orderBean.setProgressBarStatus(storeResponseDto.getProcessBarResponse() == null ? Integer.valueOf(2) : storeResponseDto.getProcessBarResponse().getStatus());
            organizationId = storeResponseDto.getParentId();
        }
        //TODO 查询订单的排队人数
        orderBean.setQueueIndex("");
        BaseQueryOrderRequest var1 = new BaseQueryOrderRequest();
        var1.setOrderId(orderBean.getOid());
        var1.setTrackingNo(LogThreadLocal.getTrackingNo());
/*        BaseOrderResponse baseOrderResponse = orderCenterSdkService.queryOrderQueueIndex(var1);
        QueryOrderQueueIndexResponse response1 = new QueryOrderQueueIndexResponse();
        response1.setErrcode(baseOrderResponse.getErrcode());
        response1.setErrmsg(baseOrderResponse.getErrmsg());
        if (RESPONSE_SUCCESS_CODE.equals(response1.getErrcode())) {
            String queueIndex = response1.getData() == null ? "" : response1.getData().toString();
            orderBean.setQueueIndex(queueIndex);
        }*/
        //  获取订单运单号，如果有运单则是第三方外卖单
        if (orderBean.getAddInfo() != null && StringUtils.isNotEmpty(orderBean.getAddInfo().getDeliveryId())) {
            hasThirdDelivery(orderBean);
        }
        // 查询订单的操作状态
        OrderStatusTrackingInfoResponse statusTrackingInfoByOid = orderCenterSdkService.getOrderStatusTrackingInfoByOid(var1);
        String string2 = JSONObject.toJSONString(statusTrackingInfoByOid);
        JSONObject jsonObject2 = JSONObject.parseObject(string2);
        OrderStatusTrackingInfoDto orderStatusTrackingInfoByOid = jsonObject2.toJavaObject(OrderStatusTrackingInfoDto.class);

        if (RESPONSE_SUCCESS_CODE.equals(orderStatusTrackingInfoByOid.getErrcode())) {
            orderStatusTracking(orderBean, orderStatusTrackingInfoByOid);
        }

        List<QueryOrderResponseVo> queryOrderResponseVos = orderAdapter.convent2QueryOrderResponseVos(Collections.singletonList(orderBean), userInfo.getWxAppId(), userInfo.getIappId());
        if (CollectionUtils.isEmpty(queryOrderResponseVos)) {
            throw new ServiceException(ResponseResult.ORDER_QUERYORDER_ERROR);
        }
        QueryOrderResponseVo queryOrderResponseVo = queryOrderResponseVos.get(0);
        //48小时自动退款描述
        if (queryOrderResponseVo.getRefundStatus() != null && queryOrderResponseVo.getRefundStatus() == 1) {
            queryOrderResponseVo.setRefundTips("若48小时内未成功退款，请联系商家人工处理");
        }

        // 判断是否有裂变活动 订单扩展信息判断必须有wxappid
        String extInfo = response.getData().getExtInfo();
        if (StringUtils.isNotBlank(extInfo)) {
            OrderExtInfoDto orderExtInfoDto = gson.fromJson(extInfo, OrderExtInfoDto.class);
            String wxappid = orderExtInfoDto.getAppid();
            // 查询门店下有没有 裂变活动
            String activityId = isShareActivity(partnerId, storeId, wxappid, response.getData().getGmtCreate(), oid, userId, sessionId, organizationId);
            queryOrderResponseVo.setActivityId(activityId);
            // 取红包图片
            queryOrderResponseVo.setRedpacketsPicture(getRedpacketsPicture(activityId));
        }

        // 支付有礼
        // 目前只有coco在订单详情参加支付有礼，且不检查订单的状态
//        if (cocoPartnerId.contains(partnerId)) {
//            joinPayGift(sessionId, queryOrderResponseVo, partnerId, null);
//        } else
        if (BizTypeEnum.SALE_COUPON.getBizType().equals(orderBean.getBizType())) {
            joinPayGift(sessionId, queryOrderResponseVo, partnerId, payGiftVer);
        }

        //拼团订单
        if (MarketTypeEnum.GROUPB.getIndex().byteValue() == queryOrderResponseVo.getMarketingType() && StringUtils.isNotEmpty(queryOrderResponseVo.getSpellGroupCode())
                && orderBean.getApportionDetails() != null) {
            QueryHistoryGroupVO querySpellGroupVo = spellGroupOrderDataManager.queryHistoryByGroupId(queryOrderResponseVo.getSpellGroupCode(), partnerId, orderBean.getUserId());
            queryOrderResponseVo.setSpellGroup(querySpellGroupVo);
        }
        buildQueryOrderResponseVo(queryOrderResponseVo, response, partnerId);

        return ResponseUtil.success(queryOrderResponseVo);
    }

    /**
     * 如果有第三方配送，返回值添加第三方配送信息
     */
    private void hasThirdDelivery(OrderBeanV1 orderBean) {
        String deliveryId = orderBean.getAddInfo().getDeliveryId();
        if ("0".equals(deliveryId)) {
            return;
        }
        QueryDeliveryBaseRequest queryDeliveryBaseRequest = new QueryDeliveryBaseRequest();
        queryDeliveryBaseRequest.setDeliveryId(deliveryId);
        queryDeliveryBaseRequest.setOpenDistance(1);
        //变更查询配送信息换新接口 wanghanghang  20210129
        //【ID1021981】C端小程序配送显示骑手、商家坐标地图、配送距离以及骑手姓名电话，支持直接拨打
        DeliveryBaseResponse<DeliveryStatusAndRiderPositionDto> deliveryBaseResponse = deliveryFeiginClient.getDeliveryStatusAndRiderPosition(queryDeliveryBaseRequest);
//        DeliveryResponseDto<DeliveryInfoDto> delivery = deliveryService.deliveryOrderOne(deliveryId, trackingNo);
        if (RESPONSE_SUCCESS_CODE.equals(deliveryBaseResponse.getCode()) && deliveryBaseResponse.getData() != null) {
            DeliveryStatusAndRiderPositionDto result = deliveryBaseResponse.getData();
            orderBean.setDeliverStatus(result.getDevlieryStatus());
            orderBean.setRiderName(result.getRiderName());
            orderBean.setRiderPhone(result.getRiderPhone());
            orderBean.setReceiveTime(result.getReceiveTime());
            orderBean.setDepatchTime(result.getDepatchTime());
            orderBean.setArriveShopTime(result.getArriveShopTime());
            orderBean.setSendTime(result.getSendTime());
            orderBean.setCompleteTime(result.getCompleteTime());

            /** 只有配送状态是2 3 4 5时，返回三方坐标信息
             * 此处如果是外卖单，则需要返回门店经纬度/用户经纬度/骑手经纬度
             * 门店经纬度 = 配送返回信息为准，外卖单独新增门店经纬度字段，和配送信息接口统一 /queryOrderRider
             * wanghanghang 20210129
             */
            if (result.getDevlieryStatus().equals(DeliveryStatus.ALLOTRIDER.getCode()) ||
                    result.getDevlieryStatus().equals(DeliveryStatus.RIDERARRIVESTORE.getCode()) ||
                    result.getDevlieryStatus().equals(DeliveryStatus.RIDERGETMEAL.getCode()) ||
                    result.getDevlieryStatus().equals(DeliveryStatus.RIDERSTARTDELIVERY.getCode())
            ) {
                orderBean.getAddInfo().setDeliverStatus(result.getDevlieryStatus());
                orderBean.getAddInfo().setDistance(deliveryBaseResponse.getData().getDistance());
                orderBean.getAddInfo().setDuration(deliveryBaseResponse.getData().getDuration());
                orderBean.getAddInfo().setStoreDistance(deliveryBaseResponse.getData().getStoreDistance());
                orderBean.getAddInfo().setStoreDuration(deliveryBaseResponse.getData().getStoreDuration());
                orderBean.getAddInfo().setRiderName(result.getRiderName());
                orderBean.getAddInfo().setRiderPhone(result.getRiderPhone());
                orderBean.getAddInfo().setOrderId(orderBean.getOid());
                orderBean.getAddInfo().setStorePhone(result.getStorePhone());
                //门店经纬度
                if (deliveryBaseResponse.getData().getStorePoint() != null) {
                    String[] storePoint = deliveryBaseResponse.getData().getStorePoint().split(",");
                    orderBean.getAddInfo().setShopLongitude(storePoint[0]);
                    orderBean.getAddInfo().setShopLatitude(storePoint[1]);
                }
                //骑手经纬度
                if (deliveryBaseResponse.getData().getCurrentPoint() != null) {
                    String[] currentPoint = deliveryBaseResponse.getData().getCurrentPoint().split(",");
                    orderBean.getAddInfo().setRiderLongitude(currentPoint[0]);
                    orderBean.getAddInfo().setRiderLatitude(currentPoint[1]);
                }
                //用户经纬度
                if (deliveryBaseResponse.getData().getDestPoint() != null) {
                    String[] destPoint = deliveryBaseResponse.getData().getDestPoint().split(",");
                    orderBean.getAddInfo().setDestLongitude(destPoint[0]);
                    orderBean.getAddInfo().setDestLatitude(destPoint[1]);
                }
            }
        }

    }

    /**
     * 查询门店下有没有 裂变活动
     *
     * @param partnerId
     * @param storeId
     * @param wxappid
     * @param orderTime
     * @return
     */
    private String isShareActivity(String partnerId, String storeId, String wxappid, Long orderTime, String bizId, String userId, String sessionId, String organizationId) {

        QueryValidShareActivityReq activityReq = new QueryValidShareActivityReq();
        activityReq.setAppId(wxappid);
        activityReq.setPartnerId(partnerId);
        activityReq.setStoreId(storeId);
        activityReq.setOrderId(bizId);
        if (StringUtils.isNotBlank(organizationId)) {
            activityReq.setOrgIds(Arrays.asList(organizationId));
        }
        String activityId = Optional.ofNullable(promotionActivityClient.queryValidShareActivity(activityReq)).map(BaseResponse::getResult).map(Object::toString).orElse("");

        String nickName = Optional.ofNullable(customerInfoManager.getCustomerInfoByObject(sessionId)).map(AssortmentCustomerInfoVo::getNickName).orElse("");
        if (StringUtils.isNotBlank(activityId)) {
            // 添加分享记录 每笔订单只能添加一笔分享记录
            ShareAcitivityRequestDto shareAcitivityRequestDto = couponAdapter.convert2ShareAcitivityRequestDto(activityId, bizId, partnerId, userId, nickName);
            BaseResponse shareResponse = promotionActivityClient.shareRecord(shareAcitivityRequestDto);
            if (Objects.equals(shareResponse.getCode(), ResponseResult.SUCCESS.getCode())) {
                return activityId;
            }
        }
        return null;
    }


    @Override
    public BaseResponse deleteOrder(DeleteOrderVo deleteOrderVo) {
        if (StringUtils.isBlank(deleteOrderVo.getOid())) {
            return ResponseUtil.error(ResponseResult.PARAMETER_MISSING.getCode(), "oid不能为空");
        }
        BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
        baseQueryOrderRequest.setOrderId(deleteOrderVo.getOid());
        baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        QueryOrderByIdResponse queryOrderByIdResponse = orderCenterSdkService.queryOrderById(baseQueryOrderRequest);
        String string = JSONObject.toJSONString(queryOrderByIdResponse);
        JSONObject jsonObject = JSONObject.parseObject(string);
        QueryOrderByIdResponseDto responseDto = jsonObject.toJavaObject(QueryOrderByIdResponseDto.class);
        if (!RESPONSE_SUCCESS_CODE.equals(responseDto.getErrcode()) || responseDto.getData() == null) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR);
        }
        OrderBeanV1 orderBean = responseDto.getData();
        if (PayStatus.HAVE_PAID.getCode().equals(orderBean.getPayStatus())) {
            return ResponseUtil.error(ResponseResult.ORDER_DELETE_ERROR.getCode(), "已支付成功");
        }
        if (NewOrderStatus.CLOSED.getIndex().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER_DELETE_ERROR.getCode(), "订单已关闭");
        }
        if (!PayStatus.NOT_PAY.getCode().equals(orderBean.getPayStatus())) {
            return ResponseUtil.error(ResponseResult.ORDER_DELETE_ERROR.getCode(), "订单状态不允许删除");
        }
        if (!NewOrderStatus.PENDING_PAYMENT.getIndex().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER_DELETE_ERROR.getCode(), "订单状态不允许删除");
        }
        //关闭预支付
        boolean paySuccess = payServiceImpl.closePrePay(orderBean);
        if (paySuccess) {
            return ResponseUtil.error(ResponseResult.ORDER_DELETE_ERROR.getCode(), "支付成功");
        }
        String partnerId = deleteOrderVo.getPartnerId();
        if (CollectionUtils.isEmpty(deletePartnerId) || deletePartnerId.contains("") || deletePartnerId.contains(partnerId)) {
            String reason = "用户取消支付";
            CancelOrderRequest cancelOrderRequest = orderAdapter.convent2CancelOrderRequest(orderBean.getOid(),
                    partnerId, AfterSalesType.USER_CANCEL, reason, LogThreadLocal.getTrackingNo(), System.currentTimeMillis() + "");
            cancelOrderRequest.setOperator(orderBean.getUserName());
            cancelOrderRequest.setPartnerId(orderBean.getCompanyId());
            cancelOrderRequest.setCreateEvent(AfterSalesOrderCreateEventEnum.REFUND_COMPLETE.getCreateEvent());
            cancelOrderRequest.setReqRemark(reason);
            try {
                orderBusinessService.orderCancel(cancelOrderRequest);
//                orderSdkService.deleteOrder(var1,LogThreadLocal.getTrackingNo());
            } catch (Exception e) {
                ErrorLog.printErrorLog("删除订单失败", "order/v2/cancel", JSONObject.toJSONString(cancelOrderRequest), e);
            }
        }
        // TODO: 2019/9/10 删除订单通知
        orderQueueService.backOrdersStatusChange(orderBean.getOid(), orderBean.getStatus());

        weChatLiveMsgHandle.reportOrderStatus(orderBean, 3);
        return ResponseUtil.success();
    }

    @Override
    public BaseResponse cancelPayOrder(DeleteOrderVo deleteOrderVo) {
        if (StringUtils.isBlank(deleteOrderVo.getOid())) {
            return ResponseUtil.error(ResponseResult.PARAMETER_MISSING.getCode(), "oid不能为空");
        }
        BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
        baseQueryOrderRequest.setOrderId(deleteOrderVo.getOid());
        baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        QueryOrderByIdResponse queryOrderByIdResponse = orderCenterSdkService.queryOrderById(baseQueryOrderRequest);
        String string = JSONObject.toJSONString(queryOrderByIdResponse);
        JSONObject jsonObject = JSONObject.parseObject(string);
        QueryOrderByIdResponseDto responseDto = jsonObject.toJavaObject(QueryOrderByIdResponseDto.class);
        if (!RESPONSE_SUCCESS_CODE.equals(responseDto.getErrcode()) || responseDto.getData() == null) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR);
        }
        OrderBeanV1 orderBean = responseDto.getData();
        if (NewOrderStatus.CLOSED.getIndex().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER_DELETE_ERROR.getCode(), "订单已取消");
        }
        if (!PayStatus.NOT_PAY.getCode().equals(orderBean.getPayStatus())) {
            return ResponseUtil.error(ResponseResult.ORDER_DELETE_ERROR.getCode(), "订单状态不允许取消");
        }
        if (!NewOrderStatus.PENDING_PAYMENT.getIndex().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER_DELETE_ERROR.getCode(), "订单状态不允许取消");
        }
        payServiceImpl.closeHistoryPrePay(orderBean);
        CancelOrderRequest var1 = new CancelOrderRequest();
        var1.setOrderId(deleteOrderVo.getOid());
        var1.setPartnerId(deleteOrderVo.getPartnerId());
        var1.setAfterSalesType(AfterSalesType.SYSTEM_CANCEL);
        var1.setReason(null);
        var1.setTrackingNo(LogThreadLocal.getTrackingNo());
        var1.setRefundSerialNo(null);
        var1.setReqRemark("未支付取消");
        var1.setOperator("admin");
        //若为4，默认做【创建】+【同意并退款完成】，售后单状态为【完成】
        var1.setCreateEvent(4);
        BaseOrderResponse baseOrderResponse = orderCenterSdkService.orderCancel(var1);
        if (!RESPONSE_SUCCESS_CODE.equals(baseOrderResponse.getErrcode())) {
            return ResponseUtil.error(ResponseResult.ORDER_CANCEL_ERROR.getCode(), baseOrderResponse.getErrmsg());
        }
        // TODO: 2019/9/10 删除订单通知
        orderQueueService.backOrdersStatusChange(orderBean.getOid(), orderBean.getStatus());
        return ResponseUtil.success();
    }

    @Override
    public BaseResponse orderRefund(OrderRefundVo orderRefundVo) {
        if (StringUtils.isEmpty(orderRefundVo.getReason())) {
            orderRefundVo.setReason("退款");
        }
        // 查询用户信息
        AssortmentCustomerInfoVo userInfo = customerInfoManager.getCustomerInfoByObject(orderRefundVo.getSessionId());
        if (userInfo == null || StringUtils.isEmpty(userInfo.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        String memberId = userInfo.getMemberId();
        String partnerId = userInfo.getPartnerId();
        String wxAppId = userInfo.getWxAppId();

        if (StringUtils.isBlank(orderRefundVo.getOid())) {
            return ResponseUtil.error(ResponseResult.PARAMETER_MISSING.getCode(), "oid不能为空");
        }

        BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
        baseQueryOrderRequest.setOrderId(orderRefundVo.getOid());
        baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        QueryOrderByIdResponse queryOrderByIdResponse = orderCenterSdkService.queryOrderById(baseQueryOrderRequest);
        String string = JSONObject.toJSONString(queryOrderByIdResponse);
        JSONObject jsonObject = JSONObject.parseObject(string);
        QueryOrderByIdResponseDto orderByIdResponseDto = jsonObject.toJavaObject(QueryOrderByIdResponseDto.class);
        boolean isSon = StringUtils.isEmpty(orderByIdResponseDto.getData().getParentCode()) || "0".equals(orderByIdResponseDto.getData().getParentCode());
        String orderId = isSon ? orderByIdResponseDto.getData().getOid() : orderByIdResponseDto.getData().getParentCode();
        if (!RESPONSE_SUCCESS_CODE.equals(orderByIdResponseDto.getErrcode()) || orderByIdResponseDto.getData() == null) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "订单信息不存在");
        }
        if (!memberId.equals(orderByIdResponseDto.getData().getUserId())) {
            // 会员合并之后，多个渠道的会员id合并为一个，这个时候session中的memberId就可能会和历史订单中的userId不一致，导致不能退款
            // 这里如果发现会员id不一致，就去查询会员合并数据，重新匹配一下
            // 不要在外面查， 大部分情况不会进这个if， 不影响通常逻辑下的tps
            List<String> memberIds = memberInfoManager.getMemberAllIds(partnerId, memberId);
            if (!memberIds.contains(orderByIdResponseDto.getData().getUserId()))
                return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "不能操作非本人的订单");
        }
        OrderBeanV1 orderBean = orderByIdResponseDto.getData();

        if (PayStatus.NOT_PAY.getCode().equals(orderByIdResponseDto.getData().getPayStatus())
                || NewOrderStatus.PENDING_PAYMENT.getIndex().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "订单未支付，无法退款");
        }
        if (NewOrderStatus.CLOSED.getIndex().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "订单已取消，无法退款");
        }

        // 微商城订单
        if (Objects.equals(BizTypeEnum.MALL.getBizType(), orderBean.getBizType()) || Objects.equals("23", orderBean.getOrderClient())) {
            // 微商城因为没有退款原因选项 所以将用户退款说明用户作为退款原因
            orderRefundVo.setReason(orderRefundVo.getRemarks());
            // 必须选择退款方式
            if (Objects.isNull(orderRefundVo.getRefundMode()) || RefundModeEnum.getByIndex(orderRefundVo.getRefundMode()) == null) {
                return ResponseUtil.error(ResponseResult.PARAMETER_MISSING.getCode(), "请选择退款方式");
            }
            // 完成/配送中 可以选择退货退款
            List<Integer> refundGoodsCodes = Arrays.asList(
                    NewOrderStatus.DELIVERING.getIndex(), NewOrderStatus.COMPLETE.getIndex());
            if (!refundGoodsCodes.contains(orderBean.getStatusV2()) && !Objects.equals(RefundModeEnum.UN_REFUND_GOODS.getIndex(), orderRefundVo.getRefundMode())) {
                return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "还未发货，请选择只退款不退货");
            }
            // 拼团类型
            if (Objects.equals(MarketTypeEnum.GROUPB.getIndex().byteValue(), orderBean.getMarketingType())
                    && (StringUtils.isBlank(orderBean.getSpellGroupCode()) || StringUtils.isBlank(orderBean.getSpellGroupActivityCode()))) {
                return ResponseUtil.error(ResponseResult.SPELL_GROUP_QUERY_GROUP_WORK_ERROR);
            }
        } else if (NewOrderStatus.DELIVERING.getIndex().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "订单配送中，退款请联系售后！");
        }

        // fisherman 预定单前置校验-> bizType=7
        if (BizTypeEnum.ADVANCE_ORDER.getBizType().compareTo(orderBean.getBizType()) == 0) {
            // 预定时间 前一天都可退款
            boolean b = orderAdapter.checkAdvanceOrder(orderBean.getGmtExpect());
            if (!b) {
                return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "预约时间当天不可退款");
            }
        }

        /**
         * 已接单，制作完成，配送中,未接单，用户可申请退款
         *
         * v1.9.3.1 支持已完成订单可申请退款(通过b端后台控制)
         */
        List<Integer> enableRefundCodes = Lists.newArrayList(Arrays.asList(
                NewOrderStatus.PLACE_AN_ORDER.getIndex(), NewOrderStatus.ACCEPTED.getIndex(), NewOrderStatus.PRODUCED.getIndex(), NewOrderStatus.DELIVERING.getIndex(), NewOrderStatus.COMPLETE.getIndex()
        ));
        if (enableRefundCodes.contains(orderBean.getStatusV2()) && PayStatus.HAVE_PAID.getCode().equals(orderBean.getPayStatus())) {
            if (CollectionUtils.isNotEmpty(orderBean.getRefundList())) {
                RefundBeanV1 refundBean = orderBean.getRefundList().get(0);
                if (RefundStatus.APPLY_REFUND.getCode().equals(refundBean.getStatus())) {
                    return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "商家正在处理中，请稍后……");
                }
                //商城订单可二次发起退款
                if (!Objects.equals(BizTypeEnum.MALL.getBizType(), orderBean.getBizType()) && RefundStatus.REFUSE_REFUND.getCode().equals(refundBean.getStatus())) {
                    return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "您的申请已被商家拒绝，请联系门店沟通。");
                }
            }
            // 【优化】【小程序】顾客申请退款提交时，判断当前的订单状态，是否允许申请退款
            boolean refundButton = orderAdapter.checkRefundButton(queryOrderByIdResponse.getData(), userInfo.getWxAppId());
            if (!refundButton) {
                return ResponseUtil.error(ResponseResult.ORDER_NOT_ALLOW_REFUND.getCode(), ResponseResult.ORDER_NOT_ALLOW_REFUND.getMessage());
            }

            boolean isRefundDeliveryFee = true;
            //商城查询配送费
            if (Objects.equals(BizTypeEnum.MALL.getBizType(), orderBean.getBizType())
                    && StringUtils.isNotEmpty(orderBean.getExtInfo())) {
                JSONObject extInfoJsonObject = JSONObject.parseObject(orderBean.getExtInfo());
                OrderExtInfoDto orderExtInfoDto = extInfoJsonObject.toJavaObject(OrderExtInfoDto.class);
                if (null != orderExtInfoDto && null != orderExtInfoDto.getProvince()) {
                    String province = orderExtInfoDto.getProvince();
                    QueryFreightRefundSupportedVo queryFreightRefundSupportedVo = new QueryFreightRefundSupportedVo();
                    queryFreightRefundSupportedVo.setPartnerId(orderBean.getCompanyId());
                    queryFreightRefundSupportedVo.setProvince(province);
                    //整合商城订单状态，订单状态 1 2 3不需校验直接退运费 20210513
                    List<Integer> isRefundDeliveryFeeCodes = Arrays.asList(
                            NewOrderStatus.PENDING_PAYMENT.getIndex(), NewOrderStatus.PLACE_AN_ORDER.getIndex(), NewOrderStatus.ACCEPTED.getIndex());
                    if (isRefundDeliveryFeeCodes.contains(orderBean.getStatusV2())) {
                        isRefundDeliveryFee = true;
                    } else {
                        QueryFreightRefundSupportedResponse queryFreightRefundSupportedResponse = deliveryFeiginClient.isFreightRefundSupported(queryFreightRefundSupportedVo);
                        if (null != queryFreightRefundSupportedResponse && RESPONSE_SUCCESS_CODE == queryFreightRefundSupportedResponse.getCode()) {
                            Boolean freightRefundSupported = queryFreightRefundSupportedResponse.getData();
                            isRefundDeliveryFee = freightRefundSupported;
                        }
                    }
                }
            } else {
                // 查询小程序是否配置了退运费
                String configStr = redisCache.hashGet(MessageFormat.format(OrderRedisKeyConstant.ORDER_REFUND_CONFIG, orderBean.getCompanyId(), wxAppId), OrderRedisKeyConstant.HashKeyForOrderRefundConfig.TAKE_OUT);
                if (StringUtils.isNotEmpty(configStr)) {
                    OrderRefundConfigEntity config = JSON.parseObject(configStr, OrderRefundConfigEntity.class);
                    String refundDeliveryFeeConfig = config.getRefundShippingFee();
                    // 0、null表示 关闭 ; 1 表示开启
                    if (null != refundDeliveryFeeConfig
                            && Arrays.asList(NewOrderStatus.DELIVERING.getIndex(), NewOrderStatus.COMPLETE.getIndex()).contains(orderBean.getStatusV2())
                            && !ALLOW_REFUND.equals(refundDeliveryFeeConfig)) {
                        isRefundDeliveryFee = false;
                    }
                }
            }

            // 未接单
            if (NewOrderStatus.PLACE_AN_ORDER.getIndex().equals(orderBean.getStatusV2())) {
                // 拼团订单主动退款触发通知促销
                if (Objects.equals(BizTypeEnum.MALL.getBizType(), orderBean.getBizType())
                        && Objects.equals(MarketTypeEnum.GROUPB.getIndex().byteValue(), orderBean.getMarketingType())) {
                    GroupWorkRefundResponse refundResponse = activityHandle.groupWorkRefund(queryOrderByIdResponse.getData());
                    if (Objects.isNull(refundResponse) || !Objects.equals(ResponseConstant.SUCCESS_RESPONSE_CODE, refundResponse.getStatusCode())) {
                        return ResponseUtil.error(ResponseResult.SPELL_GROUP_REFUND_ERROR);
                    }
                }
                //商家未接单逻辑处理    1.调用支付退款 2.根据支付退款返回状态组装订单取消参数,调用订单取消接口
                BaseResponse baseResponse = partnerNoTakeOrder(orderRefundVo, orderBean, orderId, AfterSalesType.USER_CANCEL, isRefundDeliveryFee);
                if (baseResponse != null) {
                    return baseResponse;
                }   // 删除订单 通知活动添加商品库存
                orderQueueService.backOrdersStatusChange(orderBean.getOid(), orderBean.getStatus(), orderBean.getPayStatus());

            } else {
                CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
                cancelOrderRequest.setPartnerId(orderBean.getCompanyId());
                cancelOrderRequest.setStoreId(orderBean.getShopId());
                cancelOrderRequest.setOrderId(orderBean.getOid());
                cancelOrderRequest.setOrderClient(Integer.parseInt(orderBean.getOrderClient()));

                //传入的售后单类型为：2：售中用户取消 8：售后申请
                cancelOrderRequest.setAfterSalesType(AfterSalesType.USER_CANCEL);
                if (NewOrderStatus.COMPLETE.getIndex().equals(orderBean.getStatusV2())) {
                    cancelOrderRequest.setAfterSalesType(AfterSalesType.USER_SALE_RETURN);
                }
                cancelOrderRequest.setReason(orderRefundVo.getReason());
                cancelOrderRequest.setReqRemark(orderRefundVo.getRemarks());
                // 商城订单 增加拓展信息
                CancelOrderRequest.AfterSalesOrderExtInfoReq salesOrderExtInfoReq = new CancelOrderRequest.AfterSalesOrderExtInfoReq();
                salesOrderExtInfoReq.setRefundMode(orderRefundVo.getRefundMode());
                cancelOrderRequest.setExtInfoReq(salesOrderExtInfoReq);

                cancelOrderRequest.setOperator(orderBean.getUserName());
                cancelOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
                cancelOrderRequest.setRefundDeliveryAmount(isRefundDeliveryFee);
                cancelOrderRequest.setRefundState(AfterSalesRefunStateEnum.STATE_1.getIndex());
                cancelOrderRequest.setOperationClient(AfterSalesApplyClientEnum.STATE_5.getIndex());
                BaseOrderResponse baseResponseDto = orderCenterSdkService.orderCancel(cancelOrderRequest);

                if (!RESPONSE_SUCCESS_CODE.equals(baseResponseDto.getErrcode())) {
                    return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), baseResponseDto.getErrmsg());
                }
                if (orderBean.getAmount() > 0) {
                    sendPosMessage(partnerId, orderBean.getShopId());
                }
                //通知小助手发送申请退款公众号订阅消息
                sendApplyRefundSubscriptionNotice(orderBean, orderRefundVo);
                //已接单可发起退款申请，查询门店有无云打印机，有则打印退款申请小票
                printApplyRefundSmallTicket(orderBean, orderRefundVo);
            }
        }
        return ResponseUtil.success();
    }


    /**
     * 商家未接单,取消订单逻辑处理    1.调用支付退款 2.根据支付退款返回状态组装订单取消参数,调用订单取消接口
     *
     * @param orderRefundVo
     * @param orderBean
     */
    @SneakyThrows
    private BaseResponse partnerNoTakeOrder(OrderRefundVo orderRefundVo, OrderBeanV1 orderBean, String fatherOrderId, AfterSalesType afterSalesType, Boolean isRefundDeliveryFee) {
        com.freemud.application.sdk.api.base.BaseResponse<OrderRefundResponse> response = null;
        Long refundId = System.currentTimeMillis();
        String partnerId = orderBean.getCompanyId();
        int state = PayRefundStatus.SUCCESS.getCode();
        if (orderBean.getAmount() != 0) {
            OrderManagerRequest orderManagerRequest = new OrderManagerRequest();
            orderManagerRequest.setReason(orderRefundVo.getReason());
            PayRefundResponse refundResponse = payServiceImpl.payRefundCommon(orderManagerRequest, orderBean);
            state = refundResponse.getPayRefundStatus().getCode();
        }

        CancelOrderRequest cancelOrderRequest = orderAdapter.convent2CancelOrderRequest(orderBean.getOid(),
                partnerId, afterSalesType, orderRefundVo.getReason(), LogThreadLocal.getTrackingNo(), refundId.toString());
        cancelOrderRequest.setOperator(orderBean.getUserName());
        cancelOrderRequest.setPartnerId(orderBean.getCompanyId());
        cancelOrderRequest.setRefundState(AfterSalesRefunStateEnum.STATE_4.getIndex());
        if (Objects.equals(PayRefundStatus.SUCCESS.getCode(), state)) {
            //退款成功
            cancelOrderRequest.setCreateEvent(AfterSalesOrderCreateEventEnum.REFUND_COMPLETE.getCreateEvent());
        } else if (Objects.equals(PayRefundStatus.RUNNING.getCode(), state)) {
            cancelOrderRequest.setCreateEvent(null);
            cancelOrderRequest.setRefundState(AfterSalesRefunStateEnum.STATE_2.getIndex());
        }else {
            // 其他退款失败的情况 不生成售后单
            return ResponseUtil.error(ResponseResult.MULTIORDER__ERRORREFUND.getCode(), "multiOrderRefund_failed");
        }
        cancelOrderRequest.setReqRemark(orderRefundVo.getRemarks());
        cancelOrderRequest.setRefundDeliveryAmount(isRefundDeliveryFee);
        // 商城订单 增加拓展信息
        CancelOrderRequest.AfterSalesOrderExtInfoReq salesOrderExtInfoReq = new CancelOrderRequest.AfterSalesOrderExtInfoReq();
        salesOrderExtInfoReq.setRefundMode(orderRefundVo.getRefundMode());
        cancelOrderRequest.setExtInfoReq(salesOrderExtInfoReq);

        BaseOrderResponse baseOrderResponse = orderCenterSdkService.orderCancel(cancelOrderRequest);
        if (baseOrderResponse == null || !ObjectUtils.equals(ResponseConstant.SUCCESS_RESPONSE_CODE, baseOrderResponse.getErrcode())) {
            return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "orderRefund_failed");
        }

        if (state == PayRefundStatus.RUNNING.getCode().intValue()) {
            // 如果退款中, 直接来个申请记录,  退款回调进行处理
            return ResponseUtil.error(ResponseResult.PAY_REFUND_ERROR);
        }
        return null;
    }


    @Override
    public BaseResponse queryOrderQueueIndex(QueryOrderQueueIndexVo queryOrderQueueIndexVo) {
        AssortmentCustomerInfoVo userInfo = customerInfoManager.getCustomerInfoByObject(queryOrderQueueIndexVo.getSessionId());
        if (userInfo == null || StringUtils.isEmpty(userInfo.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        try {
            BaseQueryOrderRequest var1 = new BaseQueryOrderRequest();
            var1.setOrderId(queryOrderQueueIndexVo.getOid());
            var1.setTrackingNo(LogThreadLocal.getTrackingNo());
            BaseOrderResponse response = orderCenterSdkService.queryOrderQueueIndex(var1);

            if (!RESPONSE_SUCCESS_CODE.equals(response.getErrcode())) {
                return ResponseUtil.error(ResponseResult.NOT_LOGIN);
            }
            Map<String, String> queueIndexMap = Maps.newTreeMap();
            queueIndexMap.put("oid", queryOrderQueueIndexVo.getOid());
            queueIndexMap.put("queueIndex", response.getData() == null ? "" : response.getData().toString());
            return ResponseUtil.success(queueIndexMap);
        } catch (Exception e) {
            return ResponseUtil.error(ResponseResult.SYSTEM_BUSINESS_ERROR);
        }
    }

    @Override
    public BaseResponse getRefundReason(GetRefundReasonVo getRefundReasonVo) {
        AssortmentCustomerInfoVo customerInfoByObject = customerInfoManager.getCustomerInfoByObject(getRefundReasonVo.getSessionId());
        if (customerInfoByObject != null && customerInfoByObject.getMemberId() == null) {
            throw new ServiceException(ResponseResult.NOT_LOGIN);
        }
        List<RefundReasonResponseVo> refundReasonResponseVos = getRefundReasonResponseVos(getRefundReasonVo);
        return ResponseUtil.success(refundReasonResponseVos);
    }

    @Override
    public BaseResponse getNewRefundReason(GetRefundReasonVo getRefundReasonVo) {
        AssortmentCustomerInfoVo userInfo = customerInfoManager.getCustomerInfoByObject(getRefundReasonVo.getSessionId());
        if (userInfo != null && userInfo.getMemberId() == null) {
            throw new ServiceException(ResponseResult.NOT_LOGIN);
        }
        String oid = getRefundReasonVo.getOid();
        if (StringUtils.isEmpty(oid)) {
            throw new ServiceException(ResponseResult.ORDER_CODE_EMPTY);
        }
        GetRefundResonResponseVo result = new GetRefundResonResponseVo();
        List<RefundReasonResponseVo> refundReasonResponseVos = getRefundReasonResponseVos(getRefundReasonVo);
        result.setRefundReasons(refundReasonResponseVos);
        assert userInfo != null;
        String refundDocument = buildRefundDocument(oid);
        result.setRefundDocument(refundDocument);
        return ResponseUtil.success(result);
    }

    @Override
    public BaseResponse createIntegralOrder(IntegralOrderVo vo) {
        AssortmentCustomerInfoVo userInfo = customerInfoManager.getCustomerInfoByObject(vo.getSessionId());
        if (userInfo == null || StringUtils.isEmpty(userInfo.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        ParkingOrderCreateReq req = new ParkingOrderCreateReq();
        req.setBizType(vo.getBizType());
        req.setUserId(userInfo.getMemberId());
        req.setUserName(userInfo.getNickName());
        req.setPartnerId(vo.getPartnerId());
        req.setImgUlr(vo.getImgUrl());
        req.setMobile(userInfo.getMobile());
        req.setOperator(userInfo.getNickName());
        //积分订单为4
        req.setOrderType((byte) 4);
        OrderBaseResp<OrderInfoReqs> result = orderSdkService.parking_v2_create(req, LogThreadLocal.getTrackingNo());
        if (Objects.isNull(result)) {
            return new BaseResponse(ResponseResultEnum.SYSTEM_ERROR.getCode(), ResponseResultEnum.SYSTEM_ERROR.getMessage(), "", null);
        }
        if (!ResponseResultEnum.SUCCESS.getCode().equalsIgnoreCase(result.getCode()) || Objects.isNull(result.getResult())) {
            return new BaseResponse(result.getCode(), result.getMessage(), "", null);
        }
        return ResponseUtil.success();
    }

    private String buildRefundDocument(String oid) {
        QueryOrderByIdResponseDto response = getQueryOrderByIdResponseDto(oid);
        if (!RESPONSE_SUCCESS_CODE.equals(response.getErrcode()) || response.getData() == null) {
            throw new ServiceException(ResponseResult.ORDER_QUERYORDER_ERROR);
        }
        OrderBeanV1 orderBean = response.getData();
        // TODO: 2019/9/9 再次校验是否可以退款 是否需要
        String document = OrderRefundConstant.COMMON_DOCUMENT;
        if (OrderTypeV1.COLLECT_GOODS.getCode().equals(orderBean.getOrderType())) {
            return document;
        }
        if (OrderTypeV1.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
            if (NewOrderStatus.COMPLETE.getIndex().equals(orderBean.getStatusV2())) {
                document = OrderRefundConstant.TAKE_OUT_COMPLETE_DOCUMENT;
                return document;
            } else {
                document = OrderRefundConstant.TAKE_OUT_NOT_COMPLETE_DOCUMENT;
                return document;
            }
        }
        return document;
    }

    private QueryOrderByIdResponseDto getQueryOrderByIdResponseDto(String oid) {
        BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
        baseQueryOrderRequest.setOrderId(oid);
        baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        QueryOrderByIdResponse queryOrderByIdResponse = orderCenterSdkService.queryOrderById(baseQueryOrderRequest);
        String string = JSONObject.toJSONString(queryOrderByIdResponse);
        JSONObject jsonObject = JSONObject.parseObject(string);
        return jsonObject.toJavaObject(QueryOrderByIdResponseDto.class);
    }

    /**
     * 构建订单退款原因
     *
     * @param getRefundReasonVo 请求参数
     * @return
     */
    private List<RefundReasonResponseVo> getRefundReasonResponseVos(GetRefundReasonVo getRefundReasonVo) {
        List<RefundReasonResponseVo> refundReasonResponseVos = Lists.newArrayList();
        if (CreateOrderType.TAKE_OUT.getCode().equals(getRefundReasonVo.getOrderType())) {
            refundReasonResponseVos.add(getRefundReasonResponseVo(RefundReasonEnum.Delivery_Time_too_long));
            refundReasonResponseVos.add(getRefundReasonResponseVo(RefundReasonEnum.Misdelivery_Leakage_of_Goods));
            refundReasonResponseVos.add(getRefundReasonResponseVo(RefundReasonEnum.Riders_confirm_service_ahead_of_schedule));
            refundReasonResponseVos.add(getRefundReasonResponseVo(RefundReasonEnum.Other));
        } else {
            refundReasonResponseVos.add(getRefundReasonResponseVo(RefundReasonEnum.Wrong_order));
            refundReasonResponseVos.add(getRefundReasonResponseVo(RefundReasonEnum.Goods_not_match_expectations));
            refundReasonResponseVos.add(getRefundReasonResponseVo(RefundReasonEnum.Other));
        }
        return refundReasonResponseVos;
    }

    /**
     * 发送pos端消息
     */
    public void sendPosMessage(String partnerId, String storeId) {
        PushMessageNoticeDto pushMessageNoticeDto = messageNoticeAdapter.convent2PushMessageNoticeDto(2, partnerId, storeId,
                null, null, null, null);
        messageNoticeClient.createMessage(pushMessageNoticeDto, LogThreadLocal.getTrackingNo());
    }

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

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


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

    /**
     * 发送支付成功模板消息
     *
     * @param orderBean
     */
    private void sendPaySuccessMessage(OrderBeanV1 orderBean) {
        Long gmtExpect = orderBean.getGmtExpect();
        if (gmtExpect != null) {
            // 预约下单
            this.sendMessage(orderBean, MessageEventType.PAYORDEREXPECT);
        } else {
            // 非预约下单
            this.sendMessage(orderBean, MessageEventType.PAYORDER);
        }
    }

    /**
     * 发送模板消息
     *
     * @param orderBean
     * @param messageEventType
     */
    private void sendMessage(OrderBeanV1 orderBean, MessageEventType messageEventType) {
        MessageTemplateRequest<MessagePushOrderTemplateRequest> messageTemplateRequest = null;
        try {
            messageTemplateRequest = messageNoticeAdapter.convent2MessageTemplateRequest(orderBean);
            messageTemplateRequest.setMessageEventType(messageEventType);
            com.freemud.application.sdk.api.base.BaseResponse baseResponse = this.messageTemplatePushService.sendTemplateMsg(messageTemplateRequest);
            if (!Objects.equals(baseResponse.getCode(), ResponseResultEnum.SUCCESS.getCode())) {
                AppLogUtil.printLog("发送支付成功模板消息 失败", orderBean.getOid(), JSON.toJSONString(baseResponse));
            }
        } catch (Exception e) {
            AppLogUtil.errorLog("sendTemplateMsg_error", JSONObject.toJSONString(orderBean), JSONObject.toJSONString(messageTemplateRequest), e);
        }
    }


    /**
     * 获取商品第三方商品编号
     *
     * @param createOrderDto
     * @return
     */
    private BaseCreateOrderRequest getProductCustomerCode(BaseCreateOrderRequest createOrderDto) {
        List<String> spuIds = new ArrayList<>();
        for (CreateOrderProductRequest productDto : createOrderDto.getProducts()) {
            spuIds.add(productDto.getProductId());
        }
        Map<String, GetProductsVo> products = itemService.getSpuProducts(spuIds, createOrderDto.getCompanyId(), createOrderDto.getShopId(), createOrderDto.getMenuType());
        if (products == null) {
            return createOrderDto;
        }
        if (products.isEmpty()) {
            return createOrderDto;
        }
        for (CreateOrderProductRequest productDto : createOrderDto.getProducts()) {
            String skuId = productDto.getSpecification();
            if (products.get(skuId) != null) {
                productDto.setSpuProductCode(products.get(skuId).getSpuProductCode());
                productDto.setCustomerCode(products.get(skuId).getCustomerCode());
                productDto.setProductCode(products.get(skuId).getProductCode());
                productDto.setThirdProductSpecId(products.get(productDto.getSpecification()).getThirdProductSpecId());
                productDto.setThirdProductPropertyId(getThirdPropertyId(products.get(productDto.getSpecification()).getProductAttributeGroupList(), productDto.getAddInfo()));

                // todo 商品组信息
                setProductGroupInfo(products.get(skuId).getProductGroupList(), productDto);
            } else {
                productDto.setCustomerCode("");
                productDto.setProductCode("");
                AppLogUtil.errorLog("getProducts_exception", JSONObject.toJSONString(skuId), JSONObject.toJSONString(products), null);
            }
            //套餐子商品
            if (CollectionUtils.isNotEmpty(productDto.getComboProduct())) {
                for (CreateOrderProductRequest comboProduct : productDto.getComboProduct()) {
                    String comboSkuId = comboProduct.getSpecification();
                    if (products.get(comboSkuId) != null) {
                        comboProduct.setSpuProductCode(products.get(comboSkuId).getSpuProductCode());
                        comboProduct.setCustomerCode(products.get(comboSkuId).getCustomerCode());
                        comboProduct.setProductCode(products.get(comboSkuId).getProductCode());
                        comboProduct.setThirdProductSpecId(products.get(comboSkuId).getThirdProductSpecId());
                        comboProduct.setThirdProductPropertyId(getThirdPropertyId(products.get(comboSkuId).getProductAttributeGroupList(), comboProduct.getAddInfo()));
                        comboProduct.setStapleFood(products.get(comboSkuId).getStapleFood());
                        // todo 套餐商品的商品组信息
                        setProductGroupInfo(products.get(comboSkuId).getProductGroupList(), comboProduct);
                    } else {
                        comboProduct.setCustomerCode("");
                        comboProduct.setProductCode("");
                        AppLogUtil.errorLog("getProducts_exception", JSONObject.toJSONString(skuId), JSONObject.toJSONString(products), null);
                    }
                }
            }
        }
        return createOrderDto;
    }

    /**
     * 设置商品组信息
     *
     * @param productGroupList
     * @param product
     */
    private void setProductGroupInfo(List<ProductGroup> productGroupList, CreateOrderProductRequest product) {
        if (CollectionUtils.isEmpty(productGroupList)) return;

        List<ProductGroupVo> targetGroupList = Lists.newArrayList();
        for (ProductGroup productGroup : productGroupList) {
            for (GroupDetail groupDetail : productGroup.getGroupDetail()) {
                ProductGroupVo productGroupVo = ProductGroupVo.builder()
                        .groupId(groupDetail.getGroupId()).groupName(productGroup.getName())
                        .thirdGroupId(productGroup.getGroupCode()).build();
                if (!targetGroupList.contains(productGroupVo)) {
                    targetGroupList.add(productGroupVo);
                }
            }
        }
        product.setProductGroupList(targetGroupList);
    }

    private String getThirdPropertyId(List<ProductAttributeGroup> productAttributeGroups, String addInfo) {
        String thirdProductPropertyId = "";
        if (StringUtils.isBlank(addInfo) || CollectionUtils.isEmpty(productAttributeGroups)) {
            return thirdProductPropertyId;
        }
        JSONObject jsonObject = JSONObject.parseObject(addInfo);
        String attributeNames = (String) jsonObject.get("attributeNames");
        List<String> list = new ArrayList<>();
        String[] split = attributeNames.split("/");

        List<AttributeValue> attributeValues = new ArrayList<>();
        for (ProductAttributeGroup attributeGroup : productAttributeGroups) {
            attributeValues.addAll(attributeGroup.getAttributeValues());
        }

        for (int i = 0; i < split.length; i++) {
            for (AttributeValue attributeValue : attributeValues) {
                if (attributeValue.getAttributeValue().equals(split[i])) {
                    list.add(attributeValue.getCustomerCode());
                    break;
                }
            }
        }
        if (CollectionUtils.isNotEmpty(list)) {
            thirdProductPropertyId = StringUtils.join(list, ",");
        }
        return thirdProductPropertyId;
    }

    /**
     * 创建订单调用集成，不区分订单类型
     *
     * @return
     */
    public BaseResponse sdkCreateOrder(CreateOrderBONew createOrderBO) {
        CreateOrderVo createOrderVo = createOrderBO.getCreateOrderVo();
        StoreMixResponseDto storeMixResponseDto = createOrderBO.getStoreMixResponseDto();
        StoreResponseDto storeResponseDto = storeMixResponseDto.getStoreInfo();
        ShoppingCartGoodsDto shoppingCartGoodsDto = createOrderBO.getShoppingCartGoodsDto();
        AssortmentCustomerInfoVo userLoginInfoDto = createOrderBO.getUserLoginInfoDto();
        //更新订单使用
        CreateOrderOperateDto response = new CreateOrderOperateDto();
        //订单扩展表保存门店组织结构信息
        OrderExtendedReq orderExtendedReq = orderAdapter.saveStoreInfo(storeResponseDto);
        // fisherman 爱马哥蛋糕 预定 额外字段存储
        orderExtendedReq.setUserPhone(createOrderVo.getUserPhone());
        orderExtendedReq.setSendWord(createOrderVo.getSendWord());
        OrderClientType orderClient = OrderClientType.SAAS;
        String appId = userLoginInfoDto.getWxAppId();
        if (ChannelEnum.TYPE_2.getCode().equals(userLoginInfoDto.getChannel())) {
            orderClient = OrderClientType.ALIPAY;
        } else if (UserLoginChannelEnum.APP.getCode().equals(userLoginInfoDto.getChannel())) {
            orderClient = OrderClientType.APP;
        }
        //抖音小程序
//        if (ChannelEnum.TYPE_5.getCode().equalsIgnoreCase(createOrderVo.getChannel())) {
//            createOrderVo.setPayChannelType(PayChannelType.TIKTOKPAY.getIndex());
//            orderClient = OrderClientType.TIKTOKPAY;
//        }

        // 美业
//        if (OrderChannelType.BEAUTIFUL.getCode().equals(createOrderVo.getChannelType())) {
//            orderClient = OrderClientType.BEAUTIFUL;
//        }

        //组装老的创建订单数据模型
        BaseCreateOrderRequest baseCreateOrderRequest = orderAdapter.convent2CreateOrderDto(createOrderVo, shoppingCartGoodsDto, storeResponseDto);
        // fisherman 订单支付价格 _> 处理 消费黑面名单逻辑
        Long amount = baseCreateOrderRequest.getAmount();
        BlacklistDto blacklistDto = new BlacklistDto();
        blacklistDto.setAmount(amount);
        blacklistDto.setPartnerId(createOrderVo.getPartnerId());
        blacklistDto.setMemberId(createOrderVo.getUserId());
        blacklistDto.setUseCustomerScore(createOrderVo.getUseCustomerScore());
        if (CollectionUtils.isNotEmpty(baseCreateOrderRequest.getAccounts())) {
            // 过滤出券, 黑名单有用户不能用券
            List<CreateOrderAccountRequest> useAccount = baseCreateOrderRequest.getAccounts()
                    .stream()
                    .filter(a -> QueryOrderAccountType.useCouponList.contains(a.getAccountType()))
                    .collect(Collectors.toList());
            blacklistDto.setUseCoupon(CollectionUtils.isNotEmpty(useAccount));
        }
        String touchStr = memberBlacklistHandler.checkisTrueBlacklist(blacklistDto);
        if (StringUtils.isNotEmpty(touchStr)) {
            return ResponseUtil.error(ResponseResult.TOUCH_SHOPPING_BLACK_LIST.getCode(), touchStr);
        }

        // 预先前置 设置 支付方式
        this.preSetPayChannelType(baseCreateOrderRequest, createOrderVo);

        //查询第三方商品编号
        baseCreateOrderRequest = getProductCustomerCode(baseCreateOrderRequest);
        //保存门店渠道信息
        baseCreateOrderRequest.setOrderExtended(orderExtendedReq);
        baseCreateOrderRequest.setOrderClient(orderClient);
        baseCreateOrderRequest.setAppId(appId);
        baseCreateOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        baseCreateOrderRequest.setUserMobile(userLoginInfoDto.getMobile());
        baseCreateOrderRequest.setPhysicalGoodsFlag(OrderPhysicalGoodsFlagEnum.PHYSICALGOODSFLAG_ONE);
        CreateOrderRequest createOrderRequest = new CreateOrderRequest();
        createOrderRequest.setBaseCreateOrderRequest(baseCreateOrderRequest);
        createOrderRequest.setOpenId(userLoginInfoDto.getOpenId());
        createOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        CreateOrderResponse createOrderFlowResponse = orderBusinessService.createOrderFlow(createOrderRequest);

        if (ObjectUtils.notEqual(Integer.valueOf(ResponseResult.SUCCESS.getCode()), createOrderFlowResponse.getErrcode())) {
            return ResponseUtil.error(createOrderFlowResponse.getErrcode().toString(), createOrderFlowResponse.getErrmsg());
        }
        OrderBeanV1 fatherBeanListOne = createOrderFlowResponse.getData();
        OrderBeanV1 productBeanListOne = createOrderFlowResponse.getData();
        long totalAmount = createOrderFlowResponse.getData().getAmount();

        response.setTotalAmount(totalAmount);
        response.setFatherOrderBean(fatherBeanListOne);
        response.setProductOrderBean(productBeanListOne);
        return ResponseUtil.success(response);
    }

    private void preSetPayChannelType(BaseCreateOrderRequest request, CreateOrderVo createOrderVo) {
        Long amount = request.getAmount();
        String cardCode = createOrderVo.getCardCode();
        List<String> cardCodes = createOrderVo.getCardCodes();
        CreateOrderUnionPayCardVo unionPayCard = createOrderVo.getUnionPayCard();
        if (amount > 0) {
            PayChannelType channelType = null;
            // 风味卡支付
            if (Objects.nonNull(unionPayCard)) {
                channelType = PayChannelType.USVCP;
                this.setPrePayChannel(request, channelType);
            } else if (StringUtils.isNotBlank(cardCode) || CollectionUtils.isNotEmpty(cardCodes)) {
                // 储值卡支付
                channelType = PayChannelType.SVC;
                this.setPrePayChannel(request, channelType);
            } else {
                // 现金支付-> 不管 前端有传递
            }

        } else if (amount == 0) {
            PayChannelType channelType = PayChannelType.ZERO;
            this.setPrePayChannel(request, channelType);
        }
    }

    private void setPrePayChannel(BaseCreateOrderRequest request, PayChannelType channelType) {
        request.setPayChannelType(channelType.getIndex());
        request.setPayChannel(channelType.getEbcode());
        request.setPayChannelName(channelType.getName());
    }

    public OrderExtInfoDto setOrderExtInfo(AssortmentCustomerInfoVo userLoginInfoDto, StoreResponseDto storeResponseDto,
                                           Integer pushOrderTime, CreateOrderVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto) {

        Integer serviceTime = storeResponseDto.getServiceTime();
        String sessionId = createOrderVo.getSessionId();
        String version = createOrderVo.getVersion();
//        CreateOrderVo.BuyMemberCard memberCard = createOrderVo.getBuyMemberCard();

        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 orderExtInfoDto = new OrderExtInfoDto();
        orderExtInfoDto.setDeliveryHoursDayStart(deliveryHoursDayStart);
        orderExtInfoDto.setDeliveryHoursDayEnd(deliveryHoursDayEnd);
        orderExtInfoDto.setOpenid(userLoginInfoDto.getOpenId());
        //todo 字段多余，订单对象已有该字段
        orderExtInfoDto.setAppid(userLoginInfoDto.getWxAppId());
        orderExtInfoDto.setSessionId(sessionId);
        if (Objects.equals(serviceTime, null)) {
            serviceTime = 50;
        }
        orderExtInfoDto.setServiceTime(serviceTime);
        orderExtInfoDto.setPushOrderTime(pushOrderTime);
        orderExtInfoDto.setVersion(version);
//        if (memberCard != null && memberCard.getRuleId() != null) {
//            orderExtInfoDto.setRuleId(memberCard.getRuleId());
//        }
        // 扩展字段中存储 sessionKey
        orderExtInfoDto.setSessionKey(createOrderVo.getSessionKey());
        orderExtInfoDto.setFormId(createOrderVo.getFormId());
        //todo　多余字段
        orderExtInfoDto.setFromAppId(userLoginInfoDto.getWxAppId());
        if (StringUtils.isNotBlank(createOrderVo.getScene())) {
            orderExtInfoDto.setScene(createOrderVo.getScene());
        }
        if (null != shoppingCartGoodsDto && null != shoppingCartGoodsDto.getSendPoint()) {
            ShoppingCartGoodsDto.SendPoint sendPoint = shoppingCartGoodsDto.getSendPoint();
            orderExtInfoDto.setSendPointValidityDateDays(sendPoint.getValidityDateDays());
            orderExtInfoDto.setSendPointMaxNum(sendPoint.getMaxNum());
            orderExtInfoDto.setSendPointActivityCode(sendPoint.getActivityCode());
            orderExtInfoDto.setSendPointEndTime(sendPoint.getEndTime().getTime() + "");
            orderExtInfoDto.setSendPointSendPoint(sendPoint.getSendPoint());
            orderExtInfoDto.setSendPointStoreLevel(sendPoint.getStoreLevel());
            orderExtInfoDto.setIsContinueExchange(sendPoint.getIsContinueExchange());
        }
        if (null != shoppingCartGoodsDto && null != shoppingCartGoodsDto.getTotalScore()) {
            orderExtInfoDto.setTotalScore(shoppingCartGoodsDto.getTotalScore());
        }
        if (null != shoppingCartGoodsDto && null != shoppingCartGoodsDto.getPackageAmountCollectType()) {
            orderExtInfoDto.setPackageAmountCollectType(shoppingCartGoodsDto.getPackageAmountCollectType());
        }

//        orderExtInfoDto.setUnDistribution(createOrderVo.getUnDistribution());
        return orderExtInfoDto;
    }


    /**
     * 获取商户自定义提示信息配置
     *
     * @param partnerId
     * @return
     */
    public String getDefinitionMsg(String partnerId) {
        String definitionMsgKey = "partner_definition_msg";
        AssortmentOpenPlatformPartnerConfig partnerConfig = openPlatformPartnerConfigManager.selectPartnerConfigByPartnerKey(partnerId, definitionMsgKey, 1);
        if (partnerConfig == null) {
            return null;
        }
        return partnerConfig.getPartnerValue();
    }


    public RefundReasonResponseVo getRefundReasonResponseVo(RefundReasonEnum refundReasonEnum) {
        RefundReasonResponseVo refundReasonResponseVo = new RefundReasonResponseVo();
        refundReasonResponseVo.setCode(refundReasonEnum.getCode());
        refundReasonResponseVo.setDesc(refundReasonEnum.getDesc());
        return refundReasonResponseVo;
    }

    /**
     * 通知小助手发送申请退款公众号订阅消息
     *
     * @param orderBean
     */
    public void sendApplyRefundSubscriptionNotice(OrderBeanV1 orderBean, OrderRefundVo request) {
        try {
            OrderExtInfoDto extInfo = JSONObject.parseObject(orderBean.getExtInfo(), OrderExtInfoDto.class);
            if (extInfo == null || extInfo.getAppid() == null) {
                return;
            }
            AssortmentOpenPlatformWxappAuthorizer authorizerAppid = wxappAuthorizerManager.findAuthorizerByWxAppId(extInfo.getAppid());
            if (authorizerAppid == null) {
                return;
            }
            String orderId = orderBean.getOid();
            Double amount = orderBean.getAmount() / 100.0D;
            SendMessageRequest sendMessageRequest = new SendMessageRequest();
            sendMessageRequest.setMessageType("REFUND_ORDER");
            sendMessageRequest.setOrderId(orderId);
            sendMessageRequest.setPartnerId(orderBean.getCompanyId());
            sendMessageRequest.setRemark(request.getReason() + "," + request.getRemarks());
            sendMessageRequest.setStoreId(orderBean.getShopId());
            sendMessageRequest.setAmount(amount.toString());
            sendMessageRequest.setRemindMessage("用户申请退款");
            sendMessageRequest.setOrderTime(orderBean.getGmtPay() == null ? "" : DateUtil.convert2String(new Date(orderBean.getGmtPay()), "yyyy-MM-dd HH:mm:ss"));
            sendMessageRequest.setUserName(orderBean.getUserName());
            sendMessageRequest.setPhone(orderBean.getPhone());
            ecologyAdminApplicationClient.sendTemplateMessage(sendMessageRequest);
        } catch (Exception e) {
            AppLogUtil.errorLog("sendApplyRefundSubscriptionNotice_error", null, null, e);
        }
    }

    /**
     * 申请退款小票打印
     *
     * @param orderBean
     * @param orderRefundVo
     */
    private void printApplyRefundSmallTicket(OrderBeanV1 orderBean, OrderRefundVo orderRefundVo) {
        // 有云打印机 打印小票，杯贴
        try {
            List<AssortmentCloudPrinter> storePrinters = cloudPrinterManager.getStorePrinters(orderBean.getCompanyId(), orderBean.getShopId());
            if (null != storePrinters && storePrinters.size() > 0) {
                boolean printerStatus = false;
                for (AssortmentCloudPrinter cloudPrinter : storePrinters) {
                    if (null != cloudPrinter.getStatus() && cloudPrinter.getStatus() == 1) {
                        printerStatus = true;
                    }
                }
                //在线打印
                if (printerStatus) {
                    OrderPrintDto orderPrintDto = orderAdapter.convert2OrderPrintDto(orderBean);
                    String reason = orderRefundVo.getReason();
                    if (StringUtils.isNotBlank(orderRefundVo.getRemarks())) {
                        reason = reason + "," + orderRefundVo.getRemarks();
                    }
                    orderPrintDto.setRemark(reason);
                    fmAssistantCloudPrintClient.applyRefundPrint(orderPrintDto);
                }
            }
        } catch (Exception e) {
            AppLogUtil.errorLog("applyRefundPrint_error", null, null, e);
        }
    }

    /**
     * 历史判断围餐是从userLoginInfoDto判断iappid的。
     * 商城订单从前端传channelType区分，
     * 默认点餐
     */
    private String getQueryOrderChannelType(QueryOrderVo queryOrderVo, AssortmentCustomerInfoVo userLoginInfoDto) {
        String channelType = OrderChannelType.SAAS.getCode();
        if (IappIdType.WC_XCX.getCode().equals(userLoginInfoDto.getIappId())) {
            channelType = OrderChannelType.IWC.getCode();
        } else if (OrderChannelType.SAASMALL.getCode().equals(queryOrderVo.getChannelType())) {
            channelType = OrderChannelType.SAASMALL.getCode();
        } else if (UserLoginChannelEnum.APP.getCode().equals(userLoginInfoDto.getChannel())) {
            channelType = OrderChannelType.APP.getCode();
//        } else if (OrderChannelType.BEAUTIFUL.getCode().equals(queryOrderVo.getChannelType())) {
//            channelType = OrderChannelType.BEAUTIFUL.getCode();
        } else if (OrderChannelType.TIKTOK.getCode().equals(queryOrderVo.getChannelType())) {
            channelType = OrderChannelType.TIKTOK.getCode();
        } else if (OrderChannelType.CASHIER.getCode().equals(queryOrderVo.getChannelType())) {
            channelType = OrderChannelType.CASHIER.getCode();
        }
        return channelType;
    }

    public BaseResponse queryOrderByConditions(QueryOrderByConditionsRequestVo queryOrderByConditionsRequestVo) {
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(queryOrderByConditionsRequestVo.getSessionId());
        if (userLoginInfoDto == null || StringUtils.isBlank(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        String userId = userLoginInfoDto.getMemberId();
        List<QueryOrderByConditionsResponseVo> responseVos = null;
        OrderConditionsReq orderConditionsReq = new OrderConditionsReq();
        BeanUtil.convertBean(queryOrderByConditionsRequestVo, orderConditionsReq);
        orderConditionsReq.setUserId(userId);
        //  当前时间往前三个月的订单查询
        Date endTime = new Date();
        orderConditionsReq.setStartTimestamp(DateUtil.addMonths(endTime, -3).getTime() / 1000);
        orderConditionsReq.setEndTimestamp(endTime.getTime() / 1000);
        BaseDownLoadResponse<List<OrderInfoReqs>> orderInfoReqs = orderDownLoadSdkService.queryOrderByConditions(orderConditionsReq, LogThreadLocal.getTrackingNo());
        if (!String.valueOf(RESPONSE_SUCCESS_CODE).equals(orderInfoReqs.getCode())) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode());
        }
//        Map<String, Object> responseMap = Maps.newTreeMap();
        //用户无订单数据
        if (orderInfoReqs.getResult() == null || orderInfoReqs.getTotalNum() == 0) {
            return ResponseUtil.success();
        }
        responseVos = orderInfoReqs.getResult().stream().map(
                orderInfo -> {
                    QueryOrderByConditionsResponseVo queryOrderByConditionsResponseVo = new QueryOrderByConditionsResponseVo();
                    BeanUtil.convertBean(orderInfo, queryOrderByConditionsResponseVo);
//                    BeanUtil.convertBean(orderBean, queryOrderByConditionsResponseVo);
                    List<String> imgUrl = new ArrayList<>();
                    String extInfo = orderInfo.getExtInfo();
                    if (!StringUtil.isEmpty(extInfo)) {
                        JSONObject jsonObject = JSONObject.parseObject(extInfo);
                        JSONArray jsonArray = (JSONArray) JSONArray.parse(jsonObject.getString("imgUlr"));
                        for (int i = 0; i < jsonArray.size(); i++) {
                            imgUrl.add(String.valueOf(jsonArray.get(i)));
                        }
                    }
                    if (null != orderInfo.getOrderSettlementDetailList() && orderInfo.getOrderSettlementDetailList().size() > 0) {
                        queryOrderByConditionsResponseVo.setSettlementAmount(orderInfo.getOrderSettlementDetailList().stream().map(OrderSettlementResp::getSettlementAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                    } else {
                        queryOrderByConditionsResponseVo.setSettlementAmount(BigDecimal.ZERO);
                    }
                    queryOrderByConditionsResponseVo.setImgUrl(imgUrl);
                    queryOrderByConditionsResponseVo.setOrderStateValue(orderAdapter.getOrderStatusValue(orderInfo.getOrderState()));
                    SimpleDateFormat sdff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String sd = sdff.format(new Date(Long.valueOf(orderInfo.getCreateTime())));
                    queryOrderByConditionsResponseVo.setCreateTime(sd);
                    return queryOrderByConditionsResponseVo;
                }
        ).collect(Collectors.toList());
        return ResponseUtil.success(responseVos);
    }


    public void buildQueryOrderResponseVo(QueryOrderResponseVo queryOrderResponseVo, QueryOrderByIdResponse response, String partnerId) {

        if (null == response || response.getData() == null || !ObjectUtils.equals(response.getErrcode(), RESPONSE_SUCCESS_CODE)) {
            return;
        }

        OrderRelationService orderRelationService = orderRelationFactory.getQueryOrdrBuildService(partnerId);
        orderRelationService.queryOrdrBuild(queryOrderResponseVo, response);

    }

    /**
     * 超时回调直接退款
     *
     * @param orderBean
     */
    public void timeOutRefund(OrderBeanV1 orderBean) {
        //调用支付退款
        Integer abState = 4;
        String noPay = "8200404";
        //4 表示订单已经退款了
        if (abState.equals(orderBean.getAbnormalState())) {
            return;
        }
        OrderManagerRequest request = new OrderManagerRequest();
        request.setReason("订单已关闭,支付未及时回调");
        Integer state = com.freemud.sdk.api.assortment.order.enums.PayRefundStatus.SUCCESS.getCode();
        PayRefundResponse commonPayRefundResponse = paymentHandle.getCommonPayRefundResponse(request, orderBean);
        com.freemud.sdk.api.assortment.order.enums.PayRefundStatus payRefundStatus = commonPayRefundResponse.getPayRefundStatus();

        SdkUpdateAbnormalState sdkUpdateAbnormalState = new SdkUpdateAbnormalState();
        String desc = "支付未及时回调";
        switch (payRefundStatus){
            case SUCCESS:
                sdkUpdateAbnormalState.setAbnormalDesc(desc + ",退款成功");
                break;
            case FAIL:
                sdkUpdateAbnormalState.setAbnormalDesc(desc + ",退款失败");
                break;
            default:
                sdkUpdateAbnormalState.setAbnormalDesc(desc + ",等待支付回调中");
        }
        sdkUpdateAbnormalState.setPartnerId(orderBean.getCompanyId());
        sdkUpdateAbnormalState.setAbnormalState(4);
        sdkUpdateAbnormalState.setOrderCode(orderBean.getOid());
        orderSdkService.updateAbnormalState(sdkUpdateAbnormalState);
    }

    private Boolean isQueryEs(Integer queryOrderStatus) {

        if (ObjectUtils.equals(QueryOrderStatus.TAKE_MEAL.getCode(), queryOrderStatus) || ObjectUtils.equals(QueryOrderStatus.NO_PAY.getCode(), queryOrderStatus)) {
            return Boolean.FALSE;
        }

        return Boolean.TRUE;
    }

    public BaseResponse queryTodayOrders(QueryOrderByConditionsRequestVo queryOrderByConditionsRequestVo) {
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(queryOrderByConditionsRequestVo.getSessionId());
        if (userLoginInfoDto == null || StringUtils.isBlank(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        String userId = userLoginInfoDto.getMemberId();
        Map<String, Object> result = new HashMap<>(0);
        Integer totalOrders = 0;
        try {
            OrderConditionsReq orderConditionsReq = new OrderConditionsReq();
            BeanUtil.convertBean(queryOrderByConditionsRequestVo, orderConditionsReq);
            orderConditionsReq.setUserId(userId);
            Date startDate = DateUtil.convert2Date(DateUtil.convert2String(new Date(), DateUtil.FORMAT_yyyyMMdd_date) + " 00:00:00", DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
            orderConditionsReq.setStartTimestamp(startDate.getTime() / 1000);
            orderConditionsReq.setEndTimestamp(new Date().getTime() / 1000);
            BaseDownLoadResponse<List<OrderInfoReqs>> orderInfoReqs = orderDownLoadSdkService.queryOrderByConditions(orderConditionsReq, LogThreadLocal.getTrackingNo());
            if (!String.valueOf(RESPONSE_SUCCESS_CODE).equals(orderInfoReqs.getCode())) {
                return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode());
            }
            totalOrders = null == orderInfoReqs.getTotalNum() ? 0 : orderInfoReqs.getTotalNum();
            result.put("totalOrders", totalOrders);
        } catch (Exception e) {
            AppLogUtil.errorLog("queryTodayOrders", gson.toJson(queryOrderByConditionsRequestVo), null, e);
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR);
        }
        return ResponseUtil.success(result);
    }

    @Override
    public BaseResponse spellGroupOrderFailRefund(SpellGroupFailRefundVo refundVo) {
        List<String> orderCodeList = refundVo.getOrderCodeList();
        if (CollectionUtils.isEmpty(orderCodeList) || orderCodeList.stream().anyMatch(StringUtils::isBlank)) {
            return ResponseUtil.error(ResponseResult.PARAMETER_MISSING.getCode(), "订单号不能为空");
        }
        // 进行一次去重
        orderCodeList = orderCodeList.stream().distinct().collect(Collectors.toList());

        // 查询订单列表
        QueryOrdersResponse orderListResp = getOrderList(orderCodeList);
        if (!RESPONSE_SUCCESS_CODE.equals(orderListResp.getErrcode()) || orderListResp.getData() == null || CollectionUtils.isEmpty(orderListResp.getData().getOrders())) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "订单信息不存在");
        }

        String string = JSONArray.toJSONString(orderListResp.getData().getOrders());
        JSONArray jsonArray = JSONArray.parseArray(string);
        List<OrderBeanV1> orderBeanList = jsonArray.toJavaList(OrderBeanV1.class);
        // 前置检查
        BaseResponse checkResponse = batchRefundBeforeCheck(orderCodeList, orderBeanList);
        if (!RESPONSE_SUCCESS_CODE.equals(orderListResp.getErrcode())) {
            return ResponseUtil.error(checkResponse.getCode(), checkResponse.getMessage());
        }

        // 过滤订单
        // todo 此时存在处理中的售后怎么办?
        orderBeanList = filterOrder(orderBeanList);
        if (orderBeanList.isEmpty()) {
            return ResponseUtil.success();
        }
        // 批量退款
        SpellGroupBatchOrderRefundVo orderRefundVo = new SpellGroupBatchOrderRefundVo();
        orderRefundVo.setPartnerId(orderBeanList.get(0).getCompanyId());
        orderRefundVo.setStoreId(orderBeanList.get(0).getShopId());
        orderRefundVo.setReason(Optional.ofNullable(RefundReasonEnum.getSpellGroupReasonByIndex(refundVo.getReason())).orElse(RefundReasonEnum.Other).getDesc());
        orderRefundVo.setRemarks(orderRefundVo.getReason());
        // 拼团失败取消 默认为只退款不退货
        orderRefundVo.setRefundMode(RefundModeEnum.UN_REFUND_GOODS.getIndex());

        // 拼团失败逻辑处理
        BaseResponse baseResponse = batchRefundOrderNoTake(orderRefundVo, orderBeanList, AfterSalesType.SYSTEM_CANCEL, true);
        if (baseResponse != null) {
            return baseResponse;
        }
        return ResponseUtil.success();
    }

    private QueryOrdersResponse getOrderList(List<String> orderCodeList) {
        BatchQueryByCodesRequest baseQueryOrderRequest = new BatchQueryByCodesRequest();
        baseQueryOrderRequest.setOrderCodes(orderCodeList);
        baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        return orderCenterSdkService.batchQueryByCodes(baseQueryOrderRequest);
    }

    private List<OrderBeanV1> filterOrder(List<OrderBeanV1> orderBeans) {
        List<OrderBeanV1> list = new ArrayList<>(orderBeans.size());
        for (OrderBeanV1 orderBean : orderBeans) {
            if (Objects.equals(PayStatus.NOT_PAY.getCode(), orderBean.getPayStatus())
                    || Objects.equals(NewOrderStatus.PENDING_PAYMENT.getIndex(), orderBean.getStatusV2())) {
                continue;
            }
            if (NewOrderStatus.CLOSED.getIndex().equals(orderBean.getStatusV2())) {
                continue;
            }
            list.add(orderBean);
        }
        return list;
    }

    private BaseResponse batchRefundBeforeCheck(List<String> orderCodeList, List<OrderBeanV1> orderBeans) {
        List<String> notFoundCodeList = new ArrayList<>(orderCodeList);
        List<String> notSupportOrderCodeList = new ArrayList<>(orderCodeList.size());
        for (OrderBeanV1 orderBean : orderBeans) {
            notFoundCodeList.remove(orderBean.getOid());
            // 是否是微商城拼团订单
            if (!Objects.equals(MarketTypeEnum.GROUPB.getIndex().byteValue(), orderBean.getMarketingType())) {
                notSupportOrderCodeList.add(orderBean.getOid());
            }
        }
        StringBuilder builder = new StringBuilder();
        if (!notFoundCodeList.isEmpty()) {
            builder.append(String.format("部分订单信息不存在:%s ,", JSON.toJSONString(notFoundCodeList)));
        }
        if (!notSupportOrderCodeList.isEmpty()) {
            builder.append(String.format("不是微商城拼团订单:%s", JSON.toJSONString(notSupportOrderCodeList)));
        }
        if (builder.length() != 0) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), builder.toString());
        }
        return ResponseUtil.success();
    }


    /**
     * 拼团失败逻辑处理
     * <p>应当只用于售前</p>
     * <p>
     * 1.调用支付退款
     * 2.根据支付退款返回状态组装订单取消参数,调用订单取消接口
     *
     * @param orderRefundVo
     * @param orderBeans
     * @param afterSalesType
     * @param isRefundDeliveryFee
     * @return
     */
    private BaseResponse batchRefundOrderNoTake(SpellGroupBatchOrderRefundVo orderRefundVo, List<OrderBeanV1> orderBeans, AfterSalesType afterSalesType, Boolean isRefundDeliveryFee) {
        if (CollectionUtils.isEmpty(orderBeans)) {
            return null;
        }
        long refundId = System.currentTimeMillis();
        String partnerId = orderRefundVo.getPartnerId();
        String storeId = orderRefundVo.getStoreId();
        // 退款批次号
        Long batchId = 0L;

        List<OrderBeanV1> payRefundOrderCodes = new ArrayList<>(orderBeans.size());
        Set<String> unPayRefund = new HashSet<>(orderBeans.size());
        orderBeans.forEach(orderBean -> {
            // 金额为0不需要退款
            if (orderBean.getAmount() > 0) {
                payRefundOrderCodes.add(orderBean);
            } else {
                unPayRefund.add(orderBean.getOid());
            }
        });

        // 1 进行批量退款
        if (!payRefundOrderCodes.isEmpty()) {
            PayBatchRefundResponse response = null;
            // 1.1 组装批量退款参数
            BatchOrderRefundV2Request batchOrderRefundV2Request = orderAdapter.getBatchOrderRefundV2Request(payRefundOrderCodes, partnerId, storeId);
            // 1.2 调用支付服务退款
            response = payServiceImpl.batchRefund(batchOrderRefundV2Request);
            PayBatchRefundResponse.BatchRefundBatchIdData batchIdData;
            // 注意响应值是200
            if (Objects.isNull(response) || !Objects.equals(ResponseCodeConstant.PAYMENT_RESPONSE_SUCCESS, response.getCode())
                    || Objects.isNull(batchIdData = response.getData()) || Objects.isNull(batchIdData.getBatchId())) {
                return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "批量退款失败");
            }
            // 获取退款批次号
            batchId = batchIdData.getBatchId();
        }

        // 2 循环退单
        List<OrderBeanV1> failOrderBean = new ArrayList<>();
        String trackingNo = LogThreadLocal.getTrackingNo();
        for (OrderBeanV1 orderBean : orderBeans) {
            CancelOrderRequest cancelOrderRequest = orderAdapter.convent2CancelOrderRequest(orderBean.getOid(),
                    partnerId, afterSalesType, orderRefundVo.getReason(), trackingNo, Long.toString(refundId));

            cancelOrderRequest.setOperator(Optional.ofNullable(cancelOrderRequest.getOperator()).orElse(orderBean.getUserName()));
            cancelOrderRequest.setPartnerId(orderBean.getCompanyId());
            // 增加拓展信息
            CancelOrderRequest.AfterSalesOrderExtInfoReq salesOrderExtInfoReq = new CancelOrderRequest.AfterSalesOrderExtInfoReq();
            salesOrderExtInfoReq.setRefundMode(orderRefundVo.getRefundMode());
            cancelOrderRequest.setExtInfoReq(salesOrderExtInfoReq);

            if (unPayRefund.contains(orderBean.getOid())) {
                // 无需退款
                cancelOrderRequest.setCreateEvent(AfterSalesOrderCreateEventEnum.REFUND_COMPLETE.getCreateEvent());
                cancelOrderRequest.setRefundState(AfterSalesRefunStateEnum.STATE_4.getIndex());
            } else {
                // 记录退款批次
                cancelOrderRequest.setCreateEvent(AfterSalesOrderCreateEventEnum.RETURN_COMPLETE.getCreateEvent());
                cancelOrderRequest.setRefundState(AfterSalesRefunStateEnum.STATE_4.getIndex());
                salesOrderExtInfoReq.setBatchRefundId(batchId);
                // todo 发生延时mq用于检查
            }
            cancelOrderRequest.setReqRemark(orderRefundVo.getRemarks());
            cancelOrderRequest.setRefundDeliveryAmount(isRefundDeliveryFee);
            boolean fail = true;
            BaseOrderResponse baseOrderResponse = orderCenterSdkService.orderCancel(cancelOrderRequest);
            if (baseOrderResponse == null || baseOrderResponse.getData() == null || !ObjectUtils.equals(ResponseConstant.SUCCESS_RESPONSE_CODE, baseOrderResponse.getErrcode())) {

            } else {
                fail = false;
                // 删除订单 通知活动添加商品库存
                orderQueueService.backOrdersStatusChange(orderBean.getOid(), orderBean.getStatus(), orderBean.getPayStatus());
            }
            // 记录失败
            if (fail) {
                failOrderBean.add(orderBean);
            }
        }
        // todo 失败入库
        return ResponseUtil.success();
    }


    @Override
    public BaseResponse scoreRecord(QueryOrderVo queryOrderVo) {
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(queryOrderVo.getSessionId());
        if (userLoginInfoDto == null || StringUtils.isBlank(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        Date startDate;
        Date endDate;
        if (StringUtils.isBlank(queryOrderVo.getStartDate()) || StringUtils.isBlank(queryOrderVo.getEndDate())) {
            Date now = new Date();
            startDate = DateUtil.addMonths(now, -6);
            endDate = DateUtil.addDays(now, 1);
        } else {
            String startDateStr = queryOrderVo.getStartDate() + " 00:00:00";
            String endDateStr = queryOrderVo.getEndDate() + " 23:59:59";
            startDate = DateUtil.convert2Date(startDateStr, "yyyy-MM-dd HH:mm:ss");
            if (startDate == null) {
                return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "查询订单开始时间格式不正确");
            }
            endDate = DateUtil.convert2Date(endDateStr, "yyyy-MM-dd HH:mm:ss");
            if (endDate == null) {
                return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "查询订单结束时间格式不正确");
            }
        }

        OrderConditionsReq queryOrdersDto = new OrderConditionsReq();
        queryOrdersDto.setUserId(userLoginInfoDto.getMemberId());
        queryOrdersDto.setPartnerId(userLoginInfoDto.getPartnerId());
        queryOrdersDto.setPageSize(queryOrderVo.getPageSize() != null ? queryOrderVo.getPageSize() : 500);
        queryOrdersDto.setPageNum(queryOrderVo.getPageNumber() != null ? queryOrderVo.getPageNumber() : 1);
        queryOrdersDto.setStartTimestamp(startDate.getTime() / 1000);
        queryOrdersDto.setEndTimestamp(endDate.getTime() / 1000);
        queryOrdersDto.setOrderClients(Arrays.asList(13));
        queryOrdersDto.setBizType(4);
        queryOrdersDto.setOrderStatus(NewOrderStatus.COMPLETE.getIndex());
//        queryOrdersDto.setPayStatuses(Arrays.asList(PayStatus.HAVE_PAID.getCode()));
        BaseDownLoadResponse<List<OrderInfoReqs>> response = orderDownLoadSdkService.queryOrderByConditions(queryOrdersDto, LogThreadLocal.getTrackingNo());

        List<ScoreRecordVo> result = new ArrayList<>();
        if (null == response || null == response.getResult()) {
            return ResponseUtil.success(result);
        }
        List<OrderInfoReqs> list = response.getResult();
        list.forEach(order -> {
            ScoreRecordVo responseVo = new ScoreRecordVo();
            responseVo.setOrderCode(order.getOrderCode());
            if (order.getCreateTime() != null) {
                responseVo.setCreateTime(Long.parseLong(order.getCreateTime()));
            }
            if (CollectionUtils.isNotEmpty(order.getOrderItemList())) {
                responseVo.setProductName(order.getOrderItemList().get(0).getProductName());
                responseVo.setProductQuantity(order.getOrderItemList().get(0).getProductQuantity());
            }
            result.add(responseVo);
        });
        return ResponseUtil.success(result);
    }

    @Override
    public BaseResponse<List<OrderCountResp>> selectCountOrdersByPartnerIds(OrderCountRequestVo orderCountRequestVo, String trackingNo) {
        OrderCountReqs orderCountReqs = new OrderCountReqs();
        BeanUtil.convertBean(orderCountRequestVo, orderCountReqs);

        OrderBaseResp<List<OrderCountResp>> result = orderSdkService.countOrdersByPartnerIds(orderCountReqs, trackingNo);
        if (Objects.isNull(result)) {
            return new BaseResponse(ResponseResultEnum.SYSTEM_ERROR.getCode(), ResponseResultEnum.SYSTEM_ERROR.getMessage(), "", null);
        }
        if (!ResponseResultEnum.SUCCESS.getCode().equalsIgnoreCase(result.getCode()) || Objects.isNull(result.getResult())) {
            return new BaseResponse(result.getCode(), result.getMessage(), "", null);
        }
        return ResponseUtil.success(result.getResult());
    }

    @Override
    public BaseResponse<OrderStateMonitorInfoVo> queryOrderStateMonitorInfo(String orderCode, String partnerId, Byte orderClient) {
        BaseQueryOrderRequest request = new BaseQueryOrderRequest();
        request.setOrderId(orderCode);
        request.setPartnerId(partnerId);
        if (Objects.nonNull(orderClient) && !Objects.equals(orderClient, 0)) {
            request.setOrderClient(orderClient.toString());
        }
        // 实时查询，暂时不查询es
        OrderStateInfoResp response = orderCenterSdkService.queryOrderStateInfo(orderCode, partnerId, orderClient, LogThreadLocal.getTrackingNo());
        if (Objects.isNull(response) || !Objects.equals(RESPONSE_SUCCESS_CODE, response.getErrcode()) || response.getData() == null) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR);
        }
        OrderStateMonitorInfoVo infoVo = new OrderStateMonitorInfoVo();
        infoVo.setOrderCode(response.getData().getOrderCode());
        infoVo.setOrderState(response.getData().getOrderState());
        infoVo.setStateTimeout(response.getData().getStateTimeout());
        infoVo.setNeedMonitor(Objects.equals(response.getData().getStateTimeout(), 0L));
        infoVo.setUpdateTimestamp(response.getData().getStateUpdateTimestamp());

        return ResponseUtil.success(infoVo);
    }

    @Override
    public BaseResponse submitAppeal(OrderAppealVo orderAppealVo) {

        String sessionId = orderAppealVo.getSessionId();
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(sessionId);
        if (userLoginInfoDto == null || StringUtils.isEmpty(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }

        SubmitAppealReq submitAppealReq = new SubmitAppealReq();

        submitAppealReq.setPartnerId(userLoginInfoDto.getPartnerId());
        submitAppealReq.setOrderCode(orderAppealVo.getOid());
        submitAppealReq.setAppealContent(orderAppealVo.getContent());
        submitAppealReq.setMobile(userLoginInfoDto.getMobile());
        submitAppealReq.setOperator(userLoginInfoDto.getNickName());
        OrderBaseResp baseResponse = orderSdkService.submitAppeal(submitAppealReq, LogThreadLocal.getTrackingNo());
        if (Objects.isNull(baseResponse) || !Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, baseResponse.getCode())) {
            return ResponseUtil.error(ResponseResult.ORDER_APPEAL_ERR);
        }
        return ResponseUtil.success();
    }

    @Override
    public BaseResponse queryOrderAppeal(OrderAppealVo orderAppealVo) {
        String sessionId = orderAppealVo.getSessionId();
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(sessionId);
        if (userLoginInfoDto == null || StringUtils.isEmpty(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        SubmitAppealReq submitAppealReq = new SubmitAppealReq();
        submitAppealReq.setPartnerId(userLoginInfoDto.getPartnerId());
        submitAppealReq.setOrderCode(orderAppealVo.getOid());
        OrderBaseResp<QueryOrderAppealVo> baseResponse = orderSdkService.queryOrderAppeal(submitAppealReq, LogThreadLocal.getTrackingNo());
        if (Objects.isNull(baseResponse) || !Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, baseResponse.getCode())) {
            return ResponseUtil.error(ResponseResult.ORDER_APPEAL_ERR);
        }
        QueryOrderAppealResponseVo responseVo = new QueryOrderAppealResponseVo();
        if (baseResponse.getResult() != null) {
            responseVo.setAppealContent(baseResponse.getResult().getAppealContent());
            responseVo.setMobile(baseResponse.getResult().getMobile());
        }
        return ResponseUtil.success(responseVo);
    }

    @Override
    public BaseResponse queryInvoiceList(QueryInvoiceReq queryInvoiceReq) {
        if (queryInvoiceReq.getSelectMonth() == null) {
            queryInvoiceReq.setStartTime(DateUtil.addMonths(new Date(), -2));//如果前端传null，聚合往前2个月
            queryInvoiceReq.setEndTime(new Date());//如果前端传null，聚合当前时间
        } else {
            queryInvoiceReq.setStartTime(DateUtil.convert2Date(queryInvoiceReq.getSelectMonth() + "-01", DateUtil.FORMAT_YMD));//yyyy-MM拼接-01
            queryInvoiceReq.setEndTime((DateUtil.addMonths(DateUtil.convert2Date(queryInvoiceReq.getSelectMonth() + "-01", DateUtil.FORMAT_YMD), 1)));////yyyy-（MM+1）拼接下月-01
        }
        QueryInvoiceRepDto queryInvoiceRepDto = orderServiceClient.queryInvoiceList(queryInvoiceReq);
        if (queryInvoiceRepDto == null || !Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, queryInvoiceRepDto.getCode())) {
            return ResponseUtil.error(ResponseResult.QUERY_INVOICE_ERR);
        }
        if (queryInvoiceRepDto.getResult() != null) {
            for (QueryInvoiceRep queryInvoiceRep : queryInvoiceRepDto.getResult().getItemList()) {
                String scanUrl = queryInvoiceRep.getInvoiceUrl();
                if (scanUrl.startsWith("<![CDATA[")) {
                    scanUrl = scanUrl.substring(9, scanUrl.length());
                }
                if (scanUrl.endsWith("]]>")) {
                    scanUrl = scanUrl.substring(0, scanUrl.length() - 3);
                }
                queryInvoiceRep.setInvoiceUrl(scanUrl);
            }
        }
        return ResponseUtil.success(queryInvoiceRepDto.getResult());
    }

    @Override
    public BaseResponse<InvoiceCreateResponseVo> createAndGetOrderInvoice(CreateOrderInvoiceRequest request) {
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(request.getSessionId());
        if (userLoginInfoDto == null || StringUtils.isEmpty(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }

        // 【1.1】. 校验订单数据
        BaseResponse checkOrderDataResponse = orderInvoiceAdapter.checkOrderData(request);
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, checkOrderDataResponse.getCode())) {
            return checkOrderDataResponse;
        }
        // 【1.2】. 查询订单详情
        QueryOrdersResponse orderResponse = this.getOrderList(request.getOrderCodes());
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS, orderResponse.getErrcode())) {
            return ResponseUtil.error(orderResponse.getErrcode() + "", orderResponse.getErrmsg());
        }
        QueryOrdersResponse.DataBean dataBean = orderResponse.getData();
        if (null == dataBean || CollectionUtils.isEmpty(dataBean.getOrders())) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERY_ERR);
        }

        // 【2】. 校验订单开票数据
        BaseResponse checkResponse = orderInvoiceAdapter.checkOrderOpenInvoiceData(dataBean.getOrders(), request, userLoginInfoDto);
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, checkResponse.getCode())) {
            return checkResponse;
        }

        // 【3.1】. 查询开票配置数据
        QueryInvoiceConfigRequest configRequest = new QueryInvoiceConfigRequest();
        configRequest.setPartnerId(request.getPartnerId());
        BaseResponse<OrderInvoiceResponse> orderInvoiceConfigResponse = microOpenplatformClient.QueryInvoiceConfigByPartnerId(configRequest);
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, orderInvoiceConfigResponse.getCode())) {
            return ResponseUtil.error(orderInvoiceConfigResponse.getCode(), orderInvoiceConfigResponse.getMessage());
        }
        OrderInvoiceResponse orderInvoiceConfig = orderInvoiceConfigResponse.getResult();
        if (null == orderInvoiceConfig) {
            return ResponseUtil.error(ResponseResult.ORDER_INVOICE_CONFIG_IS_NULL);
        }

        // 【3.2】. 调用支付接口开订单发票，非码支付系统内部再调用三方-百望系统开票
        InvoiceCreateRequest invoiceCreateRequest = orderInvoiceAdapter.convert2InvoiceCreateRequest(dataBean.getOrders(), request, orderInvoiceConfig);
        com.freemud.application.sdk.api.base.BaseResponse<InvoiceCreateResponse> invoiceResponse = payServiceImpl.createInvoice(invoiceCreateRequest);
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, invoiceResponse.getCode()) || null == invoiceResponse.getData()) {
            return ResponseUtil.error(invoiceResponse.getCode(), invoiceResponse.getMessage());
        }

        InvoiceCreateResponse invoiceData = invoiceResponse.getData();
        // 【3.1】.发票格式处理
        invoiceData.setScanUrl(orderInvoiceAdapter.handleInvoiceData(invoiceData.getScanUrl()));

        // 【4】. 录入发票记录，修改订单发票状态
        OrderInvoiceRequest orderInvoiceRequest = orderInvoiceAdapter.convert2OrderInvoiceRequest(invoiceCreateRequest, invoiceData,
                orderInvoiceConfig, request.getOrderCodes(), userLoginInfoDto.getMemberId());
        BaseResponse orderInvoiceResponse = orderServiceClient.createInvoice(orderInvoiceRequest);
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, orderInvoiceResponse.getCode())) {
            return orderInvoiceResponse;
        }

        InvoiceCreateResponseVo responseVo = new InvoiceCreateResponseVo();
        responseVo.setScanUrl(invoiceData.getScanUrl());
        return ResponseUtil.success(responseVo);
    }

    @Override
    public BaseResponse<OrderInvoiceConfigVo> queryInvoiceConfig(GetInvoiceConfigRequest request) {
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(request.getSessionId());
        if (userLoginInfoDto == null || StringUtils.isEmpty(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }

        // 查询发票配置
        QueryInvoiceConfigRequest configRequest = new QueryInvoiceConfigRequest();
        configRequest.setPartnerId(request.getPartnerId());
        BaseResponse<OrderInvoiceResponse> orderInvoiceConfigResponse = microOpenplatformClient.QueryInvoiceConfigByPartnerId(configRequest);
        if (!Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, orderInvoiceConfigResponse.getCode())) {
            return ResponseUtil.error(orderInvoiceConfigResponse.getCode(), orderInvoiceConfigResponse.getMessage());
        }
        OrderInvoiceResponse orderInvoiceConfig = orderInvoiceConfigResponse.getResult();
        if (null == orderInvoiceConfig) {
            return ResponseUtil.error(ResponseResult.ORDER_INVOICE_CONFIG_IS_NULL);
        }
        OrderInvoiceConfigVo configVo = new OrderInvoiceConfigVo();
        BeanUtil.convertBean(orderInvoiceConfig, configVo);
        return ResponseUtil.success(configVo);
    }


    /**
     * 支付退款成功，订单未创建售后单
     *
     * @return
     */
    private String cancelOrder(OrderBeanV1 orderBean) {
        CancelOrderRequest cancelOrderRequest = orderAdapter.convent2CancelOrderRequest(orderBean.getOid(),
                orderBean.getCompanyId(), AfterSalesType.OTHER, "退款回掉取消订单", LogThreadLocal.getTrackingNo(), null);
        cancelOrderRequest.setOperator("退款成功回掉");
        cancelOrderRequest.setPartnerId(orderBean.getCompanyId());
        //退款成功
        cancelOrderRequest.setCreateEvent(AfterSalesOrderCreateEventEnum.REFUND_COMPLETE.getCreateEvent());
        cancelOrderRequest.setReqRemark("");
        cancelOrderRequest.setRefundState(AfterSalesRefunStateEnum.STATE_4.getIndex());
        cancelOrderRequest.setRefundDeliveryAmount(true);
        BaseOrderResponse baseOrderResponse = orderCenterSdkService.orderCancel(cancelOrderRequest);

        orderQueueService.backOrdersStatusChange(orderBean.getOid(), orderBean.getStatus());
        return newSendPaySuccessNoticeMessage();
    }


    @Override
    public BaseResponse couponOrderRefund(OrderRefundVo orderRefundVo, int flag) {
        if (StringUtils.isEmpty(orderRefundVo.getReason())) {
            orderRefundVo.setReason("退款");
        }
        // 查询订单
        BaseResponse<OrderBeanV1> orderResponse = this.checkOrderAndGetOrderBean(orderRefundVo.getOid());
        if (!Objects.equals(orderResponse.getCode(), ResponseResult.SUCCESS.getCode())) {
            return orderResponse;
        }
        OrderBeanV1 orderBean = orderResponse.getResult();

        AssortmentCustomerInfoVo userLoginInfoDto;
        if (flag > 0) {
            userLoginInfoDto = new AssortmentCustomerInfoVo();
            userLoginInfoDto.setMemberId(orderBean.getUserId());
            userLoginInfoDto.setWxAppId(orderBean.getAppId());
        } else {
            // 校验用户是否登录
            BaseResponse<AssortmentCustomerInfoVo> baseResponse = this.checkUserLoginInfoDto(orderRefundVo.getSessionId());
            if (!Objects.equals(baseResponse.getCode(), ResponseResult.SUCCESS.getCode())) {
                return baseResponse;
            }
            userLoginInfoDto = baseResponse.getResult();
        }

        // 校验操作
        BaseResponse checkResult = this.couponOrderRefundCheck(userLoginInfoDto, orderBean);
        if (!Objects.equals(checkResult.getCode(), ResponseResult.SUCCESS.getCode())) {
            return checkResult;
        }
        // fisherman 调用会员获取券的有效性,是否有转赠状态
        checkResult = this.customerExtendHandle(orderBean);
        if (!Objects.equals(checkResult.getCode(), ResponseResult.SUCCESS.getCode())) {
            return checkResult;
        }

        // fisherman 券作废
        checkResult = this.couponOnLineHandle(orderBean);
        if (!Objects.equals(checkResult.getCode(), ResponseResult.SUCCESS.getCode())) {
            return checkResult;
        }

        // 走正常退款订单逻辑 这里是否可以丢MQ 异步操作
        try {
            this.doCouponOrderRefund(orderBean, orderRefundVo);
        } catch (Exception e) {
            RefundFailureRequestDTO requestDTO = RefundFailureRequestDTO.builder().orderCode(orderBean.getOid())
                    .failureType(RefundFailureRequestDTO.FAILURETYPE_SYSTEM_ERROR)
                    .reason(JSON.toJSONString(e.getMessage()))
                    .partnerId(orderBean.getCompanyId())
                    .operator("")
                    .ver(0).build();
            orderServiceClient.refundFailures(requestDTO);
        }
        return ResponseUtil.success();
    }

    /**
     * @param orderBean
     * @return
     */
    private BaseResponse customerExtendHandle(OrderBeanV1 orderBean) {
        BaseResponse<List<String>> baseResponse = this.couponOrderCommomCheck(orderBean);
        if (baseResponse.getCode().compareTo(ResponseResult.SUCCESS.getCode()) != 0) {
            return baseResponse;
        }
        // 获取优惠券
        List<String> couponCodeList = baseResponse.getResult();
        UserCouponCheckRequest request = new UserCouponCheckRequest();
        request.setPartnerId(orderBean.getCompanyId());
        request.setMemberId(orderBean.getUserId());
        request.setCouponCodes(couponCodeList);
        UserBaseResponsDTO<List<String>> responsDTO = customerExtendClient.getMemberCouponCodes(request);
        if (responsDTO == null || !Objects.equals(responsDTO.getCode(), ResponseResult.SUCCESS.getCode())) {
            return ResponseUtil.error(ResponseResult.COUPON_CANCEL_FAIL.getCode(), "会员服务调用失败");
        }
        List<String> responsDTOData = responsDTO.getData();
        if (CollectionUtils.isEmpty(responsDTOData) || !responsDTOData.containsAll(couponCodeList)) {
            // fisherman 文案让产品提供
            return ResponseUtil.error(ResponseResult.COUPON_CANCEL_FAIL.getCode(), "您购买的优惠券已转赠给好友，不支持退款");
        }
        return ResponseUtil.success();
    }

    /**
     * 调用券码作废操作
     *
     * @param orderBean
     * @return
     */
    private BaseResponse couponOnLineHandle(OrderBeanV1 orderBean) {
        if (orderBean.getBizType().compareTo(BizTypeEnum.SALE_COUPON.getBizType()) != 0) {
            return ResponseUtil.error(ResponseResult.COUPON_ORDER_VERIFY_FAIL.getCode(), "不是卖券订单");
        }
        BaseResponse<List<String>> baseResponse = this.couponOrderCommomCheck(orderBean);
        if (baseResponse.getCode().compareTo(ResponseResult.SUCCESS.getCode()) != 0) {
            return baseResponse;
        }
        // 获取优惠券
        List<String> couponCodeList = baseResponse.getResult();

        CheckAndCancelRequest request = new CheckAndCancelRequest();
        request.setPartnerId(Integer.parseInt(orderBean.getCompanyId()));
        request.setMemberId(orderBean.getUserId());
        request.setCouponCodeList(couponCodeList);

        CouponResponseDTO<CheckAndCancelResponseDTO> responseDTO = couponOnlineClient.checkandcancel(request);
        if (responseDTO == null
                || !Objects.equals(responseDTO.getStatusCode(), 100)) {
            // 直接接口调用失败,
            return ResponseUtil.error(ResponseResult.COUPON_CANCEL_FAIL.getCode(), "操作失败,请稍后重试");
        }
        CheckAndCancelResponseDTO result = responseDTO.getResult();
        // 作废成功
        if (result.getResultCode().compareTo(CheckAndCancelResponseDTO.SUCCESS) == 0) {
            return ResponseUtil.success();
        }
        String memo = result.getMemo();
        return ResponseUtil.error(ResponseResult.COUPON_CANCEL_FAIL.getCode(), memo);

    }

    private BaseResponse<List<String>> couponOrderCommomCheck(OrderBeanV1 orderBean) {
        List<OrderSettlementResp> orderSettlementDetailList = orderBean.getOrderSettlementDetailList();
        if (CollectionUtils.isEmpty(orderSettlementDetailList)) {
            return ResponseUtil.error(ResponseResult.COUPON_CANCEL_FAIL.getCode(), "没有优惠券信息");
        }
        // 获取优惠券
        List<String> couponCodeList = orderSettlementDetailList.stream()
                .filter(s -> s.getSettlementType().compareTo(SettlementTypeEnum.SEND_COUPON.getSettlementType()) == 0)
                .map(OrderSettlementResp::getExternalObjectId).collect(Collectors.toList());

        // fisherman 核销券失败的逻辑处理
        if (CollectionUtils.isEmpty(couponCodeList)) {
            return ResponseUtil.error(ResponseResult.COUPON_CANCEL_FAIL.getCode(), "没有优惠券信息");
        }
        return ResponseUtil.success(couponCodeList);
    }


    @Override
    public BaseResponse couponOrderRefundRetry(OrderRefundRetryVo orderRefundRetryVo) {

        QueryRefundFailuresListReq queryRefundFailuresListReq = new QueryRefundFailuresListReq();
        queryRefundFailuresListReq.setId(orderRefundRetryVo.getId());
        BaseResponse<List<QueryRefundFailuresListDto>> queryRefundFailuresListDtoBaseResponse = orderServiceClient.refundFailuresList(queryRefundFailuresListReq);
        if (!ResponseConstant.SUCCESS_RESPONSE_CODE_STR.equals(queryRefundFailuresListDtoBaseResponse.getCode())
                || CollectionUtils.isEmpty(queryRefundFailuresListDtoBaseResponse.getResult())
                || queryRefundFailuresListDtoBaseResponse.getResult().size() != 1) {
            return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "该记录不存在或查询异常");
        }
        QueryRefundFailuresListDto queryRefundFailuresListDto = queryRefundFailuresListDtoBaseResponse.getResult().get(0);

        // 查询订单
        BaseResponse<OrderBeanV1> orderResponse = this.checkOrderAndGetOrderBean(queryRefundFailuresListDto.getOrderCode());
        if (!Objects.equals(orderResponse.getCode(), ResponseResult.SUCCESS.getCode())) {
            return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "订单数据查询失败：" + orderResponse.getMessage());
        }
        OrderBeanV1 orderBean = orderResponse.getResult();
        AfterSalesOrderResp afterSalesOrderResp = orderBean.getAfterSalesOrderResp();
        if (afterSalesOrderResp == null) {
            return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "不存在售后单信息");
        }

        String lockKey = "refund_retry_key:" + queryRefundFailuresListDto.getOrderCode();
        try {
            Long expire = 60l;
            if (!LockUtils.lock(redisCache.getRedisTemplate(), lockKey, expire)) {
                return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "处理中，请稍等。");
            }

            if (Integer.valueOf(1).equals(queryRefundFailuresListDto.getLastFailureType()) || Integer.valueOf(2).equals(queryRefundFailuresListDto.getLastFailureType())) {
                Long refundId = System.currentTimeMillis();

                // TODO: 22-6-23 退款逻辑待合并
                if (orderBean.getAmount() != 0) {
                    if (null != orderBean.getOrderPayItem() && orderBean.getOrderPayItem().size() > 0) {
                        //调用支付退款
                        MultiOrderRefundRequest multiOrderRefundRequest = orderAdapter.getMultiOrderPayRefundRequest(orderBean, refundId);
                        MultiOrderRefundResponse multiOrderRefundResponse = payServiceImpl.paymentApplicationRefund(multiOrderRefundRequest, orderBean.getCompanyId());
                        if (multiOrderRefundResponse == null || multiOrderRefundResponse.getData() == null || !ResponseCodeConstant.RESPONSE_SUCCESS_200.equals(multiOrderRefundResponse.getCode())) {
                            return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "调用支付退款接口失败：" + JSON.toJSONString(multiOrderRefundResponse));
                        }
                        List<MultiOrderRefundResponse.RefundPlatformResponse> refundPlatformResponseList = multiOrderRefundResponse.getData().refundPlatformResponseList;
                        if (null != refundPlatformResponseList && refundPlatformResponseList.size() > 0) {
                            redisCache.save(RedisUtil.getPaymentTransIdSequenceKey(refundPlatformResponseList.get(0).getTransId()), orderBean.getOid(), 1L, TimeUnit.DAYS);
                        }
                    } else {
                        //调用支付退款
                        PayRefundRequestDto orderPayRefundRequest = orderAdapter.getOrderPayRefundRequest(orderBean, refundId, orderBean.getOid());
                        //抖音支付退款必传
                        orderPayRefundRequest.setRefundDesc("退款失败人工重试");
                        com.freemud.application.sdk.api.base.BaseResponse<OrderRefundResponse> response = payServiceImpl.orderRefund(orderPayRefundRequest);
                        if (response == null || response.getData() == null || !ResponseCodeConstant.RESPONSE_SUCCESS_STR.equals(response.getCode())) {
                            return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "调用支付退款接口失败：" + JSON.toJSONString(response));
                        }
                        if (!ResponseConstant.SUCCESS_RESPONSE_CODE.equals(response.getData().getStatusCode())) {
                            return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "支付退款失败：" + JSON.toJSONString(response));
                        }
                    }
                }

                RefundFailuresSuccessfulReq refundFailuresSuccessfulReq = new RefundFailuresSuccessfulReq();
                refundFailuresSuccessfulReq.setId(orderRefundRetryVo.getId());
                refundFailuresSuccessfulReq.setOrderCode(orderBean.getOid());
                refundFailuresSuccessfulReq.setPartnerId(orderBean.getCompanyId());
                BaseResponse baseResponse = orderServiceClient.refundFailuresSuccessful(refundFailuresSuccessfulReq);
                if (!ResponseConstant.SUCCESS_RESPONSE_CODE_STR.equals(baseResponse.getCode())) {
                    return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "处理完成但更新记录失败");
                }

                AfterSalesOperateReq request = new AfterSalesOperateReq();
                request.setOrderCode(orderBean.getOid());
                request.setPartnerId(orderBean.getCompanyId());
                request.setOrderClient(Integer.parseInt(orderBean.getOrderClient()));
                request.setAfterSalesCode(afterSalesOrderResp.getAfterSalesCode());
                request.setAfterSerialNo(String.valueOf(refundId));
                request.setAdultRemark("重试退款");
                request.setOperator("技术支持");
                request.setOperationClient(OperationClientEnum.STATE_6.getIndex());
                request.setRefundState(AfterSalesRefunStateEnum.STATE_4.getIndex());
                OrderBaseResp orderBaseResp = orderSdkService.adultApproveWithRefundComplete(request, LogThreadLocal.getTrackingNo());

                if (orderBaseResp == null || !Objects.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, orderBaseResp.getCode())) {
                    return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "基础服务订单退款完成失败");
                }

                stockHandle.revert(null, orderBean);

            } else {
                return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "暂不支持该操作");
            }

        } catch (Exception e) {
            throw e;
        } finally {
            LockUtils.unlock(redisCache.getRedisTemplate(), lockKey);
        }

        return ResponseUtil.success();
    }

    @Override
    public BaseResponse developRefund(OrderDevelopRefundVo orderRefundVo) {

        if (CollectionUtils.isEmpty(orderRefundVo.getOrderCodes())) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "未传递订单号");
        }
        Map<String, String> resultMap = new LinkedHashMap<>();
        orderRefundVo.getOrderCodes().forEach(orderCode -> {
            try {
                BaseResponse resp = this.batchDevelopRefund(orderRefundVo, orderCode);
                if (Objects.equals(resp.getCode(), ResponseResult.SUCCESS.getCode())) {
                    resultMap.put(orderCode, "成功");
                } else {
                    resultMap.put(orderCode, resp.getMessage());
                }
            } catch (Exception e) {
                resultMap.put(orderCode, e.getMessage());
            }
        });
        return ResponseUtil.success(resultMap);
    }

    private BaseResponse batchDevelopRefund(OrderDevelopRefundVo orderRefundVo, String orderCode) {
        if (StringUtils.isEmpty(orderRefundVo.getReason())) {
            orderRefundVo.setReason("内部操作退款,操作人:" + orderRefundVo.getOperator());
        }
        // 查询订单
        BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
        baseQueryOrderRequest.setOrderId(orderCode);
        baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        QueryOrderByIdResponse queryOrderByIdResponse = orderCenterSdkService.queryOrderById(baseQueryOrderRequest);
        String string = JSONObject.toJSONString(queryOrderByIdResponse);
        JSONObject jsonObject = JSONObject.parseObject(string);
        QueryOrderByIdResponseDto orderByIdResponseDto = jsonObject.toJavaObject(QueryOrderByIdResponseDto.class);
        if (!RESPONSE_SUCCESS_CODE.equals(orderByIdResponseDto.getErrcode()) || orderByIdResponseDto.getData() == null) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "订单信息不存在");
        }
        OrderBeanV1 orderBean = orderByIdResponseDto.getData();
        if (PayStatus.NOT_PAY.getCode().equals(orderByIdResponseDto.getData().getPayStatus())
                || NewOrderStatus.PENDING_PAYMENT.getIndex().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "订单未支付，无法退款");
        }
        if (NewOrderStatus.CLOSED.getIndex().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "订单已取消，无法退款");
        }
        // fisherman 仅仅支持 餐饮类订单进行操作
        List<Integer> bizTypes = Arrays.asList(1,7);
        if (!bizTypes.contains(orderBean.getBizType())) {
            return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "仅支持餐饮订单操作");
        }

        // fisherman 该接口的调用 肯定是因已经商户确认要退款的操作, 所以不走正常的 是否可退款判断
        if (PayStatus.HAVE_PAID.getCode().equals(orderBean.getPayStatus())) {
            boolean isRefundDeliveryFee = true;
            //商城查询配送费
            if (Objects.equals(BizTypeEnum.MALL.getBizType(), orderBean.getBizType())
                    && StringUtils.isNotEmpty(orderBean.getExtInfo())) {
                JSONObject extInfoJsonObject = JSONObject.parseObject(orderBean.getExtInfo());
                OrderExtInfoDto orderExtInfoDto = extInfoJsonObject.toJavaObject(OrderExtInfoDto.class);
                if (null != orderExtInfoDto && null != orderExtInfoDto.getProvince()) {
                    String province = orderExtInfoDto.getProvince();
                    QueryFreightRefundSupportedVo queryFreightRefundSupportedVo = new QueryFreightRefundSupportedVo();
                    queryFreightRefundSupportedVo.setPartnerId(orderBean.getCompanyId());
                    queryFreightRefundSupportedVo.setProvince(province);
                    //整合商城订单状态，订单状态 1 2 3不需校验直接退运费 20210513
                    List<Integer> isRefundDeliveryFeeCodes = Arrays.asList(
                            NewOrderStatus.PENDING_PAYMENT.getIndex(), NewOrderStatus.PLACE_AN_ORDER.getIndex(), NewOrderStatus.ACCEPTED.getIndex());
                    if (isRefundDeliveryFeeCodes.contains(orderBean.getStatusV2())) {
                        isRefundDeliveryFee = true;
                    } else {
                        QueryFreightRefundSupportedResponse queryFreightRefundSupportedResponse = deliveryFeiginClient.isFreightRefundSupported(queryFreightRefundSupportedVo);
                        if (null != queryFreightRefundSupportedResponse && RESPONSE_SUCCESS_CODE == queryFreightRefundSupportedResponse.getCode()) {
                            Boolean freightRefundSupported = queryFreightRefundSupportedResponse.getData();
                            isRefundDeliveryFee = freightRefundSupported;
                        }
                    }
                }
            } else {
                // 查询小程序是否配置了退运费
                String configStr = redisCache.hashGet(MessageFormat.format(OrderRedisKeyConstant.ORDER_REFUND_CONFIG, orderBean.getCompanyId(), orderBean.getAppId()), OrderRedisKeyConstant.HashKeyForOrderRefundConfig.TAKE_OUT);
                if (StringUtils.isNotEmpty(configStr)) {
                    OrderRefundConfigEntity config = JSON.parseObject(configStr, OrderRefundConfigEntity.class);
                    String refundDeliveryFeeConfig = config.getRefundShippingFee();
                    // 0、null表示 关闭 ; 1 表示开启
                    if (null != refundDeliveryFeeConfig
                            && Arrays.asList(NewOrderStatus.DELIVERING.getIndex(), NewOrderStatus.COMPLETE.getIndex()).contains(orderBean.getStatusV2())
                            && !ALLOW_REFUND.equals(refundDeliveryFeeConfig)) {
                        isRefundDeliveryFee = false;
                    }
                }
            }

            // 未接单
            if (NewOrderStatus.PLACE_AN_ORDER.getIndex().equals(orderBean.getStatusV2())) {
                // 未接单的 请用户直接操作C端小程序处理
                return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "订单未接单,请指引用户C端操作退款！");
            } else {
                boolean isCreateAfter = true;
                // 查询是否有未处理的售后单,如果有 直接调用请求,
                if (CollectionUtils.isNotEmpty(orderBean.getRefundList())) {
                    List<RefundBeanV1> refundList = orderBean.getRefundList();
                    Collections.sort(refundList, (o1, o2) -> {
                        Long aLong = Long.valueOf(o1.getCreateTime());
                        Long bLong = Long.valueOf(o2.getCreateTime());
                        if (bLong > aLong) {
                            return 1;
                        } else if (bLong < aLong) {
                            return -1;
                        } else {
                            return 0;
                        }
                    });
                    RefundBeanV1 refundBeanV11 = refundList.get(0);
                    isCreateAfter = refundBeanV11.getStatus().compareTo(RefundStatusV1.APPLY_REFUND.getCodeV1()) != 0;
                }

                if (isCreateAfter) {
                    CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
                    cancelOrderRequest.setPartnerId(orderBean.getCompanyId());
                    cancelOrderRequest.setStoreId(orderBean.getShopId());
                    cancelOrderRequest.setOrderId(orderBean.getOid());
                    cancelOrderRequest.setOrderClient(Integer.parseInt(orderBean.getOrderClient()));

                    //传入的售后单类型为：2：售中用户取消 8：售后申请
                    cancelOrderRequest.setAfterSalesType(AfterSalesType.USER_CANCEL);
                    if (NewOrderStatus.COMPLETE.getIndex().equals(orderBean.getStatusV2())) {
                        cancelOrderRequest.setAfterSalesType(AfterSalesType.USER_SALE_RETURN);
                    }
                    cancelOrderRequest.setReason(orderRefundVo.getReason());
                    cancelOrderRequest.setReqRemark(orderRefundVo.getReason());
                    // 商城订单 增加拓展信息
                    CancelOrderRequest.AfterSalesOrderExtInfoReq salesOrderExtInfoReq = new CancelOrderRequest.AfterSalesOrderExtInfoReq();
                    salesOrderExtInfoReq.setRefundMode(orderRefundVo.getRefundMode());
                    cancelOrderRequest.setExtInfoReq(salesOrderExtInfoReq);

                    cancelOrderRequest.setOperator(orderRefundVo.getOperator());
                    cancelOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
                    cancelOrderRequest.setRefundDeliveryAmount(isRefundDeliveryFee);
                    BaseOrderResponse baseResponseDto = orderCenterSdkService.orderCancel(cancelOrderRequest);

                    if (!RESPONSE_SUCCESS_CODE.equals(baseResponseDto.getErrcode())) {
                        return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), baseResponseDto.getErrmsg());
                    }
                    if (orderBean.getAmount() > 0) {
                        sendPosMessage(orderBean.getCompanyId(), orderBean.getShopId());
                    }
                    // 兼容下面的方法
                    OrderRefundVo refundVo = new OrderRefundVo();
                    refundVo.setReason(orderRefundVo.getReason());
                    refundVo.setRemarks(orderRefundVo.getReason());
                    //通知小助手发送申请退款公众号订阅消息
                    sendApplyRefundSubscriptionNotice(orderBean, refundVo);
                    //已接单可发起退款申请，查询门店有无云打印机，有则打印退款申请小票
                    printApplyRefundSmallTicket(orderBean, refundVo);
                }


            }
            // 调用oms的 同意退款操作
            OrderManagerRequest request = new OrderManagerRequest();
            request.setPartnerId(orderBean.getCompanyId());
            request.setStoreId(orderBean.getShopId());
            request.setOrderId(orderBean.getOid());
            request.setReason(orderRefundVo.getReason());
            request.setOperateType(cn.freemud.management.enums.OperateType.ORDER_DEVELOPER_AGREE_REFUND.getOpType());
            request.setOperator(orderRefundVo.getOperator());
            BaseResponse baseResponse = orderManagerAdapter.developRefund(request);
            return baseResponse;
        }
        return ResponseUtil.error(ResponseResult.ORDER__ERRORREFUND.getCode(), "订单未支付！");
    }

    /**
     * 订单退款操作
     * 1.调用支付 进行退款
     * 2.调用基础服务, 进行订单状态变更
     *
     * @param orderBean
     * @return
     */
    private void doCouponOrderRefund(OrderBeanV1 orderBean, OrderRefundVo orderRefundVo) {
        // 支付金额 大于0 调用支付 进行退款
        Long refundId = System.currentTimeMillis();
        Integer state = PayRefundStatus.SUCCESS.getCode();

        // fisherman  ----> 支付校验 begin
        BigDecimal refundAmount = orderVerifyHandle.getRefundAmount(orderBean, false);
        orderBean.setAmount(refundAmount.longValue());
        // fisherman 模拟退款失败
        if (Objects.nonNull(testOrderRefundFail)) {
            orderBean.setAmount(refundAmount.longValue() + testOrderRefundFail);
        }
        //支付退款
        PayRefundResponse refundResponse;
        try {
            if (null != orderBean.getOrderPayItem() && orderBean.getOrderPayItem().size() > 0) {
                refundResponse = payServiceImpl.payRefundCommon(null,orderBean);
            } else {
                // TODO: 22-6-23 待考虑合并到上面一起
                refundResponse = paymentHandle.refund("用户买券订单-申请退款", orderBean);
            }
            if (refundResponse.getPayRefundStatus().getCode().compareTo(PayRefundStatus.SUCCESS.getCode()) != 0) {
                int failureType = 0;
                if (refundResponse.getPayRefundStatus().getCode().compareTo(PayRefundStatus.NOT_SUFFICIENT_FUNDS.getCode()) == 0) {
                    failureType = RefundFailureRequestDTO.FAILURETYPE_NOT_SUFFICIENT_FUNDS;
                }
                RefundFailureRequestDTO requestDTO = RefundFailureRequestDTO.builder().orderCode(orderBean.getOid())
                        .failureType(failureType)
                        .reason("退款失败")
                        .partnerId(orderBean.getCompanyId())
                        .operator("")
                        .ver(0).build();
                orderServiceClient.refundFailures(requestDTO);
            }
            state = refundResponse.getPayRefundStatus().getCode();
        } catch (OrderServiceException orderEx) {
            // 系统异常
            RefundFailureRequestDTO requestDTO = RefundFailureRequestDTO.builder().orderCode(orderBean.getOid())
                    .failureType(RefundFailureRequestDTO.FAILURETYPE_SYSTEM_ERROR)
                    .reason(orderEx.getMessage())
                    .partnerId(orderBean.getCompanyId())
                    .operator("")
                    .ver(0).build();
            orderServiceClient.refundFailures(requestDTO);
            state = null;
        }

        // fisherman  ----> 支付校验 end
        // 调用基础服务, 进行订单状态变更
        CancelOrderRequest cancelOrderRequest = orderAdapter.convent2CancelOrderRequest(orderBean.getOid(),
                orderBean.getCompanyId(), AfterSalesType.USER_CANCEL, orderRefundVo.getReason(), LogThreadLocal.getTrackingNo(), refundId.toString());
        cancelOrderRequest.setOperator(orderBean.getUserName());
        cancelOrderRequest.setPartnerId(orderBean.getCompanyId());
        Integer refundStates = AfterSalesRefunStateEnum.STATE_1.getIndex();
        if (Objects.equals(PayRefundStatus.RUNNING.getCode(), state)) {
            // 退款中
            cancelOrderRequest.setCreateEvent(AfterSalesOrderCreateEventEnum.RETURN_COMPLETE.getCreateEvent());
            refundStates = AfterSalesRefunStateEnum.STATE_2.getIndex();
        } else if (Objects.equals(PayRefundStatus.SUCCESS.getCode(), state)) {
            //退款成功
            refundStates = AfterSalesRefunStateEnum.STATE_4.getIndex();
            cancelOrderRequest.setCreateEvent(AfterSalesOrderCreateEventEnum.REFUND_COMPLETE.getCreateEvent());
        } else {
            // 退款失败,直接给基础服务null 用于后续补偿操作
            cancelOrderRequest.setCreateEvent(null);
        }
        cancelOrderRequest.setRefundState(refundStates);
        cancelOrderRequest.setReqRemark(orderRefundVo.getRemarks());
        cancelOrderRequest.setRefundDeliveryAmount(false);
        // 商城订单 增加拓展信息
        CancelOrderRequest.AfterSalesOrderExtInfoReq salesOrderExtInfoReq = new CancelOrderRequest.AfterSalesOrderExtInfoReq();
        salesOrderExtInfoReq.setRefundMode(orderRefundVo.getRefundMode());
        cancelOrderRequest.setExtInfoReq(salesOrderExtInfoReq);
        BaseOrderResponse baseOrderResponse = orderCenterSdkService.orderCancel(cancelOrderRequest);
        if (baseOrderResponse == null || !ObjectUtils.equals(ResponseConstant.SUCCESS_RESPONSE_CODE, baseOrderResponse.getErrcode())) {
            throw new ServiceException(ResponseResult.ORDER__ERRORREFUND);
        }
        if (Objects.nonNull(state)) {
            //冲正库存
            stockHandle.revert(null, orderBean);
        }
        // 删除订单 通知活动添加商品库存  status 需要老订单的 ordercode
//        orderQueueService.backOrdersStatusChange(orderBean.getOrderCode(), orderBean.getOrderState(), orderBean.getPayState());
    }

    /**
     * 校验订单是否可退款等
     *
     * @param userLoginInfoDto
     * @param orderBean
     * @return
     */
    private BaseResponse couponOrderRefundCheck(AssortmentCustomerInfoVo userLoginInfoDto, OrderBeanV1 orderBean) {
        // 校验是否是用户订单
        if (!Objects.equals(userLoginInfoDto.getMemberId(), orderBean.getUserId())) {
            return ResponseUtil.error(ResponseResult.ORDER_QUERYORDER_ERROR.getCode(), "不能操作非本人的订单");
        }
        // 是否是卖券订单
        if (orderBean.getBizType().compareTo(BizTypeEnum.SALE_COUPON.getBizType()) != 0) {
            return ResponseUtil.error(ResponseResult.COUPON_ORDER_COMMON_VERIFY_FAIL);
        }
        // 校验订单状态 卖券订单只有在6已完成状态下 才能退款
        if (orderBean.getStatus().compareTo(OrderStatusV1.COMPLETE.getCode()) != 0) {
            return ResponseUtil.error(ResponseResult.COUPON_ORDER_COMMON_VERIFY_FAIL.getCode(), "只可操作完成的订单");
        }
        // 校验一遍是否有售后单
        if (CollectionUtils.isNotEmpty(orderBean.getRefundList())) {
            return ResponseUtil.error(ResponseResult.COUPON_ORDER_COMMON_VERIFY_FAIL.getCode(), "已存在退款申请,请耐心等待处理");
        }
        // fisherman 查询配置是否能退款 未完成
        boolean isTrue = orderAdapter.checkRefundButtionBizTypeIs6(orderBean.getCompanyId(), orderBean.getBizType(),
                orderBean.getStatus(), userLoginInfoDto.getWxAppId(), new Date(orderBean.getGmtCreate()), orderBean.getOrderType());
        if (isTrue) {
            return ResponseUtil.success();
        }
        return ResponseUtil.error(ResponseResult.COUPON_ORDER_COMMON_VERIFY_FAIL.getCode(), "虚拟券退款配置未启用,请联系客服");
    }


    /**
     * 调用基础服务 获取订单信息
     *
     * @param oid
     * @return
     */
    private BaseResponse<OrderBeanV1> checkOrderAndGetOrderBean(String oid) {
        if (StringUtils.isBlank(oid)) {
            return ResponseUtil.error(ResponseResult.ORDER_CODE_EMPTY);
        }
        BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
        baseQueryOrderRequest.setOrderId(oid);
        baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
        QueryOrderByIdResponse queryOrderByIdResponse = orderCenterSdkService.queryOrderById(baseQueryOrderRequest);

        if (queryOrderByIdResponse == null || queryOrderByIdResponse.getData() == null) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        OrderBeanV1 data = queryOrderByIdResponse.getData();
        return ResponseUtil.success(data);
    }


    /**
     * 查询用户 是否登录
     *
     * @param sessionId
     * @return
     */
    private BaseResponse<AssortmentCustomerInfoVo> checkUserLoginInfoDto(String sessionId) {
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(sessionId);
        if (userLoginInfoDto == null || StringUtils.isEmpty(userLoginInfoDto.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        return ResponseUtil.success(userLoginInfoDto);
    }

    /**
     * 发送支付成功模板消息
     */
    public void sendMessageByNewApp(SendPaySuccessMessageVo sendPaySuccessMessageVo) {
        OrderBeanV1 orderBean = new OrderBeanV1();
        orderBean.setCompanyId(sendPaySuccessMessageVo.getPartnerId());
        orderBean.setAddress(sendPaySuccessMessageVo.getAddress());
        orderBean.setDaySeq(sendPaySuccessMessageVo.getDaySeq());
        orderBean.setGmtExpect(sendPaySuccessMessageVo.getGmtExpect());
        orderBean.setShopName(sendPaySuccessMessageVo.getStoreName());
        orderBean.setGmtCreate(sendPaySuccessMessageVo.getGmtCreate());
        orderBean.setOid(sendPaySuccessMessageVo.getOrderCode());
        orderBean.setOrderType(sendPaySuccessMessageVo.getOrderType());
        orderBean.setOtherCode(sendPaySuccessMessageVo.getOtherCode());
        orderBean.setAmount(sendPaySuccessMessageVo.getAmount());
        OrderExtInfoDto extInfoDto = JSON.parseObject(sendPaySuccessMessageVo.getExtInfo(), OrderExtInfoDto.class);
        extInfoDto.setAppid(extInfoDto.getAppid());
        extInfoDto.setOpenid(extInfoDto.getOpenid());
        extInfoDto.setPrepayId(extInfoDto.getPrepayId());
        orderBean.setExtInfo(JSON.toJSONString(extInfoDto));
        this.sendPaySuccessMessage(orderBean);
    }

}
