package com.ym.mec.biz.service.impl;

import java.math.BigDecimal;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ym.mec.biz.dal.dao.SysUserCashAccountDao;
import com.ym.mec.biz.dal.entity.SysUserCashAccount;
import com.ym.mec.biz.dal.enums.PlatformCashAccountStatusEnum;
import com.ym.mec.biz.service.SysUserCashAccountService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;

@Service
public class SysUserCashAccountServiceImpl extends BaseServiceImpl<Integer, SysUserCashAccount> implements SysUserCashAccountService {

	@Autowired
	private SysUserCashAccountDao sysUserCashAccountDao;

	@Override
	public BaseDAO<Integer, SysUserCashAccount> getDAO() {
		return sysUserCashAccountDao;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean updateBalance(Integer userId, BigDecimal decimal) {

		SysUserCashAccount cashAccount = sysUserCashAccountDao.getLocked(userId);
		if (cashAccount == null) {
			throw new BizException("用户[{}]现金账户不存在", userId);
		}

		if (cashAccount.getStatus() != PlatformCashAccountStatusEnum.NORMAL) {
			throw new BizException("账户不可用");
		}
		BigDecimal balance = cashAccount.getBalance().add(decimal);
		if (balance.doubleValue() < 0) {
			throw new BizException("现金账户[{}]余额不足，可用余额剩{}元", userId, cashAccount.getBalance().doubleValue());
		}

		cashAccount.setBalance(balance);
		cashAccount.setUpdateTime(new Date());

		sysUserCashAccountDao.update(cashAccount);

		return true;
	}

}