package org.springblade.payment.callback.trade;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeepay.yop.sdk.service.common.response.YopResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.cache.PaymentCache;
import org.springblade.common.constant.CallbackServeUrl;
import org.springblade.common.enums.OrderType;
import org.springblade.common.enums.WithdrawStatus;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.ldt.bills.entity.WithdrawRec;
import org.springblade.ldt.bills.service.IWithdrawRecService;
import org.springblade.ldt.shop.entity.Shop;
import org.springblade.ldt.shop.service.IShopService;
import org.springblade.payment.entity.SuccessParams;
import org.springblade.payment.event.UserPointTransferWithdrawEvent;
import org.springblade.yeePay.common.YeePayConst;
import org.springblade.yeePay.common.YeepayApiConstant;
import org.springblade.yeePay.entity.saas.account.WithdrawOrderDto;
import org.springblade.yeePay.service.YeepaySaasService;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author July
 * @version 1.0.0
 * @ClassName UserPointWithdrawCallback.java
 * @Description 用户积分提现---转账回调
 * @createTime 2021年10月19日 17:28:00
 */
@Component
@AllArgsConstructor
@Slf4j
public class UserPointTransferWithdrawCallback {

	private IWithdrawRecService withdrawRecService;
	private IShopService shopService;
	private YeepaySaasService yeepaySaasService;
	private YeePayConst yeePayConst;
	private BladeLogger bladeLogger;

	@EventListener
	public void PaySuccess(UserPointTransferWithdrawEvent userPointTransferWithdrawEvent) {
		SuccessParams successParams = userPointTransferWithdrawEvent.getSuccessParams();
		Long withdrawRecId = successParams.getWithdrawRecId();
		WithdrawRec withdrawRec = withdrawRecService.getById(withdrawRecId);
		Assert.notNull(withdrawRec, "订单查询失败，无此订单信息！");
		//接收到转账回调后进行用户提现操作
		Shop shop = shopService.getById(withdrawRec.getOwnerId());

		String requestNo = IdUtil.simpleUUID();
		WithdrawOrderDto withdrawOrderDto = WithdrawOrderDto.builder()
			.parentMerchantNo(yeePayConst.getPlatformServiceNo())
			.requestNo(requestNo)
			.merchantNo(shop.getMerchantNo())
			.bankAccountNo(withdrawRec.getReceiverAccountNo())
			.receiveType(YeepayApiConstant.receiveType.valueOf(withdrawRec.getReceiveType()))
			.orderAmount(successParams.getTotalPrice().toPlainString())
			.notifyUrl(CallbackServeUrl.CALL_BACK_SERVE_URL + "/withdraw/callback/YEE_PAY_WITHDRAW")
			.build();
		withdrawRec.setRequestNo(requestNo);
		withdrawRecService.saveOrUpdate(withdrawRec);

		bladeLogger.info("用户积分余额提现--提现请求参数", withdrawOrderDto.toString());
		YopResponse yopResponse = yeepaySaasService.withdrawOrder(withdrawOrderDto);
		JSONObject res = JSON.parseObject(yopResponse.getStringResult());
		if (!Objects.equals(res.getString("returnCode"), "UA00000")) {

			withdrawRec.setWithdrawStatus(WithdrawStatus.FAIL.getValue());
			withdrawRec.setFailReason(res.getString("returnMsg"));
			withdrawRecService.saveOrUpdate(withdrawRec);

			bladeLogger.info("userPointWithdraw-提现", res.toJSONString());
			throw new ServiceException(res.getString("returnMsg"));
		}

		//支付参数
		SuccessParams notifySuccessParams = SuccessParams.builder()
			.orderType(OrderType.USER_POINT_WITHDRAW.name())
			.status(WithdrawStatus.WAITING.getValue())
			.userId(withdrawRec.getOwnerId())
			.totalPrice(withdrawRec.getActualPrice())
			.shopId(shop.getId())
			.tenantId(shop.getTenantId())
			.withdrawRecId(withdrawRec.getId())
			.build();

		PaymentCache.putSuccessParams(Convert.toStr(requestNo), notifySuccessParams);
	}
}
