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

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ym.mec.biz.dal.dao.CourseScheduleRewardsRulesDao;
import com.ym.mec.biz.dal.entity.CourseSchedule.CourseScheduleType;
import com.ym.mec.biz.dal.entity.CourseScheduleRewardsRules.RewardMode;
import com.ym.mec.biz.dal.entity.CourseScheduleRewardsRules;
import com.ym.mec.biz.service.CourseScheduleRewardsRulesService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.util.json.JsonUtil;

@Service
public class CourseScheduleRewardsRulesServiceImpl extends BaseServiceImpl<Integer, CourseScheduleRewardsRules> implements CourseScheduleRewardsRulesService {

	@Autowired
	private CourseScheduleRewardsRulesDao courseScheduleRewardsDao;

	@Override
	public BaseDAO<Integer, CourseScheduleRewardsRules> getDAO() {
		return courseScheduleRewardsDao;
	}

	@Override
	public BigDecimal queryRewardsAmount(Integer organId, CourseScheduleType courseScheduleType, int coursesNum) {

		List<CourseScheduleRewardsRules> CourseScheduleRewardsRulesList = courseScheduleRewardsDao.query(organId, courseScheduleType);

		if (CourseScheduleRewardsRulesList == null || CourseScheduleRewardsRulesList.size() == 0) {
			return new BigDecimal(0);
		}

		CourseScheduleRewardsRules courseScheduleRewardsRules = CourseScheduleRewardsRulesList.get(0);

		String json = courseScheduleRewardsRules.getRewardsRulesJson();

		List<RewardsRules> rewardsRulesList = JsonUtil.parseArray(json, RewardsRules.class);
		
		Collections.sort(rewardsRulesList);
		
		RewardsRules rewardsRules = new RewardsRules();
		
		for(RewardsRules rule : rewardsRulesList){
			if(rule.min >= coursesNum && rule.max < coursesNum){
				rewardsRules = rule;
				break;
			}
		}
		
		if(courseScheduleRewardsRules.getRewardMode() == RewardMode.TOTAL){
			return rewardsRules.getAmount();
		}

		return rewardsRules.getAmount().multiply(new BigDecimal(coursesNum));
	}

	class RewardsRules implements Comparable<RewardsRules> {

		private int min;

		private int max;

		private BigDecimal amount = new BigDecimal(0);

		public int getMin() {
			return min;
		}

		public void setMin(int min) {
			this.min = min;
		}

		public int getMax() {
			return max;
		}

		public void setMax(int max) {
			this.max = max;
		}

		public BigDecimal getAmount() {
			return amount;
		}

		public void setAmount(BigDecimal amount) {
			this.amount = amount;
		}

		@Override
		public int compareTo(RewardsRules rules) {
			if (this.min > rules.min) {
				return 1;
			}
			return -1;
		}
	}
}