package org.springblade.payment.callback.trade;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.entity.PointBills;
import org.springblade.ldt.bills.service.IBillsService;
import org.springblade.ldt.bills.service.IPointBillsService;
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.MallChargeEvent;
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;

import java.util.List;

/**
 * @author: lianghanqiang
 * @description: 代理付款回调
 * @since: 8/5/21 -- 3:01 PM
 */
@AllArgsConstructor
@Component
public class MallChargeCallback {

	private IBillsService billsService;
	private IPointBillsService pointBillsService;
	private IMallService mallService;


	@EventListener
	@Async
	@Transactional
	public void PaySuccess(MallChargeEvent mallChargeEvent) {
		SuccessParams successParams = mallChargeEvent.getSuccessParams();
		Bills bills = billsService.getOne(new QueryWrapper<Bills>().lambda().eq(Bills::getId, successParams.getBills().getId()));
		//*.先更新积分记录
		handlePointBills(bills);
		handleBills(bills, successParams.getRes());
		handleMall(bills);

	}

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

	/**
	 * 将积分明细修改已核销
	 */
	private void handlePointBills(Bills bills) {
		List<Long> ids = JSON.parseArray(bills.getBillDesc(), Long.class);
		Assert.isTrue(pointBillsService.update(Wrappers.<PointBills>lambdaUpdate().set(PointBills::getIsCheak, 1).in(PointBills::getId, ids)), () -> {
			throw new ServiceException("更新渠道积分账户异常！");
		});
	}

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


}
