package cn.freemud.management.service.adapter;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.management.entities.dto.request.order.OrderManagerRequest;
import cn.freemud.management.entities.dto.request.order.RefundSuccessCallbackVo;
import cn.freemud.management.entities.dto.response.order.OrderManagerResponse;
import cn.freemud.management.enums.OperateType;
import cn.freemud.management.enums.ResponseResult;
import cn.freemud.management.service.OrderBaseService;
import cn.freemud.management.service.handle.OrderVerifyHandle;
import cn.freemud.management.util.ResponseUtil;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.enums.BizTypeEnum;
import com.freemud.application.sdk.api.ordercenter.enums.NewOrderStatus;
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 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.util.Objects;

@Component
public class OrderManagerAdapter {

    @Autowired
    private OrderVerifyHandle orderVerifyHandle;
    @Autowired
    private OrderBaseService orderBaseService;
    @Autowired
    private OrderBeanFactory orderBeanFactory;
    @Value("${mccafe.partner.id}")
    private String macCafePartnerId;


    /**
     * 接单
     *
     * @param request
     * @return
     */
    public BaseResponse<OrderManagerResponse> orderConfirmTake(OrderManagerRequest request) {
        //查询订单
        BaseResponse<OrderBeanV1> orderBeanResp = this.getOrderBean(request.getOrderId());
        if (!Objects.equals(orderBeanResp.getCode(), ResponseResult.SUCCESS.getCode())) {
            return ResponseUtil.error(orderBeanResp.getMessage());
        }
        OrderBeanV1 orderBean = orderBeanResp.getResult();
        //订单接单参数校验
        String companyId = orderBean.getCompanyId();
        if (!macCafePartnerId.equals(companyId)) {
            BaseResponse verifyResponse = orderVerifyHandle.orderConfirmTakeVerify(orderBean, request);
            if (ObjectUtils.notEqual(verifyResponse.getCode(), ResponseResult.SUCCESS.getCode())) {
                return verifyResponse;
            }
        }
        BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderConfirm(request, orderBean);
        return handleResponse(request, orderBean, orderManagerResponse);
    }

    /**
     * 制作完成
     *
     * @param request
     * @return
     */
    public BaseResponse<OrderManagerResponse> orderDone(OrderManagerRequest request) {
        //查询订单
        OrderBeanV1 orderBean = orderBaseService.getByOrderCode(request.getOrderId());
        if (null == orderBean) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        //订单接单参数校验
        BaseResponse verifyResponse = orderVerifyHandle.orderDoneVerify(orderBean, request);
        if (ObjectUtils.notEqual(verifyResponse.getCode(), ResponseResult.SUCCESS.getCode())) {
            return handleResponse(request, orderBean, verifyResponse);
        }
        BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderDone(request, orderBean);
        return handleResponse(request, orderBean, orderManagerResponse);
    }

    /**
     * 送出
     *
     * @param request
     * @return
     */
    public BaseResponse<OrderManagerResponse> orderDelivery(OrderManagerRequest request) {
        //查询订单
        OrderBeanV1 orderBean = orderBaseService.getByOrderCode(request.getOrderId());
        if (Objects.isNull(orderBean)) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        /*****兼容爱马哥，送出即完成start******/
        if (!OrderTypeV1.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
            request.setOperateType(OperateType.ORDER_AFFIRM.getOpType());
            return orderAffirm(request, orderBean);
        }
        /*****容爱马哥，送出即完成end******/
        //订单接单参数校验
        BaseResponse verifyResponse = orderVerifyHandle.orderDeliveryVerify(orderBean, request);
        if (ObjectUtils.notEqual(verifyResponse.getCode(), ResponseResult.SUCCESS.getCode())) {
            return StringUtils.equals(verifyResponse.getCode(), ResponseResult.ORDER_IS_COMPLETE_CAN_NOT_DELIVERY.getCode()) ? handleResponse(request, orderBean, ResponseUtil.success()) : handleResponse(request, orderBean, verifyResponse);
        }
        BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderDelivery(request, orderBean);
        return handleResponse(request, orderBean, orderManagerResponse);
    }

    /**
     * 完成
     *
     * @param request
     * @return
     */
    public BaseResponse<OrderManagerResponse> orderAffirm(OrderManagerRequest request, OrderBeanV1 orderBean) {
        if (orderBean == null) {
            //查询订单
            orderBean = orderBaseService.getByOrderCode(request.getOrderId());
            if (null == orderBean) {
                return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
            }
        }
        //订单接单参数校验
        BaseResponse verifyResponse = orderVerifyHandle.orderAffirmVerify(orderBean, request);
        if (ObjectUtils.notEqual(verifyResponse.getCode(), ResponseResult.SUCCESS.getCode())) {
            return handleResponse(request, orderBean, verifyResponse);
        }
        BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderAffirm(request, orderBean);
        return handleResponse(request, orderBean, orderManagerResponse);
    }

    /**
     * 拒单
     *
     * @param request
     * @return
     */
    public BaseResponse orderReject(OrderManagerRequest request) {
        //查询订单
        OrderBeanV1 orderBean = orderBaseService.getByOrderCode(request.getOrderId());
        if (null == orderBean) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        //订单接单参数校验
        BaseResponse verifyResponse;
        if (BizTypeEnum.MALL.getBizType().compareTo(orderBean.getBizType()) == 0) {
            verifyResponse = orderVerifyHandle.mallOrderRejectVerify(orderBean, request);
        } else {
            if (!macCafePartnerId.equals(orderBean.getCompanyId())) {
                verifyResponse = orderVerifyHandle.orderRejectVerify(orderBean, request);
            } else {
                verifyResponse = orderVerifyHandle.mcCafeOrderRejectVerify(orderBean, request);
            }
        }
        if (ObjectUtils.notEqual(verifyResponse.getCode(), ResponseResult.SUCCESS.getCode())) {
            return handleResponse(request, orderBean, verifyResponse);
        }
        BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderReject(request, orderBean);
        return handleResponse(request, orderBean, orderManagerResponse);
    }

    /**
     * 同意退款
     *
     * @param request
     * @return
     */
    public BaseResponse orderAgreeRefund(OrderManagerRequest request) {
        //查询订单
        OrderBeanV1 orderBean = orderBaseService.getByOrderCode(request.getOrderId());
        if (null == orderBean) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        //订单接单参数校验
        BaseResponse verifyResponse;
        if (BizTypeEnum.MALL.getBizType() == orderBean.getBizType()) {
            verifyResponse = orderVerifyHandle.mallOrderAgreeRefund(orderBean, request);
        }else if(BizTypeEnum.FM_MALL.getBizType()==orderBean.getBizType()){//新版saas商城同意退款校验
            verifyResponse = orderVerifyHandle.fmMallOrderAgreeRefund(orderBean, request);
        }else{
            verifyResponse = orderVerifyHandle.orderAgreeRefund(orderBean, request);
        }
        if (ObjectUtils.notEqual(verifyResponse.getCode(), ResponseResult.SUCCESS.getCode())) {
            return handleResponse(request, orderBean, verifyResponse);
        }
        BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderAgreeRefund(request, orderBean);
        return handleResponse(request, orderBean, orderManagerResponse);
    }

    /**
     * 同意退款或者取消订单
     */
    public BaseResponse orderPayRefund(OrderManagerRequest request) {
        //查询订单
        OrderBeanV1 orderBean = orderBaseService.getByOrderCode(request.getOrderId());
        if (null == orderBean) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        if (CollectionUtils.isNotEmpty(orderBean.getRefundList())) {
            //订单接单参数校验
            BaseResponse verifyResponse = orderVerifyHandle.orderAgreeRefundMCCafe(orderBean, request);
            if (ObjectUtils.notEqual(verifyResponse.getCode(), ResponseResult.SUCCESS.getCode())) {
                return handleResponse(request, orderBean, verifyResponse);
            }
            BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderAgreeRefund(request, orderBean);
            return handleResponse(request, orderBean, orderManagerResponse);
        } else {
            BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderCancel(request, orderBean);
            return handleResponse(request, orderBean, orderManagerResponse);
        }
    }

    /**
     * 拒绝退款
     *
     * @param request
     * @return
     */
    public BaseResponse orderRejectRefund(OrderManagerRequest request) {
        //查询订单
        OrderBeanV1 orderBean = orderBaseService.getByOrderCode(request.getOrderId());
        if (null == orderBean) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        //订单接单参数校验
        BaseResponse verifyResponse;
        if (BizTypeEnum.MALL.getBizType() == orderBean.getBizType()) {
            verifyResponse = orderVerifyHandle.mallOrderRejectRefund(orderBean, request);
        } else {
            verifyResponse = orderVerifyHandle.orderRejectRefund(orderBean, request);
        }


        if (ObjectUtils.notEqual(verifyResponse.getCode(), ResponseResult.SUCCESS.getCode())) {
            return handleResponse(request, orderBean, verifyResponse);
        }
        BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderRejectRefund(request, orderBean);
        return handleResponse(request, orderBean, orderManagerResponse);
    }

    /**
     * 取消订单
     *
     * @param request
     * @return
     */
    public BaseResponse orderCancel(OrderManagerRequest request) {
        //查询订单
        OrderBeanV1 orderBean = orderBaseService.getByOrderCode(request.getOrderId());
        if (null == orderBean) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderCancel(request, orderBean);
        return handleResponse(request, orderBean, orderManagerResponse);
    }

    /**
     * 拒绝退款
     *
     * @param request
     * @return
     */
    public BaseResponse mcCafeOrderRejectRefund(OrderManagerRequest request) {
        //查询订单
        OrderBeanV1 orderBean = orderBaseService.getByOrderCode(request.getOrderId());
        if (null == orderBean) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        //订单接单参数校验
        BaseResponse verifyResponse = orderVerifyHandle.mcCafeOrderRejectRefund(orderBean, request);
        if (ObjectUtils.notEqual(verifyResponse.getCode(), ResponseResult.SUCCESS.getCode())) {
            return handleResponse(request, orderBean, verifyResponse);
        }
        BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderRejectRefund(request, orderBean);
        return handleResponse(request, orderBean, orderManagerResponse);
    }


    private BaseResponse<OrderManagerResponse> handleResponse(OrderManagerRequest request, OrderBeanV1 orderBean, BaseResponse result) {
        if (orderBean == null) {
            return result;
        }
        RefundStatusV1 refundStatus = CollectionUtils.isNotEmpty(orderBean.getRefundList()) ? RefundStatusV1.getRefundStatusByCodeV1(orderBean.getRefundList().get(0).getStatus()) : null;
        OrderStatusV1 orderStatus = OrderStatusV1.getByCode(orderBean.getStatus());
        if (ObjectUtils.equals(ResponseResult.SUCCESS.getCode(), result.getCode())) {
            OperateType byOpType = OperateType.getByOpType(request.getOperateType());
            if (byOpType != null) {
                switch (byOpType) {
                    case ORDER_CONFIRM:
                        orderStatus = OrderStatusV1.RECEIPT;
                        break;
                    case ORDER_DONE:
                        orderStatus = OrderStatusV1.COMPLETE_MAKE;
                        break;
                    case ORDER_SEND:
                        orderStatus = OrderStatusV1.DISTRIBUTION;
                        break;
                    case ORDER_AFFIRM:
                        orderStatus = OrderStatusV1.COMPLETE;
                        break;
                    case ORDER_REJECT:
                    case ORDER_AGREE_REFUND:
                        orderStatus = OrderStatusV1.CANCEL;
                        refundStatus = RefundStatusV1.COMPLETE_REFUND;
                        break;
                    case ORDER_REJECT_REFUND:
                        refundStatus = RefundStatusV1.REFUSE_REFUND;
                        break;
                    default:
                }
            }
            return ResponseUtil.success(new OrderManagerResponse(orderStatus, refundStatus));
        }
        result.setResult(new OrderManagerResponse(orderStatus, refundStatus));
        return result;
    }

    /**
     * 创建配送单
     *
     * @param request
     * @return
     */
    public BaseResponse orderCreateDelivery(OrderManagerRequest request) {
        //查询订单
        BaseResponse<OrderBeanV1> orderBeanResp = this.getOrderBean(request.getOrderId());
        if (!Objects.equals(orderBeanResp.getCode(), ResponseResult.SUCCESS.getCode())) {
            return ResponseUtil.error(orderBeanResp.getMessage());
        }
        OrderBeanV1 orderBean = orderBeanResp.getResult();
        //订单接单参数校验
        if (orderBean == null) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderCreateDelivery(request, orderBean);
        return handleResponse(request, orderBean, orderManagerResponse);
    }

    private BaseResponse<OrderBeanV1> getOrderBean(String orderId) {
        //查询订单
        OrderBeanV1 orderBean = orderBaseService.getByOrderCode(orderId);
        // 防止NPE
        if (orderBean == null) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        return ResponseUtil.success(orderBean);
    }

    /**
     * 取消配送
     *
     * @param request
     * @return
     */
    public BaseResponse orderCancelDelivery(OrderManagerRequest request) {
        //查询订单
        BaseResponse<OrderBeanV1> orderBeanResp = this.getOrderBean(request.getOrderId());
        if (!Objects.equals(orderBeanResp.getCode(), ResponseResult.SUCCESS.getCode())) {
            return ResponseUtil.error(orderBeanResp.getMessage());
        }
        OrderBeanV1 orderBean = orderBeanResp.getResult();
        BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderCancelDelivery(request, orderBean);
        return handleResponse(request, orderBean, orderManagerResponse);
    }

    /**
     * @param request
     * @return 改操作 无需校验订单参数 直接退款
     * 使用该方法 请先进行报备, 因为不暴露给外部使用, 不属于业务代码
     * @see OrderManagerAdapter#orderAgreeRefund(cn.freemud.management.entities.dto.request.order.OrderManagerRequest)
     */
    public BaseResponse developRefund(OrderManagerRequest request) {
        //查询订单
        OrderBeanV1 orderBean = orderBaseService.getByOrderCode(request.getOrderId());
        if (null == orderBean) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        // 设置退款金额
        orderBean.setAmount(orderVerifyHandle.getRefundAmount(orderBean, false).longValue());
        BaseResponse<OrderManagerResponse> orderManagerResponse = orderBeanFactory.getOrderManagerService(orderBean).orderAgreeRefund(request, orderBean);
        return handleResponse(request, orderBean, orderManagerResponse);
    }


    /**
     * 支付退款成功回调
     *
     * @param request
     * @return
     */
    public BaseResponse refundSuccessCallback(RefundSuccessCallbackVo request) {
        // step 1 查订单
        OrderBeanV1 orderBean = orderBaseService.getByOrderCode(request.getOrderCode());
        if (null == orderBean) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        // step 2 检查订单状态
        //已取消的订单不能操作
        if (ObjectUtils.equals(OrderStatusV1.CANCEL.getV2Code(), orderBean.getStatusV2())) {
            return ResponseUtil.error(ResponseResult.ORDER_HAS_CANCELED);
        }
        // step 3 调用后续逻辑操作
        orderBeanFactory.getOrderManagerService(orderBean).refundSuccessCallback(request, orderBean);
        return ResponseUtil.success();
    }
}
