package org.springblade.payment.callback.trade;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.enums.AppConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.ldt.bills.entity.Bills;
import org.springblade.ldt.bills.service.IBillsService;
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.WeChatPayEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * @author: lianghanqiang
 * @description: 用户通过微信付款回调
 * @since: 9/1/21 -- 4:52 PM
 */
@Component
@AllArgsConstructor
@Slf4j
public class WeChatPayCallback {
	private IBillsService billsService;
	private IShopService shopService;

	@EventListener
	@Transactional
	public void handleWeChatPayCallback(WeChatPayEvent weChatPayEvent){
		SuccessParams successParams = weChatPayEvent.getSuccessParams();

		//修改订单状态
		Bills bills = billsService.getById(successParams.getBills().getId());
		bills.setPayStatus(AppConstant.BillPayStatus.付款成功.name());

		//增加商户余额
		Shop shop = shopService.getById(bills.getReceiveId());
		shop.setBalance(shop.getBalance().add(bills.getPrice()));
		shop.setTotalBalance(shop.getBalance());
		Assert.isTrue(billsService.saveOrUpdate(bills),()->{throw new ServiceException("订单信息更新异常"); });
		Assert.isTrue(shopService.saveOrUpdate(shop),()->{throw new ServiceException("商户余额更新异常"); });
	}
}
