package org.springblade.payment.callback.trade;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.enums.WithdrawStatus;
import org.springblade.common.enums.WithdrawType;
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.UserPointWithdrawEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
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 UserPointWithdrawCallback {

	private IWithdrawRecService withdrawRecService;
	private IShopService shopService;

	@EventListener
	public void PaySuccess(UserPointWithdrawEvent userPointWithdrawEvent) {
		SuccessParams successParams = userPointWithdrawEvent.getSuccessParams();

		Long withdrawRecId = successParams.getWithdrawRecId();
		WithdrawRec withdrawRec = withdrawRecService.getById(withdrawRecId);
		Assert.notNull(withdrawRec, "订单查询失败，无此订单信息！");
		Shop shop = shopService.getById(withdrawRec.getOwnerId());
		Assert.notNull(shop, "订单人查询失败，无此订单人信息！");

		//判断订单状态，已付款订单处理 （单笔支付可能接收多笔回调）
		if (Objects.equals(withdrawRec.getWithdrawStatus(), WithdrawStatus.DONE.getValue())) {
			return;
		}

		//收到回调改提现数据
		JSONObject res = successParams.getRes();
		if ("SUCCESS".equalsIgnoreCase(successParams.getStatus())) {
			withdrawRec.setThirdOrderId(successParams.getThirdOrderId());
			withdrawRec.setFee(successParams.getRes().getBigDecimal("fee"));//易宝手续费
			withdrawRec.setWithdrawStatus(WithdrawStatus.DONE.getValue());
			withdrawRec.setReceiveAmount(res.getBigDecimal("receiveAmount"));//实际到账金额
			withdrawRec.setOrderId(res.getString("orderNo"));

			BigDecimal price = withdrawRec.getReceiveAmount().add(withdrawRec.getFee()).add(withdrawRec.getPlatformFee());
			if (withdrawRec.getType().equals(WithdrawType.POINT_WITHDRAW)) {
				//积分提现成功扣商户积分余额
				shop.setPoint(shop.getPoint().subtract(price));
			} else if (withdrawRec.getType().equals(WithdrawType.RECEIVABLE_WITHDRAW)) {
				//应收提现成功扣商户可提现余额【已核销】
				shop.setWithdrawCharge(shop.getWithdrawCharge().subtract(price));
			}
			shopService.saveOrUpdate(shop);
		} else {
			withdrawRec.setWithdrawStatus(WithdrawStatus.FAIL.getValue());
			withdrawRec.setFailReason(res.getString("failReason"));
		}

		withdrawRecService.saveOrUpdate(withdrawRec);
	}
}
