package cn.freemud.management.service.handle;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.management.entities.dto.request.order.OrderManagerRequest;
import cn.freemud.management.entities.dto.response.order.OrderManagerResponse;
import cn.freemud.management.enums.*;
import cn.freemud.management.enums.OperateType;
import cn.freemud.management.util.ResponseUtil;
import cn.freemud.redis.RedisCache;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freemud.api.assortment.datamanager.manager.cache.CacheOpenPlatformPartnerWxappConfigManager;
import com.freemud.application.sdk.api.ordercenter.entities.v1.AccountBeanV1;
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.OrderSourceV1;
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.RefundStatusV1;
import com.freemud.sdk.api.assortment.message.enums.OrderType;
import com.freemud.sdk.api.assortment.order.adapter.OrderSdkAdapter;
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.OldOrderAccountType;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

//import cn.freemud.base.log.LogTreadLocal;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: OrderVerifyService
 * @Package cn.freemud.management.service.impl
 * @Description:
 * @author: shuhu.hou
 * @date: 2020/3/26 16:04
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Component
public class OrderVerifyHandle {

    /**
     * 允许退款
     */
    private static final String ALLOW_REFUND = "1";
    /**
     * svc储值卡支付，可用于判断订单是否用储值卡支付
     */
    private static final String PAY_CODE_10102 = "10102";

    @Autowired
    private CacheOpenPlatformPartnerWxappConfigManager cacheOpenPlatformPartnerWxappConfigManager;

    @Autowired
    private OrderSdkAdapter orderSdkAdapter;
    @Autowired
    private OrderCenterSdkService orderCenterSdkService;
    @Autowired
    private DeliveryHandle deliveryHandle;
    @Autowired
    private RedisCache redisCache;

    @Value("${delivery.support.ordersource}")
    private String supportOrderSource;
    @Value("${mccafe.partner.id}")
    private String macCafePartnerId;

    private static final String THIRD = "third";
    private static final String delivery_type_self = "self";
    /**
     * 接单校验
     *
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse orderConfirmTakeVerify(OrderBeanV1 orderBean, OrderManagerRequest request) {
        if (orderBean == null) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        if (!OrderStatusV1.TAKE_ORDER.getV2Code().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER_CANNOT_CONFIRM, getOrderManagerResponse(orderBean));
        }
        return ResponseUtil.success();
    }

    /**
     * 订单配送校验
     *
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse orderDeliveryVerify(OrderBeanV1 orderBean, OrderManagerRequest request) {
        if (orderBean == null) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        //已完成的订单不能配送
        if (OrderStatusV1.COMPLETE.getV2Code().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER_IS_COMPLETE_CAN_NOT_DELIVERY, getOrderManagerResponse(orderBean));
        }
        //订单已经发送过配送
        if (OrderStatusV1.DISTRIBUTION.getV2Code().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.DELIVERY_SEND_REPETITION, getOrderManagerResponse(orderBean));
        }
        //判断订单状态是否为已经申请退款订单
        if (checkRefund(orderBean)
                && orderBean.getHasRefund() != null
                && orderBean.getHasRefund()
                && (orderBean.getRefundList().get(orderBean.getRefundList().size() - 1).getStatus() == 1
                || orderBean.getRefundList().get(orderBean.getRefundList().size() - 1).getStatus() == 4)) {
            return ResponseUtil.error(ResponseResult.DELIVERY_SEND_APPLY_REFUND, getOrderManagerResponse(orderBean));
        }
        //外卖订单不是接单不能送出
        if (!OrderStatusV1.RECEIPT.getV2Code().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.DELIVERY_SEND_STATUS_NOTAKE, getOrderManagerResponse(orderBean));
        }
        //三方配送正在进行，不允许操作送出  除非是骑手已经取餐
        if (!macCafePartnerId.equals(orderBean.getCompanyId()) && this.checkSaasWm(orderBean) && this.verifyThirdFlow(orderBean,request)) {
            return ResponseUtil.error(ResponseResult.ORDER_MOVE_FAILED);
        }
        return ResponseUtil.success();
    }


    /**
     * 订单制作完成校验
     *
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse orderDoneVerify(OrderBeanV1 orderBean, OrderManagerRequest request) {
        if (orderBean == null) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        //已制作完成的订单不能重复操作
        if (OrderStatusV1.COMPLETE_MAKE.getV2Code().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.DONE_FAIL_REPETITION, getOrderManagerResponse(orderBean));
        }
        //订单非接单状态，不能制作完成
        if (!OrderStatusV1.RECEIPT.getV2Code().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.DONE_FAIL_NOT_ACCEPT, getOrderManagerResponse(orderBean));
        }
        //判断订单状态是否为已经申请退款订单
        if (orderBean.getHasRefund() != null
                && orderBean.getHasRefund()
                && (orderBean.getRefundList().get(orderBean.getRefundList().size() - 1).getStatus() == 1
                || orderBean.getRefundList().get(orderBean.getRefundList().size() - 1).getStatus() == 4)) {
            return ResponseUtil.error(ResponseResult.DONE_FAIL_APPLY_REFUND, getOrderManagerResponse(orderBean));
        }
        if (this.checkSaasWm(orderBean) && this.verifyThirdFlow(orderBean,request)) {
            return ResponseUtil.error(ResponseResult.ORDER_MOVE_FAILED);
        }
        return ResponseUtil.success();
    }

    /**
     * 订单完成校验
     *
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse orderAffirmVerify(OrderBeanV1 orderBean, OrderManagerRequest request) {
        if (orderBean == null) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        //判断订单是否已送达
        if (OrderStatusV1.COMPLETE.getV2Code().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.DELIVERY_SEND_REPETITION, getOrderManagerResponse(orderBean));
        }
        //已取消的订单不能操作
        if (OrderStatusV1.CANCEL.getV2Code().equals(orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER_HAS_CANCELED, getOrderManagerResponse(orderBean));
        }
        //判断订单状态是否为已经申请退款订单
        if (checkRefund(orderBean)&&orderBean.getHasRefund() != null
                && orderBean.getHasRefund()
                && (orderBean.getRefundList().get(orderBean.getRefundList().size() - 1).getStatus() == 1
                || orderBean.getRefundList().get(orderBean.getRefundList().size() - 1).getStatus() == 4)) {
            return ResponseUtil.error(ResponseResult.AFFIRM_FAIL_APPLY_REFUND, getOrderManagerResponse(orderBean));
        }
        //校验订单是否为配送状态
        if (isWaimai(orderBean) && ObjectUtils.notEqual(OrderStatusV1.DISTRIBUTION.getV2Code(), orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER_DELIVERY_FAILED, getOrderManagerResponse(orderBean));
        }
        //三方配送正在进行，不允许操作送出  除非是骑手已经取餐
        if (!macCafePartnerId.equals(orderBean.getCompanyId()) && this.checkSaasWm(orderBean) && this.verifyThirdFlow(orderBean,request)) {
            return ResponseUtil.error(ResponseResult.ORDER_MOVE_FAILED);
        }
        return ResponseUtil.success();
    }

    private static boolean checkRefund(OrderBeanV1 orderBean) {
        List<String> uncheckRefund = Arrays.asList(
                OrderSourceV1.ELEME.getCode(),
                OrderSourceV1.EBAI.getCode(),
                OrderSourceV1.MTWM.getCode(),
                OrderSourceV1.BDWM.getCode(),
                OrderSourceV1.JUBAOPEN.getCode(),
                OrderSourceV1.DIANPING.getCode(),
                OrderSourceV1.KOUBEI.getCode()
        );
        // 非三方渠道, 且是外卖类型三方配送的订单，不再进行售后单的判断,否则配送无法进行流转
        return !Objects.equals(OrderTypeV1.TAKE_OUT.getCode(), orderBean.getOrderType())
                || !(!uncheckRefund.contains(orderBean.getSource())
                && Objects.nonNull(orderBean.getAddInfo())
                && THIRD.equalsIgnoreCase(orderBean.getAddInfo().getDeliveryType()));
    }

    /**
     * 拒单
     *
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse orderRejectVerify(OrderBeanV1 orderBean, OrderManagerRequest request) {
        if (orderBean == null) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        Integer statusV2 = orderBean.getStatusV2();

        //判断订单是否已经被拒单
        if (NewOrderStatus.CLOSED.getIndex().equals(statusV2)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_REPETITION, getOrderManagerResponse(orderBean));
        }
        //判断订单是否已经取消
//        if (OrderStatus.CANCEL.getCode().equals(status)) {
//            return ResponseUtil.error(ResponseResult.ORDER_HAS_CANCELED, getOrderManagerResponse(orderBean));
//        }
        //判断订单是否在配送中
        if (NewOrderStatus.DELIVERING.getIndex().equals(statusV2)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_ORDER_IS_DELIVERY, getOrderManagerResponse(orderBean));
        }
        //判断订单是否已送达
        if (NewOrderStatus.COMPLETE.getIndex().equals(statusV2)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_ORDER_IS_COMPLETE, getOrderManagerResponse(orderBean));
        }
        if (!NewOrderStatus.PLACE_AN_ORDER.getIndex().equals(statusV2)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_ORDER_IS_NOT_NEW, getOrderManagerResponse(orderBean));
        }
        return ResponseUtil.success();
    }

    /**
     * 拒单
     *
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse mallOrderRejectVerify(OrderBeanV1 orderBean, OrderManagerRequest request) {
        if (orderBean == null) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        Integer statusV2 = orderBean.getStatusV2();
        //判断订单是否已经被拒单
        if (NewOrderStatus.CLOSED.getIndex().equals(statusV2)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_REPETITION, getOrderManagerResponse(orderBean));
        }
        //判断订单是否已经取消
//        if (OrderStatus.CANCEL.getCode().equals(status)) {
//            return ResponseUtil.error(ResponseResult.ORDER_HAS_CANCELED, getOrderManagerResponse(orderBean));
//        }
        //判断订单是否在配送中
        if (NewOrderStatus.DELIVERING.getIndex().equals(statusV2)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_ORDER_IS_DELIVERY, getOrderManagerResponse(orderBean));
        }
        //判断订单是否已送达
        if (NewOrderStatus.COMPLETE.getIndex().equals(statusV2)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_ORDER_IS_COMPLETE, getOrderManagerResponse(orderBean));
        }
        return ResponseUtil.success();
    }
    /**
     * 拒单
     *
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse mcCafeOrderRejectVerify(OrderBeanV1 orderBean, OrderManagerRequest request) {
        if (orderBean == null) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }

        Integer statusV2 = orderBean.getStatusV2();

        //判断订单是否已经被拒单
        if (NewOrderStatus.CLOSED.getIndex().equals(statusV2)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_REPETITION, getOrderManagerResponse(orderBean));
        }
        //判断订单是否已经取消
//        if (OrderStatus.CANCEL.getCode().equals(status)) {
//            return ResponseUtil.error(ResponseResult.ORDER_HAS_CANCELED, getOrderManagerResponse(orderBean));
//        }
        //判断订单是否在配送中
        if (NewOrderStatus.DELIVERING.getIndex().equals(statusV2)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_ORDER_IS_DELIVERY, getOrderManagerResponse(orderBean));
        }
        //判断订单是否已送达
        if (NewOrderStatus.COMPLETE.getIndex().equals(statusV2)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_ORDER_IS_COMPLETE, getOrderManagerResponse(orderBean));
        }
        if (!NewOrderStatus.PLACE_AN_ORDER.getIndex().equals(statusV2) && !OrderTypeV1.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_ORDER_IS_NOT_NEW, getOrderManagerResponse(orderBean));
        }
        return ResponseUtil.success();
    }

    /**
     * 同意退款
     *
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse orderAgreeRefund(OrderBeanV1 orderBean, OrderManagerRequest request) {
        //已取消的订单不能操作
        if (ObjectUtils.equals(OrderStatusV1.CANCEL.getV2Code(), orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER_HAS_CANCELED);
        }
        //判断订单是否有申请退款
        if (orderBean.getAfterSalesOrderResp() == null) {
            return ResponseUtil.error(ResponseResult.ORDER_REFUND_NOT_APPLY);
        }

        //审核中或已退货状态可同意退款
        List<Integer> canAgreeRefundStatus = Arrays.asList(1,4);
        if (!canAgreeRefundStatus.contains(orderBean.getAfterSalesOrderResp().getAfterSalesStatus())) {
            return ResponseUtil.error(ResponseResult.ORDER_REFUND_NOT_APPLY);
        }
        if("pos".equals(request.getOperator())){
            request.setOperationClient(1);
        }else if("小助手".equals(request.getOperator())){
            request.setOperationClient(2);
        }else if("开发平台".equals(request.getOperator())){
            request.setOperationClient(3);
        }else if("自动任务".equals(request.getOperator())){
            request.setOperationClient(4);
        }
        //门店发起退款，需要品牌审核，则小助手不能发同意退款
        if(Objects.equals(AfterSalesType.STORE_CANCEL.getIndex(),orderBean.getAfterSalesOrderResp().getAfterSalesType())){
            //售后渠道 1:POS插件 2:小助手 3:开放平台 4:自动任务 5:用户端 6:系统 7:万象 8:太一
            if(Objects.equals(request.getOperationClient() , 2) && request.getBrandVerifyAfterSales()){
                return ResponseUtil.error(ResponseResult.CAN_NOT_REFUND);
            }
            return ResponseUtil.success();
        }
        //订单是否支持退款
        boolean isCanRefund = false;
        //订单
        boolean isRefundDeliveryFee=false;
        //saas渠道订单，已完成的订单不能操作, 商户配置已完成订单可退款可退款
//        if (ObjectUtils.equals(orderBean.getSource(), OrderSourceV1.SAAS.getCode())) {
//            isCanRefund = getRefundConfig(orderBean);
//            if (!isCanRefund) {
//                return ResponseUtil.error(ResponseResult.ORDER_HAD_AFFIRM_CAN_NOT_REFUND);
//            }
//        }
//        if (isCanRefund) {
            orderBean.setAmount(getRefundAmount(orderBean,isRefundDeliveryFee).longValue());
//        }
        return ResponseUtil.success();
    }

    /**
     * 商城同意退款
     *
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse mallOrderAgreeRefund(OrderBeanV1 orderBean, OrderManagerRequest request) {
        //已取消的订单不能操作
        if (ObjectUtils.equals(OrderStatusV1.CANCEL.getV2Code(), orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER_HAS_CANCELED);
        }
        //判断订单是否有申请退款
        if (orderBean.getHasRefund() == null || !orderBean.getHasRefund()) {
            return ResponseUtil.error(ResponseResult.ORDER_REFUND_NOT_APPLY);
        }
        //订单是否支持退款
        boolean isCanRefund = false;
        //订单
        boolean isRefundDeliveryFee=false;
        //saas渠道订单，已完成的订单不能操作, 商户配置已完成订单可退款可退款
        if (ObjectUtils.equals(orderBean.getBizType(), BizTypeEnum.MALL.getBizType())) {
            isCanRefund = getRefundConfig(orderBean);
            if (!isCanRefund) {
                return ResponseUtil.error(ResponseResult.ORDER_HAD_AFFIRM_CAN_NOT_REFUND);
            }
        }
        if (isCanRefund) {
            orderBean.setAmount(getRefundAmount(orderBean,isRefundDeliveryFee).longValue());
        }
        return ResponseUtil.success();
    }

    /**
     * 麦咖啡同意退款
     *
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse orderAgreeRefundMCCafe(OrderBeanV1 orderBean, OrderManagerRequest request) {
        //已取消的订单不能操作
        if (ObjectUtils.equals(OrderStatusV1.CANCEL.getV2Code(), orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER_HAS_CANCELED);
        }
        for (RefundBeanV1 refundBean : orderBean.getRefundList()) {
            if(RefundStatusV1.APPLY_REFUND.getCodeV1().equals(refundBean.getStatus())) {
                return ResponseUtil.success();
            }
            if(RefundStatusV1.COMPLETE_REFUND.getCodeV1().equals(refundBean.getStatus())) {
                return ResponseUtil.error(ResponseResult.AGREE_REFUND_ORDER_FAIL.getCode(), "订单已经退款完成，不能重复申请");
            }
        }
        return ResponseUtil.success();
    }

    /**
     * 拒绝退款
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse orderRejectRefund(OrderBeanV1 orderBean, OrderManagerRequest request) {
        //判断当前订单是否发起退款
        if (orderBean.getHasRefund() == null || !orderBean.getHasRefund() || orderBean.getAfterSalesOrderResp() == null) {
            return ResponseUtil.error(ResponseResult.ORDER_REFUND_NOT_APPLY);
        }
        if (ObjectUtils.equals(AfterSalesStatus.COMPLETE.getIndex(), orderBean.getAfterSalesOrderResp().getAfterSalesStatus())) {
            return ResponseUtil.error(ResponseResult.ORDER_REJECT_REFUND_REPETITION);
        }
        //订单不是申请退款中，不能操作
        if  (ObjectUtils.notEqual(AfterSalesStatus.PENDING.getIndex(), orderBean.getAfterSalesOrderResp().getAfterSalesStatus())) {
            return ResponseUtil.error(ResponseResult.ORDER_REJECT_REFUND_STATUS_NOT);
        }
        //新订单，已完成，取消订单不能操作
        if (OrderSourceV1.SAAS.getCode().equals(orderBean.getSource())
                && (OrderStatusV1.TAKE_ORDER.getV2Code().equals(orderBean.getStatusV2())
                || OrderStatusV1.CANCEL.getV2Code().equals(orderBean.getStatusV2()))) {
            return ResponseUtil.error(ResponseResult.ORDER_REJECT_REFUND_STATUS_END);
        }
        return ResponseUtil.success();
    }

    /**
     * 取消退款
     * @param orderBean
     * @return
     */
    public BaseResponse orderCancel(OrderBeanV1 orderBean, String opType) {

        List<String> standardPaymentRefundSourceList = Lists.newArrayList(OrderSourceV1.SAAS.getCode(), OrderSourceV1.APP.getCode(), OrderSourceV1.ALIPAY.getCode());
        // 商家同意退款时，校验订单是否能退款（B端后台"订单退款设置"）
        boolean isCanRefund = true;
        if (Objects.equals(OperateType.ORDER_AGREE_REFUND, opType) && standardPaymentRefundSourceList.contains(orderBean.getSource())) {
            isCanRefund = getRefundConfig(orderBean);
            if (!isCanRefund) {
                return ResponseUtil.error(ResponseResult.AGREE_REFUND_APPLY_ORDER_NOT_ALLOW);
            }
        }
        return ResponseUtil.success();
    }

    /**
     * 拒绝退款
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse mallOrderRejectRefund(OrderBeanV1 orderBean, OrderManagerRequest request) {
        //判断当前订单是否发起退款
        if (orderBean.getHasRefund() == null || !orderBean.getHasRefund()) {
            return ResponseUtil.error(ResponseResult.ORDER_REFUND_NOT_APPLY);
        }
        //判断该当前订单是否已经退款
        List<RefundBeanV1> list = orderBean.getRefundList();
        if (ObjectUtils.equals(list.get(list.size() - 1).getStatus(), 5)) {
            return ResponseUtil.error(ResponseResult.ORDER_REJECT_REFUND_REPETITION);
        }
        //新订单，已完成，取消订单不能操作
        if (Objects.equals(BizTypeEnum.MALL.getBizType(),orderBean.getBizType())
                && (OrderStatusV1.TAKE_ORDER.getV2Code().equals(orderBean.getStatusV2())
                || OrderStatusV1.CANCEL.getV2Code().equals(orderBean.getStatusV2()))) {
            return ResponseUtil.error(ResponseResult.ORDER_REJECT_REFUND_STATUS_END);
        }
        return ResponseUtil.success();
    }

    /**
     * 拒绝退款
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse mcCafeOrderRejectRefund(OrderBeanV1 orderBean, OrderManagerRequest request) {
        //判断当前订单是否发起退款
        if (orderBean.getHasRefund() == null || !orderBean.getHasRefund()) {
            return ResponseUtil.error(ResponseResult.ORDER_REFUND_NOT_APPLY);
        }

        if(CollectionUtils.isEmpty(orderBean.getRefundList())) {
            return ResponseUtil.error(ResponseResult.ORDER_REFUND_NOT_APPLY);
        }

        for (RefundBeanV1 refundBean : orderBean.getRefundList()) {
            if (ObjectUtils.equals(refundBean.getStatus(), RefundStatus.COMPLETE_REFUND.getCode())) {
                return ResponseUtil.error(ResponseResult.ORDER_REJECT_REFUND_REPETITION);
            }

            if (OrderStatusV1.CANCEL.getV2Code().equals(orderBean.getStatusV2())) {
                return ResponseUtil.error(ResponseResult.ORDER_REJECT_REFUND_STATUS_END);
            }

            if (ObjectUtils.equals(refundBean.getStatus(), RefundStatus.APPLY_REFUND.getCode())) {
                break;
            }
        }

        return ResponseUtil.success();
    }

    /**
     * 通用校验
     *
     * @param orderBean
     * @param request
     * @return
     */
    private BaseResponse commonVerify(OrderBeanV1 orderBean, OrderManagerRequest request) {
        if (ObjectUtils.notEqual(orderBean.getCompanyId(), request.getPartnerId())) {
            return ResponseUtil.error(ResponseResult.ORDER_PARTNER_ID_NOT_MATCTH, getOrderManagerResponse(orderBean));
        }
        //开放平台不传入门店
        if (ObjectUtils.notEqual(request.getOperator(), OperateClient.OPEN_PLATFORM.getOpName()) && ObjectUtils.notEqual(orderBean.getShopId(), request.getStoreId())) {
            return ResponseUtil.error(ResponseResult.ORDER_STORE_ID_NOT_MATCTH, getOrderManagerResponse(orderBean));
        }
        return ResponseUtil.success();
    }

    /**
     * 是否是外卖
     *
     * @param orderBean
     * @return
     */
    private boolean isWaimai(OrderBeanV1 orderBean) {
        String source = orderBean.getSource();
        if (OrderSourceV1.BDWM.getCode().equals(source) || OrderSourceV1.JDWM.getCode().equals(source)
                || OrderSourceV1.MTWM.getCode().equals(source) || OrderSourceV1.ELEME.getCode().equals(source)) {
            return true;
        }
        return false;
    }

    private OrderManagerResponse getOrderManagerResponse(OrderBeanV1 orderBean) {
        Integer refundStatus = CollectionUtils.isEmpty(orderBean.getRefundList()) ? null : orderBean.getRefundList().get(0).getStatus();
        return new OrderManagerResponse(orderBean.getGmtExpect(), orderBean.getStatus(), refundStatus);
    }

    /**
     * 已完成订单退款配置查询
     *
     * @param data
     * @return true=可同意退款
     */
    private boolean getRefundConfig(OrderBeanV1 data) {
        boolean isFinishRefund = false;
        // [华莱士20210410] 微商城订单判断
        if(Objects.equals(BizTypeEnum.MALL.getBizType(),data.getBizType())){
            // 除 未支付 拒单 和 取消外，其他可退款
            return Stream.of(OrderStatusV1.WAIT_PAY,OrderStatusV1.CANCEL).noneMatch(s -> Objects.equals(data.getStatusV2(),s.getV2Code()));
        }
        com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto extInfo = null;
        JSONObject jsonObject1 = JSONObject.parseObject(data.getExtInfo());
        extInfo = jsonObject1.toJavaObject(com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto.class);

        // 查询小程序配置的退款设置
        String redisKey = MessageFormat.format(OrderRedisKeyConstant.ORDER_REFUND_CONFIG, data.getCompanyId(), extInfo.getAppid());
        String hashKey;
        if(MarketTypeEnum.CASHIER.getIndex().byteValue() == data.getMarketingType()){
            //收银单，使用收银单的退款配置
            hashKey = OrderRedisKeyConstant.HashKeyForOrderRefundConfig.CASHIER;
        } else {
            hashKey = OrderType.TAKE_OUT.getCode().equals(data.getOrderType())
                    ? OrderRedisKeyConstant.HashKeyForOrderRefundConfig.TAKE_OUT
                    : OrderRedisKeyConstant.HashKeyForOrderRefundConfig.EAT_IN;
        }
        String configStr = redisCache.hashGet(redisKey, hashKey);
        if (StringUtils.isEmpty(configStr)) {
            return true;
        }
        OrderRefundConfigEntity config = JSON.parseObject(configStr, OrderRefundConfigEntity.class);
        String orderRefund = null;
        if(MarketTypeEnum.CASHIER.getIndex().byteValue() == data.getMarketingType()){
            //收银单，使用收银单的退款配置 收银单只有完成的订单，直接判断是否可以退款就行
            orderRefund = config.getCashierOrderRefund();
        } else if (OrderType.TAKE_OUT.getCode().equals(data.getOrderType())) {
            //外卖单，使用外卖单的退款配置
            switch (data.getStatus()) {
                // 未接单
                case 1: orderRefund = config.getDeliveryTakeOrderRefund(); break;
                //已接单
                case 3: orderRefund = config.getDeliveryReceiptOrderRefund(); break;
                //制作完成
                case 31: orderRefund = config.getDeliveryCompleteMakeOrderRefund(); break;
                // 订单完成
                case 5: orderRefund = config.getDeliveryOrderRefund(); break;
                default: break;
            }
        } else {
            //其他，使用堂食的退款配置（必须先判断收银单，因为收银单的类型也是堂食，只是orderClient不一样
            switch (data.getStatus()) {
                // 未接单
                case 1: orderRefund = config.getTakeOrderRefund(); break;
                //已接单
                case 3: orderRefund = config.getReceiptOrderRefund(); break;
                //制作完成
                case 31: orderRefund = config.getCompleteMakeOrderRefund(); break;
                // 订单完成
                case 5: orderRefund = config.getOrderRefund(); break;
                default: break;
            }
        }
        return ALLOW_REFUND.equals(orderRefund);
    }

    /**
     * 获取已完成订单退款金额
     * isRefundDeliveryFee 退款是否退配送费已在申请退款传到订单基础服务，取订单售后单中退款金额 actualAmount
     */
    public BigDecimal getRefundAmount(OrderBeanV1 data,boolean isRefundDeliveryFee) {
        //是否配置已完成订单可退款
        BigDecimal refundAmount = new BigDecimal(data.getAmount());
//        if (isRefundDeliveryFee || isPayBySVC(data)){
//            return refundAmount;
//        }
//        List<AccountBeanV1> accountList = data.getAccountList();
//        if (CollectionUtils.isNotEmpty(accountList)) {
//            for (AccountBeanV1 orderCostResp : accountList) {
//                if (orderCostResp.getType() == OldOrderAccountType.DELIVERY_AMOUNT.getCode()) {
//                    refundAmount = new BigDecimal(data.getAmount().intValue() - orderCostResp.getPrice());
//                }
//            }
//        }
        return refundAmount;
    }
    /**
     * 订单是否使用储值卡支付（储值卡支付的订单，不支持部分退款）
     *
     * @param order
     * @return true-是，false-不是
     */
    private boolean isPayBySVC(OrderBeanV1 order) {
        return PAY_CODE_10102.equalsIgnoreCase(order.getPayChannel());
    }

    /**
     * 需要三方配送的saas外卖
     * @param orderBean
     * @return
     */
    private boolean checkSaasWm(OrderBeanV1 orderBean) {
        //
        if (1 == orderBean.getOrderType()
                && OrderSourceV1.SAAS.getCode().equals(orderBean.getSource())
                && THIRD.equalsIgnoreCase(orderBean.getAddInfo().getDeliveryType())) {
            return true;
        } else {
            return false;
        }
    }
    private boolean verifyThirdFlow(OrderBeanV1 orderBean,OrderManagerRequest request) {
        // 运单异常 运单取消  正常的运单是不允许手工操作流转的
        Boolean horseman =  request.getHorseman()!=null ? request.getHorseman():false;
        List<Integer> allow = Arrays.asList(DeliveryStatus.DELIVERYERROR.getCode(), DeliveryStatus.DELIVERYCANCEL.getCode());
        if (!allow.contains(orderBean.getDeliverStatus()) && !horseman) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 新版saas商城同意退款校验
     *
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse fmMallOrderAgreeRefund(OrderBeanV1 orderBean, OrderManagerRequest request) {
        //已取消的订单不能操作
        if (ObjectUtils.equals(OrderStatusV1.CANCEL.getV2Code(), orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER_HAS_CANCELED);
        }
        //判断订单是否有申请退款
        if (orderBean.getHasRefund() == null || !orderBean.getHasRefund()) {
            return ResponseUtil.error(ResponseResult.ORDER_REFUND_NOT_APPLY);
        }
//        //订单是否支持退款
//        boolean isCanRefund = false;
//        //订单
//        boolean isRefundDeliveryFee=false;
//        //saas渠道订单，已完成的订单不能操作, 商户配置已完成订单可退款可退款
//        if (ObjectUtils.equals(orderBean.getBizType(), BizTypeEnum.MALL.getBizType())) {
//            isCanRefund = getRefundConfig(orderBean);
//            if (!isCanRefund) {
//                return ResponseUtil.error(ResponseResult.ORDER_HAD_AFFIRM_CAN_NOT_REFUND);
//            }
//        }
//        if (isCanRefund) {
//            orderBean.setAmount(getRefundAmount(orderBean,isRefundDeliveryFee).longValue());
//        }
        return ResponseUtil.success();
    }

}