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.LuckDrawCountDao;
import com.ym.mec.biz.dal.entity.LuckDrawCount;
import com.ym.mec.biz.service.LuckDrawCountService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.service.impl.BaseServiceImpl;

@Service
public class LuckDrawCountServiceImpl extends BaseServiceImpl<Long, LuckDrawCount> implements LuckDrawCountService {

	@Autowired
	private LuckDrawCountDao luckDrawCountDao;

	@Override
	public BaseDAO<Long, LuckDrawCount> getDAO() {
		return luckDrawCountDao;
	}

	@Override
	public LuckDrawCount getLock(Long userId) {
		return luckDrawCountDao.getLock(userId);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean freeGive(Long userId, int times) {
		boolean isInsert = false;
		LuckDrawCount luckDrawCount = luckDrawCountDao.getLock(userId);
		if (luckDrawCount == null) {
			luckDrawCount = new LuckDrawCount();
			luckDrawCount.setUserId(userId);
			isInsert = true;
		}
		luckDrawCount.setAvailableCount(luckDrawCount.getAvailableCount() + times);
		luckDrawCount.setModifyOn(new Date());

		return isInsert ? insert(luckDrawCount) > 0 : update(luckDrawCount) > 0;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean updateTimes(Long userId, int times) {
		boolean isInsert = false;
		LuckDrawCount luckDrawCount = luckDrawCountDao.getLock(userId);
		if (luckDrawCount == null) {
			luckDrawCount = new LuckDrawCount();
			luckDrawCount.setUserId(userId);
			isInsert = true;
		}
		luckDrawCount.setAvailableCount(luckDrawCount.getAvailableCount() + times);
		luckDrawCount.setModifyOn(new Date());
		return isInsert ? insert(luckDrawCount) > 0 : update(luckDrawCount) > 0;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean updateAmount(Long userId, Long amount) {
		boolean isInsert = false;
		LuckDrawCount luckDrawCount = luckDrawCountDao.getLock(userId);
		if (luckDrawCount == null) {
			luckDrawCount = new LuckDrawCount();
			luckDrawCount.setUserId(userId);
			isInsert = true;
		}
		luckDrawCount.setAvailableAmount(luckDrawCount.getAvailableAmount().add(new BigDecimal(amount)));
		if (amount < 0) {
			luckDrawCount.setUsedCount(luckDrawCount.getUsedCount() + 1);
		}
		luckDrawCount.setModifyOn(new Date());
		return isInsert ? insert(luckDrawCount) > 0 : update(luckDrawCount) > 0;
	}

}
