package com.ifish.serviceImpl;

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

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.ifish.dao.CouponDao;
import com.ifish.dao.CouponRecordDao;
import com.ifish.dao.GoldExpendRecordDao;
import com.ifish.dao.UserAssetDao;
import com.ifish.dto.JsonResult;
import com.ifish.dto.PageingDto;
import com.ifish.entity.Coupon;
import com.ifish.entity.CouponRecord;
import com.ifish.entity.GoldExpendRecord;
import com.ifish.entity.UserAsset;
import com.ifish.enums.BooleanEnum;
import com.ifish.enums.GoldExpendTypeEnum;
import com.ifish.enums.ResultEnum;
import com.ifish.exception.IfishException;
import com.ifish.hibernate.Pagination;
import com.ifish.service.CouponService;
import com.ifish.util.IfishUtil;
import com.ifish.util.ResultUtil;
import com.ifish.validator.PageParam;

/**
 * 优惠券
 * @author Administrator
 *
 */
@Service
@Transactional
public class CouponServiceImpl implements CouponService {

	@Autowired
	private CouponDao couponDao;
	@Autowired
	private UserAssetDao userAssetDao;
	@Autowired
	private CouponRecordDao couponRecordDao;
	@Autowired
	private GoldExpendRecordDao goldExpendRecordDao;
	
	/**
	 * 获取所有可兑换优惠券
	 */
	@Override
	public JsonResult<?> getAllValidCoupon() {
		Date curDate = IfishUtil.getCurDate();
		//可兑换优惠券
		List<Coupon> couponList = couponDao.findByProperty(
			Order.desc("updateTime"),
			Restrictions.or(
				//在结束日期前可兑换
				Restrictions.ge("validEndDate", curDate),
				//都为null表示无使用期限
				Restrictions.and(
					Restrictions.isNull("validStartDate"),
					Restrictions.isNull("validEndDate")
				)
			)
		);
		//查询兑换数量
		for (Coupon coupon : couponList) {
			//查询该兑换券的兑换数量
			int exchangeCount = couponRecordDao.getCouponRecordCountByCouponId(coupon.getCouponId());
			coupon.setExchangeCount(exchangeCount);
		}
		return ResultUtil.success(couponList);
	}

	/**
	 * 兑换优惠券
	 */
	@Override
	public JsonResult<?> exchangeCoupon(Integer userId, Integer couponId) {
		UserAsset userAsset = userAssetDao.get(userId);
		if(userAsset==null){
			throw new IfishException(ResultEnum.error402);
		}
		Coupon coupon = couponDao.get(couponId);
		if(coupon==null){
			throw new IfishException(ResultEnum.error402);
		}
		//有效期内可兑换
		Date validStartDate = coupon.getValidStartDate();
		Date validEndDate = coupon.getValidEndDate();
		Date curDate = IfishUtil.getCurDate();
		//不在有效期内
		if(validStartDate!=null && validEndDate!=null && curDate.compareTo(validEndDate)>0){
			throw new IfishException(ResultEnum.warn219);
		}
		//优惠券数量
		Integer couponNumber = coupon.getCouponNumber();
		if(couponNumber!=null && couponNumber<=0){
			throw new IfishException(ResultEnum.warn221);
		}
		//金币不足
		BigDecimal needGold = coupon.getNeedGold();
		BigDecimal goldValue = userAsset.getGoldValue();
		if(goldValue.compareTo(needGold)<0){
			JSONObject json = new JSONObject();
			json.put("goldValue", goldValue);
			return ResultUtil.warn(ResultEnum.warn215.getKey(),json);
		}
		//兑换上限
		Integer upperLimit = coupon.getUpperLimit();
		if(upperLimit!=null){
			int couponCount = couponRecordDao.getCouponRecordCountByUser(userId, couponId);
			//兑换达到上限
			if(couponCount>=upperLimit){
				throw new IfishException(ResultEnum.warn220);
			}
		}
		//新增优惠券兑换记录
		CouponRecord couponRecord = new CouponRecord();
		couponRecord.setUserId(userId);
		couponRecord.setCouponId(couponId);
		couponRecord.setMoneyValue(coupon.getMoneyValue());
		couponRecord.setNeedGold(coupon.getNeedGold());
		couponRecord.setUseNeedMoney(coupon.getUseNeedMoney());
		couponRecord.setTagText(coupon.getTagText());
		couponRecord.setValidStartDate(coupon.getValidStartDate());
		couponRecord.setValidEndDate(coupon.getValidEndDate());
		couponRecord.setIsUsed(BooleanEnum.NO.getKey());
		couponRecord.setCreateTime(new Date());
		//生成8位激活码
		while(true){
			String activationCode = IfishUtil.getCharAndNumr(8).toUpperCase();
			//查询激活码是否存在
			CouponRecord tmpCouponRecord = couponRecordDao.findUniqueByProperty(Restrictions.eq("activationCode", activationCode));
			if(tmpCouponRecord==null){
				couponRecord.setActivationCode(activationCode);
				couponRecordDao.save(couponRecord);
				//优惠券数量减一
				if(couponNumber!=null){
					couponNumber--;
					coupon.setCouponNumber(couponNumber);
				}
				break;
			}
		}
		//扣除金币
		goldValue = goldValue.subtract(needGold);
		userAsset.setGoldValue(goldValue);
		//兑换消耗金币记录
		GoldExpendRecord goldRecord = new GoldExpendRecord(userId, needGold, GoldExpendTypeEnum.exchangeCoupon);
		//兑换记录ID
		goldRecord.setRelationId(couponRecord.getRecordId());
		goldExpendRecordDao.save(goldRecord);
		//查询该兑换券的兑换数量
		int exchangeCount = couponRecordDao.getCouponRecordCountByCouponId(couponId);
		JSONObject json = new JSONObject();
		json.put("exchangeCount", exchangeCount);
		json.put("couponNumber", couponNumber);
		json.put("goldValue", goldValue);
		return ResultUtil.success(json);
	}
	
	/**
	 * 优惠券兑换记录
	 */
	@Override
	public PageingDto<?> getCouponRecordByPage(PageParam param) {
		//分页获取数据
		Integer firstResult = param.getFirstResult();
		Pagination<CouponRecord> page = couponRecordDao.findByCriteria(firstResult, param.getPageSize(), Order.desc("recordId"),Restrictions.eq("userId", param.getUserId()));
		List<CouponRecord> list = page.getList();
		firstResult+=list.size();
		//分页数据封装
		return ResultUtil.success(firstResult, page.getTotalCount(), list);
	}
}
