package org.springblade.payment.callback.trade;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
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.mall.entity.Mall;
import org.springblade.ldt.mall.service.IMallService;
import org.springblade.payment.entity.SuccessParams;
import org.springblade.payment.event.MallRechargeEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * @author July
 * @description 商场充值回调
 * @createdTime 2021/9/29 10:41
 */
@AllArgsConstructor
@Component
public class MallRechargeCallback {

	private IBillsService billsService;
	private IMallService mallService;

	@EventListener
	@Async
	@Transactional
	public void PaySuccess(MallRechargeEvent mallRechargeEvent) {
		SuccessParams successParams = mallRechargeEvent.getSuccessParams();
		JSONObject res = successParams.getRes();
		Bills bills = billsService.getOne(new QueryWrapper<Bills>().lambda().eq(Bills::getId, successParams.getBills().getId()));
		handleBills(res, bills);
		handleMall(bills);
	}

	private void handleMall(Bills bills) {
		Mall mall = mallService.getById(bills.getMallId());
		mall.setBalance(mall.getBalance().add(bills.getPrice()));
		Assert.isTrue(billsService.saveOrUpdate(bills), () -> {
			throw new ServiceException("更新商场充值余额异常！");
		});
	}

	private void handleBills(JSONObject res, Bills bills) {
		bills.setPayStatus(AppConstant.BillPayStatus.付款成功.name());
		bills.setBillDesc(res.getString("remitComment"));
		bills.setThirdOrderId(res.getString("orderNo"));
		Assert.isTrue(billsService.saveOrUpdate(bills), () -> {
			throw new ServiceException("更新付款账单信息异常！");
		});
	}

}
