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.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.OperateClient;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
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.enums.OldOrderType;
import com.freemud.sdk.api.assortment.order.enums.OrderSourceType;
import com.freemud.sdk.api.assortment.order.enums.RefundStatus;
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 (!OrderStatus.TAKE_ORDER.getCode().equals(orderBean.getStatus())) {
            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 (OrderStatus.COMPLETE.getCode().equals(orderBean.getStatus())) {
            return ResponseUtil.error(ResponseResult.ORDER_IS_COMPLETE_CAN_NOT_DELIVERY, getOrderManagerResponse(orderBean));
        }
        //订单已经发送过配送
        if (OrderStatus.DISTRIBUTION.getCode().equals(orderBean.getStatus())) {
            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 (!OrderStatus.RECEIPT.getCode().equals(orderBean.getStatus())) {
            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 (OrderStatus.COMPLETE_MAKE.getCode().equals(orderBean.getStatus())) {
            return ResponseUtil.error(ResponseResult.DONE_FAIL_REPETITION, getOrderManagerResponse(orderBean));
        }
        //订单非接单状态，不能制作完成
        if (!OrderStatus.RECEIPT.getCode().equals(orderBean.getStatus())) {
            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 (OrderStatus.COMPLETE.getCode().equals(orderBean.getStatus())) {
            return ResponseUtil.error(ResponseResult.DELIVERY_SEND_REPETITION, getOrderManagerResponse(orderBean));
        }
        //已取消的订单不能操作
        if (OrderStatus.CANCEL.getCode().equals(orderBean.getStatus())) {
            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(OrderStatus.DISTRIBUTION.getCode(), orderBean.getStatus())) {
            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(
                OrderSourceType.ELEME.getCode(),
                OrderSourceType.EBAI.getCode(),
                OrderSourceType.MTWM.getCode(),
                OrderSourceType.BDWM.getCode(),
                OrderSourceType.JUBAOPEN.getCode(),
                OrderSourceType.DIANPING.getCode(),
                OrderSourceType.KOUBEI.getCode()
        );
        // 非三方渠道, 且是外卖类型三方配送的订单，不再进行售后单的判断,否则配送无法进行流转
        return !Objects.equals(OldOrderType.TAKE_OUT.getCode(), orderBean.getType())
                || !(!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 status = orderBean.getStatus();
        //判断订单是否已经被拒单
        if (OrderStatus.REFUSE.getCode().equals(status)) {
            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 (OrderStatus.DISTRIBUTION.getCode().equals(status)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_ORDER_IS_DELIVERY, getOrderManagerResponse(orderBean));
        }
        //判断订单是否已送达
        if (OrderStatus.COMPLETE.getCode().equals(status)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_ORDER_IS_COMPLETE, getOrderManagerResponse(orderBean));
        }
        if (!OrderStatus.TAKE_ORDER.getCode().equals(status)) {
            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 status = orderBean.getStatus();
        //判断订单是否已经被拒单
        if (OrderStatus.REFUSE.getCode().equals(status)) {
            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 (OrderStatus.DISTRIBUTION.getCode().equals(status)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_ORDER_IS_DELIVERY, getOrderManagerResponse(orderBean));
        }
        //判断订单是否已送达
        if (OrderStatus.COMPLETE.getCode().equals(status)) {
            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 status = orderBean.getStatus();
        //判断订单是否已经被拒单
        if (OrderStatus.REFUSE.getCode().equals(status)) {
            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 (OrderStatus.DISTRIBUTION.getCode().equals(status)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_ORDER_IS_DELIVERY, getOrderManagerResponse(orderBean));
        }
        //判断订单是否已送达
        if (OrderStatus.COMPLETE.getCode().equals(status)) {
            return ResponseUtil.error(ResponseResult.REJECT_FAIL_ORDER_IS_COMPLETE, getOrderManagerResponse(orderBean));
        }
        if (!OrderStatus.TAKE_ORDER.getCode().equals(status) && !OldOrderType.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(OrderStatus.CANCEL.getCode(), orderBean.getStatus())) {
            return ResponseUtil.error(ResponseResult.ORDER_HAS_CANCELED);
        }
        //判断订单是否有申请退款
        if (orderBean.getHasRefund() == null
                || !orderBean.getHasRefund()
                || orderBean.getRefundList().get(orderBean.getRefundList().size() - 1).getStatus() != 1) {
            return ResponseUtil.error(ResponseResult.ORDER_REFUND_NOT_APPLY);
        }
        //订单是否支持退款
        boolean isCanRefund = false;
        //订单
        boolean isRefundDeliveryFee=false;
        //saas渠道订单，已完成的订单不能操作, 商户配置已完成订单可退款可退款
        if (ObjectUtils.equals(orderBean.getSource(), OrderSource.SAAS.getSource())) {
            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(OrderStatus.CANCEL.getCode(), orderBean.getStatus())) {
            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.getSource(), OrderSource.MALL.getSource())) {
            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(OrderStatus.CANCEL.getCode(), orderBean.getStatus())) {
            return ResponseUtil.error(ResponseResult.ORDER_HAS_CANCELED);
        }
        for (RefundBeanV1 refundBean : orderBean.getRefundList()) {
            if(RefundStatus.APPLY_REFUND.getCode().equals(refundBean.getStatus())) {
                return ResponseUtil.success();
            }
            if(RefundStatus.COMPLETE_REFUND.getCode().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()) {
            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 (ObjectUtils.notEqual(list.get(list.size() - 1).getStatus(), 1)) {
            return ResponseUtil.error(ResponseResult.ORDER_REJECT_REFUND_STATUS_NOT);
        }
        //新订单，已完成，取消订单不能操作
        if (OrderSource.SAAS.getSource().equals(orderBean.getSource())
                && (OrderStatus.TAKE_ORDER.getCode().equals(orderBean.getStatus())
                || OrderStatus.CANCEL.getCode().equals(orderBean.getStatus()))) {
            return ResponseUtil.error(ResponseResult.ORDER_REJECT_REFUND_STATUS_END);
        }
        return ResponseUtil.success();
    }

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

        List<String> standardPaymentRefundSourceList = Lists.newArrayList(OrderSourceType.SAAS.getCode(), OrderSourceType.APP.getCode(), OrderSourceType.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 (OrderSource.MALL.getSource().equals(orderBean.getSource())
                && (OrderStatus.TAKE_ORDER.getCode().equals(orderBean.getStatus())
                || OrderStatus.CANCEL.getCode().equals(orderBean.getStatus()))) {
            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 (OrderStatus.CANCEL.getCode().equals(orderBean.getStatus())) {
                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 (OrderSource.BDWM.getSource().equals(source) || OrderSource.JDWM.getSource().equals(source)
                || OrderSource.MTWM.getSource().equals(source) || OrderSource.ELEME.getSource().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(com.freemud.sdk.api.assortment.order.enums.OrderSourceType.SAASMALL.getCode(),data.getSource()) ){
            // 除 未支付 拒单 和 取消外，其他可退款
            return Stream.of(OrderStatus.WAIT_PAY,OrderStatus.REFUSE,OrderStatus.CANCEL).noneMatch(s -> Objects.equals(data.getStatus(),s.getCode()));
        }
        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 (OrderClientType.CASHIER.getIndex().toString().equals(data.getOrderClient())) {
            //收银单，使用收银单的退款配置
            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 (OrderClientType.CASHIER.getIndex().toString().equals(data.getOrderClient())) {
            //收银单，使用收银单的退款配置 收银单只有完成的订单，直接判断是否可以退款就行
            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);
    }

    /**
     * 获取已完成订单退款金额
     */
    private 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.getType()
                && OrderSource.SAAS.getSource().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;
        }
    }
}