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

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
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.LuckDrawPrizeDao;
import com.ym.mec.biz.dal.entity.LuckDrawCount;
import com.ym.mec.biz.dal.entity.LuckDrawGroup;
import com.ym.mec.biz.dal.entity.LuckDrawPrize;
import com.ym.mec.biz.service.LuckDrawCountService;
import com.ym.mec.biz.service.LuckDrawGroupService;
import com.ym.mec.biz.service.LuckDrawLogService;
import com.ym.mec.biz.service.LuckDrawPrizeService;
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 LuckDrawPrizeServiceImpl extends BaseServiceImpl<Integer, LuckDrawPrize> implements LuckDrawPrizeService {

	/** 抽奖概率的固定基数 */
	private final int DRAW_BASE_NUMBER = 100000;

	@Autowired
	private LuckDrawPrizeDao luckDrawPrizeDao;

	@Autowired
	private LuckDrawLogService luckDrawLogService;

	@Autowired
	private LuckDrawCountService luckDrawCountService;

	@Autowired
	private LuckDrawGroupService luckDrawGroupService;

	@Override
	public BaseDAO<Integer, LuckDrawPrize> getDAO() {
		return luckDrawPrizeDao;
	}

	@Override
	public boolean batchInsert(List<LuckDrawPrize> luckDrawPrizeList) {
		if (luckDrawPrizeList != null && luckDrawPrizeList.size() > 0) {
			luckDrawPrizeDao.batchInsert(luckDrawPrizeList);
		}
		return true;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public LuckDrawPrize draw(final Long userId, int group) {
		final LuckDrawGroup luckDrawGroup = luckDrawGroupService.get(group);
		if (luckDrawGroup == null) {
			throw new BizException("系统出错");
		}
		Date currentDate = new Date();
		// 是否过期
		if (currentDate.before(luckDrawGroup.getStartTime()) || currentDate.after(luckDrawGroup.getEndTime())) {
			throw new BizException("抽奖未开始或已结束");
		}

		int consumeValue = luckDrawGroup.getConsumeValue();
		String consumeType = luckDrawGroup.getConsumeType();

		if (StringUtils.equalsIgnoreCase("TIMES", consumeType)) {
			// 判断是否有抽奖机会
			LuckDrawCount luckDrawCount = luckDrawCountService.getLock(userId);
			if (luckDrawCount == null) {
				throw new BizException("当前没有抽奖机会");
			}
			if (luckDrawCount.getAvailableCount() <= 0) {
				throw new BizException("当前没有抽奖机会");
			}
			// 更新抽奖机会
			luckDrawCount.setAvailableCount(luckDrawCount.getAvailableCount() - consumeValue);
			luckDrawCount.setModifyOn(currentDate);
			if (luckDrawCount.getUsedCount() == null) {
				luckDrawCount.setUsedCount(1);
			} else {
				luckDrawCount.setUsedCount(luckDrawCount.getUsedCount() + consumeValue);
			}
			luckDrawCountService.update(luckDrawCount);
		} else {
			throw new BizException("系统数据异常");
		}
		// 抽奖逻辑
		List<LuckDrawPrize> luckDraws = luckDrawPrizeDao.queryEnabledList(group);
		if (luckDraws != null) {
			int randomNum = RandomUtils.nextInt(0, DRAW_BASE_NUMBER);
			double start = 0;
			double chances = 0;
			for (LuckDrawPrize luckDraw : luckDraws) {
				chances += luckDraw.getChances();
				// 抽中了
				if (start <= randomNum && randomNum < (chances * DRAW_BASE_NUMBER)) {
					LuckDrawPrize syncLuckDraw = luckDrawPrizeDao.getLock(luckDraw.getId());
					Date date = new Date();
					// 检查库存
					if (syncLuckDraw.getIsDefault() == true || syncLuckDraw.getStock() > 0) {
						// 减库存
						syncLuckDraw.setStock(syncLuckDraw.getStock() - 1);
						syncLuckDraw.setModifyOn(date);
						update(syncLuckDraw);
						// 抽奖记录
						luckDrawLogService.add(userId, syncLuckDraw.getId(), group);

						return syncLuckDraw;
					} else {
						// 库存不足，抽中默认奖品
						List<LuckDrawPrize> defaultPrizeList = luckDrawPrizeDao.queryDefaultPrize(group);
						if (defaultPrizeList != null && defaultPrizeList.size() > 0) {
							syncLuckDraw = luckDrawPrizeDao.getLock(defaultPrizeList.get(0).getId());
							// 减库存
							syncLuckDraw.setStock(syncLuckDraw.getStock() - 1);
							syncLuckDraw.setModifyOn(date);
							update(syncLuckDraw);
							// 抽奖记录
							luckDrawLogService.add(userId, syncLuckDraw.getId(), group);
							return syncLuckDraw;
						} else {
							throw new BizException("系统繁忙，请重试");
						}
					}
				}
				start = luckDraw.getChances() * DRAW_BASE_NUMBER;
			}
		}
		return null;
	}

}
