package cn.freemud.management.service.handle;

import cn.freemud.management.adapter.PaymentSdkAdapter;
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.thirdparty.MulitiPaymentClient;
import cn.freemud.management.util.RedisUtil;
import cn.freemud.redis.RedisCache;
import com.freemud.application.sdk.api.base.BaseResponse;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.AfterSalesOrderResp;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
import com.freemud.application.sdk.api.paymentcenter.client.request.OrderRefundNewRequest;
import com.freemud.application.sdk.api.paymentcenter.client.response.RefundNewResponse;
import com.freemud.application.sdk.api.paymentcenter.client.service.PaymentNewService;
import com.freemud.sdk.api.assortment.order.enums.OldOrderType;
import com.freemud.sdk.api.assortment.order.enums.PayRefundStatus;
import com.freemud.sdk.api.assortment.order.request.order.MultiOrderRefundRequest;
import com.freemud.sdk.api.assortment.order.response.order.MultiOrderRefundResponse;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse;
import com.freemud.sdk.api.assortment.payment.request.OrderRefundRequest;
import com.freemud.sdk.api.assortment.payment.response.OrderRefundResponse;
import com.freemud.sdk.api.assortment.payment.service.StandardPaymentService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
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.util.*;
import java.util.concurrent.TimeUnit;

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

    private static final String SUCCESS="100";

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

    @Autowired
    private StandardPaymentService standardPaymentService;
    @Autowired
    private PaymentSdkAdapter paymentSdkAdapter;
    @Autowired
    private OrderSdkService orderSdkService;
    @Autowired
    private MulitiPaymentClient mulitiPaymentClient;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private PaymentNewService paymentNewService;

    /**
     * 退款
     * @param request
     * @param orderBean
     * @return
     */
    public PayRefundResponse refund(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean){
        PayRefundStatus refundStatus=PayRefundStatus.SUCCESS;
        OrderRefundRequest orderRefundRequest = paymentSdkAdapter.getOrderRefundRequest(orderBean,getRefundAmount(orderBean));
        //抖音支付必传
        orderRefundRequest.setRefundDesc(request.getReason() == null? "商家退款" : request.getReason());
        if (ObjectUtils.equals(orderBean.getAmount(), 0L)) {
            return handlePayRefundResponse(refundStatus,orderRefundRequest.getRefundId());
        }
        BaseResponse<OrderRefundResponse> orderRefundResponse;
        orderRefundResponse = standardPaymentService.orderRefund(orderRefundRequest, LogThreadLocal.getTrackingNo());
        if (orderRefundResponse==null){
            throw new OrderServiceException(ResponseResult.REFUND_EXCEPTION);
        }
        if (ObjectUtils.notEqual(orderRefundResponse.getCode(),SUCCESS)){
            //商户余额不足的情况下，返回异常特殊处理.
            if(ResponseResult.NOT_SUFFICIENT_FUNDS.getCode().equals(orderRefundResponse.getCode())){
                throw new OrderServiceException(ResponseResult.NOT_SUFFICIENT_FUNDS);
            }
            throw new OrderServiceException(ResponseResult.REFUND_FAIL,orderRefundResponse.getMessage());
        }
        refundStatus=ObjectUtils.equals( PayRefundStatus.SUCCESS.getCode(), orderRefundResponse.getData().getRefundStatus())?PayRefundStatus.SUCCESS:PayRefundStatus.RUNNING;
        return handlePayRefundResponse(refundStatus,orderRefundRequest.getRefundId());
    }
    /**
     * 退款
     * @param orderBean
     * @return
     */
    public PayRefundResponse newOrderRefund(QueryOrdersResponse.DataBean.OrderBean orderBean, OrderExtInfoDto orderExtInfoDto){
        PayRefundStatus refundStatus=PayRefundStatus.SUCCESS;
        OrderRefundNewRequest refundRequest = paymentSdkAdapter.convert2OrderRefundNewRequest(orderBean, orderExtInfoDto);
        if (ObjectUtils.equals(orderBean.getAmount(), 0L)) {
            return handlePayRefundResponse(refundStatus,refundRequest.getRefundId());
        }
        com.freemud.application.sdk.api.base.BaseResponse<RefundNewResponse> orderRefundResponse;
        try {
            orderRefundResponse = paymentNewService.newOrderRefund(refundRequest, LogThreadLocal.getTrackingNo());
        }catch (Exception ex){
            ErrorLog.errorConvertJson(this.getClass(), "paymentNewService.newOrderRefundError", ex);
            throw new OrderServiceException(ResponseResult.REFUND_EXCEPTION);
        }
        if (orderRefundResponse==null){
            throw new OrderServiceException(ResponseResult.REFUND_EXCEPTION);
        }
        if (ObjectUtils.notEqual(orderRefundResponse.getCode(),SUCCESS)){
            throw new OrderServiceException(ResponseResult.REFUND_FAIL,orderRefundResponse.getMessage());
        }
        refundStatus=ObjectUtils.equals( PayRefundStatus.SUCCESS.getCode(), orderRefundResponse.getData().getCode())?PayRefundStatus.SUCCESS:PayRefundStatus.FAIL;
        return handlePayRefundResponse(refundStatus,refundRequest.getRefundId());
    }

    /**
     * 麦咖啡退款
     * @param request
     * @param orderBean
     * @return
     */
    public PayRefundResponse mcCafeRefund(OrderManagerRequest request, QueryOrdersResponse.DataBean.OrderBean orderBean){
        PayRefundStatus refundStatus=PayRefundStatus.SUCCESS;
        OrderRefundRequest orderRefundRequest = paymentSdkAdapter.getOrderRefundRequest(orderBean, new BigDecimal(orderBean.getAmount()));
        if (ObjectUtils.equals(orderBean.getAmount(), 0L)) {
            return handlePayRefundResponse(refundStatus,orderRefundRequest.getRefundId());
        }
        if(macCafePartnerId.equals(orderBean.getCompanyId())) {
            Map<String, String> extendParams = new HashMap<>();
            if(OldOrderType.TAKE_OUT.getCode().equals(orderBean.getOrderType())) {
                extendParams.put("mealType", "delivery");
            } else {
                extendParams.put("mealType", "pickup");
            }
            orderRefundRequest.setExtendParams(extendParams);
        }
        BaseResponse<OrderRefundResponse> orderRefundResponse;
        try {
            orderRefundResponse = standardPaymentService.orderRefund(orderRefundRequest, "");
        }catch (Exception ex){
            ErrorLog.errorConvertJson(this.getClass(), "refundError", ex);
            return handlePayRefundResponse(PayRefundStatus.FAIL,orderRefundRequest.getRefundId());
        }
        if (orderRefundResponse==null || ObjectUtils.notEqual(orderRefundResponse.getCode(),SUCCESS)){
            return handlePayRefundResponse(PayRefundStatus.FAIL,orderRefundRequest.getRefundId());
        }
        refundStatus=ObjectUtils.equals(PayRefundStatus.SUCCESS.getCode(), orderRefundResponse.getData().getRefundStatus())?PayRefundStatus.SUCCESS:PayRefundStatus.FAIL;
        return handlePayRefundResponse(refundStatus,orderRefundRequest.getRefundId());
    }

    /**
     * 获取退款金额
     *
     * @param data
     * @return
     */
    private BigDecimal getRefundAmount(QueryOrdersResponse.DataBean.OrderBean  data) {
        BigDecimal refundAmount = new BigDecimal(data.getAmount());
        com.freemud.application.sdk.api.ordercenter.response.BaseResponse<List<AfterSalesOrderResp>> listBaseResponse = orderSdkService.queryAfterSaleByOrderCode(data.getCompanyId(), data.getOid());
        if (CollectionUtils.isNotEmpty(listBaseResponse.getResult())){
            refundAmount=new BigDecimal(listBaseResponse.getResult().get(0).getActualAmount());
        }
        return refundAmount;
    }

    private PayRefundResponse handlePayRefundResponse(PayRefundStatus refundStatus, Long refundId){
        PayRefundResponse payRefundResponse = new PayRefundResponse();
        payRefundResponse.setPayRefundStatus(refundStatus);
        payRefundResponse.setRefundId(refundId.toString());
        return payRefundResponse;
    }

    private PayRefundResponse handlePayRefundResponse(PayRefundStatus refundStatus, String refundId){
        PayRefundResponse payRefundResponse = new PayRefundResponse();
        payRefundResponse.setPayRefundStatus(refundStatus);
        payRefundResponse.setRefundId(refundId.toString());
        return payRefundResponse;
    }

    public PayRefundResponse multiRefund(QueryOrdersResponse.DataBean.OrderBean orderBean){
        PayRefundStatus refundStatus=PayRefundStatus.SUCCESS;
        MultiOrderRefundRequest multiOrderRefundRequest = paymentSdkAdapter.getMultiOrderPayRefundRequest(orderBean,getRefundAmount(orderBean));
        MultiOrderRefundResponse multiOrderRefundResponse = mulitiPaymentClient.paymentApplicationRefund(multiOrderRefundRequest,orderBean.getCompanyId());
        if (multiOrderRefundResponse == null || multiOrderRefundResponse.getData() == null || !com.freemud.sdk.api.assortment.order.domain.ResponseCodeConstant.ORDER_PAY_RESPONSE_SUCCESS.equals(multiOrderRefundResponse.getCode())) {
            throw new OrderServiceException(ResponseResult.REFUND_EXCEPTION);
        }
        List<MultiOrderRefundResponse.RefundPlatformResponse> refundPlatformResponseList = multiOrderRefundResponse.getData().refundPlatformResponseList;
        if(null != refundPlatformResponseList && refundPlatformResponseList.size()>0){
            redisCache.save(RedisUtil.getPaymentTransIdSequenceKey(refundPlatformResponseList.get(0).getTransId()),orderBean.getOid(),1L,TimeUnit.DAYS);
        }
        return handlePayRefundResponse(refundStatus,multiOrderRefundRequest.getRefundTradeNo());
    }
}
