package cn.freemud.management.service.impl;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.management.entities.dto.request.order.OrderManagerRequest;
import cn.freemud.management.entities.dto.response.activity.GroupWorkRefundResponse;
import cn.freemud.management.entities.dto.response.order.OrderManagerResponse;
import cn.freemud.management.entities.dto.response.pay.PayRefundResponse;
import cn.freemud.management.enums.OperateType;
import cn.freemud.management.enums.ResponseResult;
import cn.freemud.management.intercept.OrderServiceException;
import cn.freemud.management.service.OrderBaseService;
import cn.freemud.management.service.OrderManagerService;
import cn.freemud.management.service.handle.*;
import cn.freemud.management.util.ResponseUtil;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.constant.ResponseConstant;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.enums.AfterSalesStatus;
import com.freemud.application.sdk.api.ordercenter.enums.BizTypeEnum;
import com.freemud.application.sdk.api.ordercenter.enums.MarketTypeEnum;
import com.freemud.application.sdk.api.ordercenter.enums.RefundModeEnum;
import com.freemud.application.sdk.api.ordercenter.request.AfterOrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.request.AfterSalesRefundFailReq;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
import com.freemud.sdk.api.assortment.order.enums.PayRefundStatus;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: rrr
 * @Package cn.freemud.management.service.impl
 * @Description: 外卖订单履单操作
 * @author: zhiheng.zhang
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
public class MallOrderMangerServiceImpl implements OrderManagerService {
    @Autowired
    private MallOrderHandle mallOrderHandle;
    @Autowired
    private OrderBaseService orderBaseService;
    @Autowired
    private PaymentHandle paymentHandle;
    @Autowired
    private DeliveryHandle deliveryHandle;
    @Autowired
    private StockHandle stockHandle;
    @Autowired
    private ActivityHandle activityHandle;
    @Autowired
    private OrderSdkService orderSdkService;

    /**
     * 同意退款
     *
     * @param request
     * @param orderBean
     * @return
     */
    @Override
    public BaseResponse<OrderManagerResponse> orderAgreeRefund(OrderManagerRequest request, OrderBeanV1 orderBean) {
        //取消配送单
//        deliveryHandle.cancelDelivery(orderBean,request);
        boolean flag = false;
        Byte refundMode = RefundModeEnum.REFUND_ALL.getIndex();
        if(null != orderBean.getAfterSalesOrderResp() && StringUtils.isNotEmpty(orderBean.getAfterSalesOrderResp().getExtInfo())){
            AfterOrderExtInfoDto afterOrderExtInfoDto = JSONObject.parseObject(orderBean.getAfterSalesOrderResp().getExtInfo(),AfterOrderExtInfoDto.class);
            if(null !=afterOrderExtInfoDto) {
                refundMode = afterOrderExtInfoDto.getRefundMode();
            }
        }

        if((StringUtils.isNotEmpty(request.getOperator()) && "自动任务".equalsIgnoreCase(request.getOperator())) && Objects.equals(RefundModeEnum.REFUND_ALL.getIndex(),refundMode) && Objects.nonNull(orderBean.getAfterSalesOrderResp()) && Objects.equals(AfterSalesStatus.PENDING.getIndex(), orderBean.getAfterSalesOrderResp().getAfterSalesStatus())){
            // 修改售后单状态为退货中
            BaseResponse mallOrderAgreeApply = mallOrderHandle.mallOrderAgreeApply(request, orderBean);
            if (mallOrderAgreeApply == null || ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), mallOrderAgreeApply.getCode())) {
                return ResponseUtil.error(ResponseResult.AGREE_REFUND_APPLY_ORDER_FAIL);
            }
            // 拼团订单主动退款触发通知促销
            if (Objects.equals(BizTypeEnum.MALL.getBizType(), orderBean.getBizType())
                    && Objects.equals(MarketTypeEnum.GROUPB.getIndex().byteValue(), orderBean.getMarketingType())) {
                GroupWorkRefundResponse refundResponse = activityHandle.groupWorkRefund(orderBean);
                if (Objects.isNull(refundResponse) || !Objects.equals(ResponseConstant.SUCCESS_RESPONSE_CODE, refundResponse.getStatusCode())) {
                    return ResponseUtil.error(ResponseResult.SPELL_GROUP_REFUND_ERROR);
                }
            }

            //支付退款
            PayRefundResponse refundResponse = this.payRefundCommon(request, orderBean);
            //fisherman --> 退款中的状态 阻止后续流程 等待支付回调  不是退款成功 都终止下面的退款流程
            if (refundResponse.getPayRefundStatus().getCode().compareTo(PayRefundStatus.SUCCESS.getCode()) != 0) {
                return ResponseUtil.error(ResponseResult.REFUND_FAIL);
            }
            //订单同意退款
            mallOrderHandle.refundAgree(request, refundResponse, orderBean);
            // 推送pos、微信消息中心
            orderBaseService.sendMessage(orderBean, OperateType.ORDER_AGREE_REFUND, request.getReason());
            //todo  可以考虑基于订单回调异步实现
            //冲正库存
            stockHandle.revert(request, orderBean);
        }else {
            if (Objects.equals(RefundModeEnum.REFUND_ALL.getIndex(), refundMode) && Objects.nonNull(orderBean.getAfterSalesOrderResp()) && Objects.equals(AfterSalesStatus.PENDING.getIndex(), orderBean.getAfterSalesOrderResp().getAfterSalesStatus())) {
                // 修改售后单状态为退货中
                mallOrderHandle.mallOrderAgreeApply(request, orderBean);
            } else {
                // 拼团订单主动退款触发通知促销
                if (Objects.equals(BizTypeEnum.MALL.getBizType(), orderBean.getBizType())
                        && Objects.equals(MarketTypeEnum.GROUPB.getIndex().byteValue(), orderBean.getMarketingType())) {
                    GroupWorkRefundResponse refundResponse = activityHandle.groupWorkRefund(orderBean);
                    if (Objects.isNull(refundResponse) || !Objects.equals(ResponseConstant.SUCCESS_RESPONSE_CODE, refundResponse.getStatusCode())) {
                        return ResponseUtil.error(ResponseResult.SPELL_GROUP_REFUND_ERROR);
                    }
                }

                //支付退款
                PayRefundResponse refundResponse = this.payRefundCommon(request, orderBean);
                //fisherman --> 退款中的状态 阻止后续流程 等待支付回调  不是退款成功 都终止下面的退款流程
                if (refundResponse.getPayRefundStatus().getCode().compareTo(PayRefundStatus.SUCCESS.getCode()) != 0) {
                    return ResponseUtil.error(ResponseResult.REFUND_FAIL);
                }
                //订单同意退款
                mallOrderHandle.refundAgree(request, refundResponse, orderBean);
                // 推送pos、微信消息中心
                orderBaseService.sendMessage(orderBean, OperateType.ORDER_AGREE_REFUND, request.getReason());
                //todo  可以考虑基于订单回调异步实现
                //冲正库存
                stockHandle.revert(request, orderBean);
            }
        }
        return ResponseUtil.success();
    }

    /**
     * 拒绝退款
     *
     * @param request
     * @param orderBean
     * @return
     */
    @Override
    public BaseResponse<OrderManagerResponse> orderRejectRefund(OrderManagerRequest request, OrderBeanV1 orderBean) {
        //拒绝退款
        mallOrderHandle.mallRefundReject(request,orderBean);
        // 推送pos、微信消息中心
        orderBaseService.sendMessage(orderBean, OperateType.ORDER_REJECT_REFUND, request.getReason());
        return ResponseUtil.success();
    }

    /**
     * 拒单
     *
     * @param request
     * @param orderBean
     * @return
     */
    @Override
    public BaseResponse<OrderManagerResponse> orderReject(OrderManagerRequest request, OrderBeanV1 orderBean) {
        //支付退款
        PayRefundResponse refundResponse = this.payRefundCommon(request, orderBean);
        //fisherman --> 退款中的状态 阻止后续流程 等待支付回调  不是退款成功 都终止下面的退款流程
        if (refundResponse.getPayRefundStatus().getCode().compareTo(PayRefundStatus.SUCCESS.getCode()) != 0) {
            return ResponseUtil.error(ResponseResult.REFUND_FAIL);
        }
        //订单拒单
        mallOrderHandle.mallOrderReject(request, refundResponse, orderBean);
        // 推送pos、微信消息中心
        orderBaseService.sendMessage(orderBean, OperateType.ORDER_REJECT, request.getReason());
        //todo  可以考虑基于订单回调异步实现
        //冲正库存
        stockHandle.revert(request,orderBean);
        return ResponseUtil.success();
    }


    /**
     * 老的微商城退款 废弃
     */
    private PayRefundResponse payRefundCommon(OrderManagerRequest request, OrderBeanV1 orderBean) {
        PayRefundResponse refundResponse = paymentHandle.getCommonPayRefundResponse(request, orderBean);
        //同意退款失败记录到订单售后单
        if (orderBean.getAfterSalesOrderResp() != null && refundResponse.getPayRefundStatus().getCode().compareTo(PayRefundStatus.FAIL.getCode()) == 0) {
            AfterSalesRefundFailReq refundFailReq = new AfterSalesRefundFailReq();
            refundFailReq.setOrderCode(orderBean.getOid());
            refundFailReq.setPartnerId(orderBean.getCompanyId());
            refundFailReq.setRefundFailReason("退款失败或退款中，" + refundResponse.getMessage());
            refundFailReq.setAfterSalesCode(orderBean.getAfterSalesOrderResp().getAfterSalesCode());
            refundFailReq.setOperationClient(request.getOperationClient());
            refundFailReq.setOperator(request.getOperator());
            orderSdkService.refundFail(refundFailReq, LogThreadLocal.getTrackingNo());
        }
        return refundResponse;
    }

}
