package com.jeequan.jeepay.pay.ctrl.channel.alipay.service;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.entity.MchApp;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.rqrs.refund.RefundOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.refund.RefundOrderRS;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchStoreDevice;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.db.entity.RefundOrder;
import com.jeequan.jeepay.pay.ctrl.channel.alipay.model.response.AlipaySpiPayOrderQueryResponse;
import com.jeequan.jeepay.pay.ctrl.channel.alipay.model.response.AlipaySpiRefundAuthCodeApplyResponse;
import com.jeequan.jeepay.pay.ctrl.channel.alipay.model.response.AlipaySpiRefundOrderResponse;
import com.jeequan.jeepay.pay.ctrl.channel.alipay.model.response.SpiBaseResponse;
import com.jeequan.jeepay.pay.ctrl.channel.alipay.util.AlipaySpiRuyiUtil;
import com.jeequan.jeepay.pay.ctrl.payorder.AbstractPayOrderController;
import com.jeequan.jeepay.pay.ctrl.refund.RefundOrderController;
import com.jeequan.jeepay.service.impl.PayOrderService;
import com.jeequan.jeepay.service.impl.RefundOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 支付宝如意spi接口：退款、退款查单
 *
 * @author zx
 *
 * @date 2021-04-27 15:50
 */
@Slf4j
@Service
public class AlipaySpiRuyiRefundOrderService extends AbstractPayOrderController {

	@Autowired private PayOrderService payOrderService;
	@Autowired private RefundOrderService refundOrderService;

	/** 通过交易凭证商户单号查询支付订单  **/
	public AlipaySpiPayOrderQueryResponse billQuery(MchStoreDevice mchStoreDevice) {
		String platformMchOrderNo = getValStringRequired("bill_merchant_no");

		PayOrder payOrder = payOrderService.selectOneByPlatformMchOrderNo(platformMchOrderNo);
		if (payOrder == null || !PayOrder.DEVICE_TYPE_ALIPAY_RUYI_LITE.equals(payOrder.getDeviceType()) || !payOrder.getDeviceNo().equals(mchStoreDevice.getDeviceNo())) {
			throw new BizException("支付订单不存在");
		}
		return AlipaySpiRuyiUtil.covertToAlipaySpiPayOrderQueryResponse(payOrder);
	}

	/** 申请退款授权码  **/
	public SpiBaseResponse refundAuthCodeApply(MchStoreDevice mchStoreDevice) {
		AlipaySpiRefundAuthCodeApplyResponse response = new AlipaySpiRefundAuthCodeApplyResponse();
		response.setGrantResult(true);
		response.setGrantPath("OTHER");
		return response;
	}

	/** 退款  **/
	public AlipaySpiRefundOrderResponse refund(MchStoreDevice mchStoreDevice) throws AlipayApiException {
		String logPrefix = "【支付宝如意Lite】退款";

		Long refundAmount = getRequiredAmountL("refund_amount");
		String payOrderId = getValStringRequired("isv_order_no"); // 服务商测订单号
		String merchantOrderNo = getValStringRequired("merchant_order_no"); // 商家订单号
		String merchantRefundNo = getValStringRequired("merchant_refund_no"); // 商家退款单号
		String authCode = getValString("auth_code");

		// 端上超时会相同参数重复调用
		RefundOrder refundOrder = refundOrderService.queryMchOrder(mchStoreDevice.getMchNo(), merchantRefundNo, null);
		if (refundOrder != null) {
			return AlipaySpiRuyiUtil.covertToAlipaySpiRefundOrderResponse(refundOrder, merchantOrderNo);
		}

		// 封装下单参数
		RefundOrderRQ rq = new RefundOrderRQ();
		rq.setMchOrderNo(merchantOrderNo);
		rq.setPayOrderId(payOrderId);
		rq.setMchRefundNo(merchantRefundNo);
		rq.setCurrency("cny");
		rq.setRefundAmount(refundAmount);
		rq.setRefundReason("如意Lite退款");
		rq.setClientIp(getClientIp());

		rq.setMchNo(mchStoreDevice.getMchNo());
		rq.setAppId(mchStoreDevice.getAppId());

		rq.setSignType(MchApp.SIGN_TYPE_MD5); // 设置默认签名方式为MD5

		RefundOrderController refundOrderController = SpringBeansUtil.getBean(RefundOrderController.class);
		ApiRes apiRes = refundOrderController.refund(rq);
		logger.info("{}发起退款，返回apiRes：{}", logPrefix, JSON.toJSONString(apiRes));
		if (ApiCodeEnum.SUCCESS.getCode() != apiRes.getCode()) {
			throw new AlipayApiException("BIZ_ERROR", apiRes.getMsg());
		}

		RefundOrderRS refundOrderRS = (RefundOrderRS) apiRes.getData();

		RefundOrder dbRecord = refundOrderService.getById(refundOrderRS.getRefundOrderId());
		AlipaySpiRefundOrderResponse response = AlipaySpiRuyiUtil.covertToAlipaySpiRefundOrderResponse(dbRecord, merchantOrderNo);

		return response;
	}

	/** 通过交易凭证商户单号查询支付订单  **/
	public AlipaySpiRefundOrderResponse refundQuery(MchStoreDevice mchStoreDevice) {
		String merchantOrderNo = getValStringRequired("merchant_order_no"); // 商家订单号
		String payOrderId = getValStringRequired("isv_order_no"); // 服务商订单号
		String merchantRefundNo = getValStringRequired("merchant_refund_no"); // 商家退款单号
		String refundOrderId = getValString("isv_refund_no"); // 服务商退款订单号

		RefundOrder refundOrder = refundOrderService.queryMchOrder(mchStoreDevice.getMchNo(), merchantRefundNo, refundOrderId);
		if (refundOrder == null || !refundOrder.getPayOrderId().equals(payOrderId)) {
			throw new BizException("退款订单不存在");
		}
		return AlipaySpiRuyiUtil.covertToAlipaySpiRefundOrderResponse(refundOrder, merchantOrderNo);
	}

}
