package org.springblade.payment.handle.handler;

import lombok.AllArgsConstructor;
import org.springblade.common.enums.OrderType;
import org.springblade.common.enums.ResCode;
import org.springblade.common.enums.SystemConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.payment.handle.entity.HandleData;
import org.springblade.payment.handle.entity.Order;
import org.springblade.ldt.bills.entity.BalanceBills;
import org.springblade.ldt.bills.service.IBalanceBillsService;
import org.springblade.ldt.user.entity.LoginUser;
import org.springblade.payment.entity.SuccessParams;
import org.springframework.util.Assert;

import java.math.BigDecimal;

/**
 * @author: lianghanqiang
 * @description: 用户账户余额处理
 * @since: 8/26/21 -- 6:24 PM
 */
@AllArgsConstructor
public class BalanceHandle implements BaseHandle {

	private IBalanceBillsService balanceBillsService;

	/**
	 * 	用户的余额扣除，余额足够抵消交易金额，剩余支付金额remain为0，交易结束
	 * 	不足抵消，remain将会流转到下一个节点处理
	 * */
	@Override
	public HandleData handle(BigDecimal remain, Order order, SuccessParams successParams) throws ServiceException {
		LoginUser user = order.getLoginUser();


		//用户账户余额为0
		if(user.getBalance().compareTo(BigDecimal.ZERO)<=0){
			successParams.getBills().setBalanceNum(BigDecimal.ZERO);
			return HandleData.builder().isSuccess(Boolean.TRUE).successParams(successParams).remain(remain).build();
		}


		//余额抵消情况
		BigDecimal handlePrice = order.getMoney();
		remain = user.getBalance().subtract(remain);
		if(remain.compareTo(BigDecimal.ZERO)>=0){
			remain =BigDecimal.ZERO;
		}else{
			remain = remain.abs();
			handlePrice =  user.getBalance();
		}

		BalanceBills balanceBills = addBillRecord(order, user, handlePrice);
		successParams.setBalanceBillsId(balanceBills.getId());
		successParams.getBills().setBalanceNum(handlePrice);

		return HandleData.builder().isSuccess(Boolean.TRUE).successParams(successParams).remain(remain).build();
	}

	/**
	 * 	添加积分抵消记录
	 *
	 * @return*/
	private BalanceBills addBillRecord(Order order, LoginUser user, BigDecimal price) {
		BalanceBills balanceBills = new BalanceBills();
		balanceBills.setReceiveId(order.getShopId());
		balanceBills.setType(OrderType.PAY_CONSUMER.name());
		balanceBills.setStatus(SystemConstant.BillPayStatus.待付款.name());
		balanceBills.setTitle("商家扫码收款");
		balanceBills.setPayId(user.getId());
		balanceBills.setPrice(price);
		Assert.isTrue(balanceBillsService.save(balanceBills),()->{throw new ServiceException(ResCode.TRADE_ERROR);});
		return balanceBills;
	}
}
