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.pay.PayRefundResponse;
import cn.freemud.management.enums.ResponseResult;
import cn.freemud.management.intercept.OrderServiceException;
import cn.freemud.management.util.ResponseUtil;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.enums.AfterSalesCreateEvent;
import com.freemud.application.sdk.api.ordercenter.enums.AfterSalesType;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.application.sdk.api.ordercenter.request.AfterSalesOperateReq;
import com.freemud.application.sdk.api.ordercenter.request.OrderModifyRelatingCodeReq;
import com.freemud.sdk.api.assortment.order.adapter.OrderSdkAdapter;
import com.freemud.sdk.api.assortment.order.enums.PayRefundStatus;
import com.freemud.sdk.api.assortment.order.enums.RefundStatus;
import com.freemud.sdk.api.assortment.order.request.order.BaseQueryOrderRequest;
import com.freemud.sdk.api.assortment.order.request.order.CancelOrderRequest;
import com.freemud.sdk.api.assortment.order.request.order.OrderRefundRequest;
import com.freemud.sdk.api.assortment.order.response.order.BaseOrderResponse;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

    @Autowired
    private OrderSdkAdapter orderSdkAdapter;
    @Autowired
    private OrderCenterSdkService orderCenterSdkService;


    /**
     * 确认接单
     *
     * @param request
     * @param orderBean
     * @return
     */
    public BaseResponse orderConfirm(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        //订单接单
        BaseQueryOrderRequest orderConfirmRequest = orderSdkAdapter.getOrderConfirmRequest(request.getOperator(), orderBean);
        BaseOrderResponse confirmOrderResponse = orderCenterSdkService.orderConfirmTake(orderConfirmRequest);
        //处理1秒重复接单问题 订单服务接单返回20067重复操作，20018状态机不支持认为接单成功
        if ("20067".equals(confirmOrderResponse.getErrcode().toString()) || "20018".equals(confirmOrderResponse.getErrcode().toString()) || "50002".equals(confirmOrderResponse.getErrcode().toString())) {
            return ResponseUtil.success();
        }
        if (ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), confirmOrderResponse.getErrcode().toString())) {
            throw new OrderServiceException(ResponseResult.ORDER_ACCEPT_FAILED);
        }
        return ResponseUtil.success();
    }

    /**
     * 更新取餐码
     * @param request
     * @param orderBean
     * @return
     */
    public BaseResponse updatePickUpGoodNo(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        // 更新取餐码
        OrderModifyRelatingCodeReq relatingCodeReq =new OrderModifyRelatingCodeReq();
        relatingCodeReq.setOrderCode(orderBean.getOid());
        relatingCodeReq.setOperator(request.getOperator());
        relatingCodeReq.setPartnerId(request.getPartnerId());
        relatingCodeReq.setPickUpGoodsNo(request.getPickUpGoodsNo());
        BaseOrderResponse baseOrderResponse = orderCenterSdkService.updatePickUpGoodNo(relatingCodeReq, LogThreadLocal.getTrackingNo());
        if (ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), baseOrderResponse.getErrcode().toString())) {
            return ResponseUtil.error(ResponseResult.ORDER_UPDATE_PICKUP_FAILED);
        }
        return ResponseUtil.success();
    }

    /**
     * 订单制作完成
     *
     * @param request
     * @param orderBean
     * @return
     */
    public BaseResponse orderDone(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        BaseQueryOrderRequest orderDoneRequest = orderSdkAdapter.getOrderConfirmRequest(request.getOperator(), orderBean);
        BaseOrderResponse baseOrderResponse = orderCenterSdkService.orderDone(orderDoneRequest);
        if (baseOrderResponse == null || ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), baseOrderResponse.getErrcode().toString())) {
            return ResponseUtil.error(ResponseResult.DONE_ORDER_FAIL);
        }
        return ResponseUtil.success();
    }

    /**
     * 订单配送
     *
     * @param request
     * @param orderBean
     * @return
     */
    public BaseResponse orderDelivery(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        BaseQueryOrderRequest orderDeliveryRequest = orderSdkAdapter.getOrderConfirmRequest(request.getOperator(), orderBean);
        BaseOrderResponse baseOrderResponse = orderCenterSdkService.orderSend(orderDeliveryRequest);
        if (baseOrderResponse == null || ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), baseOrderResponse.getErrcode().toString())) {
            return ResponseUtil.error(ResponseResult.DELIVERY_FAIL);
        }
        return ResponseUtil.success();
    }

    /**
     * 订单完成
     *
     * @param request
     * @param orderBean
     * @return
     */
    public BaseResponse orderAffirm(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        BaseQueryOrderRequest orderAffirmRequest = orderSdkAdapter.getOrderConfirmRequest(request.getOperator(), orderBean);
        BaseOrderResponse baseOrderResponse = orderCenterSdkService.orderAffirm(orderAffirmRequest);
        if (baseOrderResponse == null || ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), baseOrderResponse.getErrcode().toString())) {
            return ResponseUtil.error(ResponseResult.AFFIRM_ORDER_FAIL);
        }
        return ResponseUtil.success();
    }

    /**
     * 拒单
     *
     * @param request
     * @param orderBean
     * @return
     */
    public BaseResponse orderReject(OrderManagerRequest request, PayRefundResponse refundResponse, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        //作废订单
        CancelOrderRequest cancelOrderRequest = orderSdkAdapter.getCancelOrderRequest(request.getOperator(), request.getReason(), refundResponse.getPayRefundStatus(), refundResponse.getRefundId(), orderBean);
        BaseOrderResponse baseOrderResponse = orderCenterSdkService.orderReject(cancelOrderRequest);
        if (baseOrderResponse == null || ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), baseOrderResponse.getErrcode().toString())) {
            return ResponseUtil.error(ResponseResult.AFFIRM_ORDER_FAIL);
        }
        return ResponseUtil.success();
    }

    /**
     * 麦咖啡拒单
     *
     * @param request
     * @param orderBean
     * @return
     */
    public BaseResponse mcCafeOrderReject(OrderManagerRequest request, PayRefundResponse refundResponse, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        //作废订单
        CancelOrderRequest cancelOrderRequest = orderSdkAdapter.getCancelOrderRequest(request.getOperator(), request.getReason(), refundResponse.getPayRefundStatus(), refundResponse.getRefundId(), orderBean);
        BaseOrderResponse baseOrderResponse = orderCenterSdkService.mcCafeOrderReject(cancelOrderRequest, orderBean);
        if (baseOrderResponse == null || ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), baseOrderResponse.getErrcode().toString())) {
            return ResponseUtil.error(ResponseResult.AFFIRM_ORDER_FAIL);
        }
        return ResponseUtil.success();
    }

    /**
     * 同意退款
     *
     * @param request
     * @param refundResponse
     * @param orderBean
     * @return
     */
    public BaseResponse refundAgree(OrderManagerRequest request, PayRefundResponse refundResponse, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        BaseQueryOrderRequest refundAgreeRequest = orderSdkAdapter.getRefundAgreeRequest(refundResponse.getRefundId(), request.getReason(), request.getOperator(), orderBean);
        BaseOrderResponse baseOrderResponse = null;
        if (PayRefundStatus.SUCCESS.equals(refundResponse.getPayRefundStatus())) {
            baseOrderResponse = orderCenterSdkService.refundComplete(refundAgreeRequest);
        } else {
            baseOrderResponse = orderCenterSdkService.refundReturn(refundAgreeRequest);
        }
        if (baseOrderResponse == null || ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), baseOrderResponse.getErrcode().toString())) {
            return ResponseUtil.error(ResponseResult.AGREE_REFUND_ORDER_FAIL);
        }
        return ResponseUtil.success();
    }

    /**
     * 麦咖啡同意退款
     *
     * @param request
     * @param refundResponse
     * @param orderBean
     * @return
     */
    public BaseResponse mcCafeRefundAgree(OrderManagerRequest request, PayRefundResponse refundResponse, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        BaseQueryOrderRequest refundAgreeRequest = orderSdkAdapter.getRefundAgreeRequest(refundResponse.getRefundId(), request.getReason(), request.getOperator(), orderBean);
        BaseOrderResponse baseOrderResponse = null;
        for(int i=0;i<orderBean.getRefundList().size();i++) {

            if (RefundStatus.APPLY_REFUND.getCode().equals(orderBean.getRefundList().get(i).getStatus())) {
                refundAgreeRequest.setAfterSalesCode(orderBean.getRefundList().get(i).getRid());
                if (PayRefundStatus.SUCCESS.equals(refundResponse.getPayRefundStatus())) {
                    baseOrderResponse = orderCenterSdkService.refundComplete(refundAgreeRequest);
                } else {
                    baseOrderResponse = orderCenterSdkService.refundReturn(refundAgreeRequest);
                }
                break;
            } else if (RefundStatus.COMPLETE_REFUND.getCode().equals(orderBean.getRefundList().get(i).getStatus())) {
                baseOrderResponse = new BaseOrderResponse();
                baseOrderResponse.setErrcode(Integer.valueOf(ResponseResult.AGREE_REFUND_ORDER_FAIL.getCode()));
                baseOrderResponse.setErrmsg("订单已经退款完成，不能重复申请");
                break;
            }
        }
        if(null == baseOrderResponse) {
            OrderRefundRequest orderRefundRequest = new OrderRefundRequest();
            orderRefundRequest.setPartnerId(refundAgreeRequest.getPartnerId());
            orderRefundRequest.setStoreId(refundAgreeRequest.getShopId());
            orderRefundRequest.setOrderId(refundAgreeRequest.getOrderId());
            orderRefundRequest.setOrderClient(OrderClientType.SAAS.getIndex());

            orderRefundRequest.setAfterSalesType(AfterSalesType.PARTNER_CANCEL);
            orderRefundRequest.setReason(refundAgreeRequest.getReason());
            orderRefundRequest.setOperator(refundAgreeRequest.getOperator());
            orderRefundRequest.setOrderStatus(orderBean.getStatus());
            if (PayRefundStatus.SUCCESS.equals(refundResponse.getPayRefundStatus())) {
                orderRefundRequest.setCreateEvent(4);
            } else {
                orderRefundRequest.setCreateEvent(5);
            }
            baseOrderResponse = orderCenterSdkService.orderRefund(orderRefundRequest);
        }
        if (baseOrderResponse == null || ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), baseOrderResponse.getErrcode().toString())) {
            return ResponseUtil.error(ResponseResult.AGREE_REFUND_ORDER_FAIL);
        }
        return ResponseUtil.success();
    }

    /**
     * 拒绝退款
     * @param request
     * @param orderBean
     * @return
     */
    public BaseResponse refundReject(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        CancelOrderRequest rejectRefundRequest = orderSdkAdapter.getRejectRefundRequest(request.getOperator(), request.getReason(), orderBean);
        BaseOrderResponse baseOrderResponse = orderCenterSdkService.orderRefundReject(rejectRefundRequest);
        if (baseOrderResponse == null || ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), baseOrderResponse.getErrcode().toString())) {
            return ResponseUtil.error(ResponseResult.REJECT_REFUND_ORDER_FAIL);
        }
        return ResponseUtil.success();
    }

    /**
     * 麦咖啡拒绝退款
     * @param request
     * @param orderBean
     * @return
     */
    public BaseResponse mcCafeRefundReject(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean) {
        CancelOrderRequest rejectRefundRequest = orderSdkAdapter.getRejectRefundRequest(request.getOperator(), request.getReason(), orderBean);
        BaseOrderResponse baseOrderResponse = null;
        for(int i=0;i<orderBean.getRefundList().size();i++) {

            if (RefundStatus.APPLY_REFUND.getCode().equals(orderBean.getRefundList().get(i).getStatus())) {
                rejectRefundRequest.setAfterSalesCode(orderBean.getRefundList().get(i).getRid());
                baseOrderResponse = orderCenterSdkService.orderRefundReject(rejectRefundRequest);
            }
            if (RefundStatus.COMPLETE_REFUND.getCode().equals(orderBean.getRefundList().get(i).getStatus())) {
                baseOrderResponse = new BaseOrderResponse();
                baseOrderResponse.setErrcode(100);
                baseOrderResponse.setErrmsg("success");
            }
        }
        if (baseOrderResponse == null || ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), baseOrderResponse.getErrcode().toString())) {
            return ResponseUtil.error(ResponseResult.REJECT_REFUND_ORDER_FAIL);
        }
        return ResponseUtil.success();
    }

    /**
     * 取消订单
     */
    public BaseResponse orderCancel(OrderManagerRequest request, PayRefundResponse refundResponse,QueryOrdersResponse.DataBean.OrderBean orderBean) {
        //作废订单
        CancelOrderRequest cancelOrderRequest = orderSdkAdapter.getCancelOrderRequest(request.getOperator(), request.getReason(), refundResponse.getPayRefundStatus(), refundResponse.getRefundId(), orderBean);
        BaseOrderResponse baseOrderResponse = orderCenterSdkService.orderCancel(cancelOrderRequest);
        if (baseOrderResponse == null || ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), baseOrderResponse.getErrcode().toString())) {
            return ResponseUtil.error(ResponseResult.AFFIRM_ORDER_FAIL);
        }
        return ResponseUtil.success();
    }


}
