package com.cku.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

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

import com.cku.dao.CkuDogMapper;
import com.cku.dao.CkuMatchSignMapper;
import com.cku.dao.CkuTabGradeMapper;
import com.cku.dao.CkuUserMapper;
import com.cku.dao.EventRelatedMapper;
import com.cku.dao.PublicMapper;
import com.cku.model.CkuDog;
import com.cku.model.CkuMatchSign;
import com.cku.model.CkuUser;
import com.cku.model.EventRelatedModel;
import com.cku.model.PublicModel;

/**
 * 
 * <p>Title:PublicService </p>
 * <p>Description: 公用服务</p>
 * <p>Company: </p> 
 * @author zhuoHeng
 * @date 2016年3月17日 下午12:52:45
 */
@Service("publicService")
public class PublicService {
	
	@Autowired
	public CkuUserMapper ckuUserMapper;
	@Autowired
	public CkuDogMapper ckuDogMapper;
	@Autowired
	public PublicMapper publicMapper;
	@Autowired
	public CkuMatchSignMapper ckuMatchSignMapper;
	@Autowired
	public CkuTabGradeMapper ckuTabGradeMapper;
	@Autowired
	public EventRelatedMapper eventRelatedMapper;
	@Autowired
	public DogRelatedServiceImpl dogRelatedServiceImpl;

	/**
	 * 
	 * @Description：根据会员号对会员资格校验（当前时间在会员资格到期时间前，会员有效。返回true）
	 * @author: zhuoHeng
	 * @version: 2016年3月17日 下午1:10:56
	 */
	public boolean memberStatus(String idNum){
		
		List<CkuUser> memberInfo = ckuUserMapper.getUserMessage(idNum);
		if(memberInfo.size()>0){
			//系统时间
			Date date = new Date();
			//美容师会员没有过期，但是会员过期的，默认算是基础会员，享有基础会员的基本功能
			if(memberInfo.size()>0 && memberInfo.get(0).getGroomerEndDate()!= null && memberInfo.get(0).getGroomerEndDate().getTime()>date.getTime()){
				return true;
			}
			//判断会员截止时间是否为空
			if("".equals(memberInfo.get(0).getMemberDeadlineTime())||memberInfo.get(0).getMemberDeadlineTime()==null){
				return false;
			}
			//会员资格到期时间
			Date memberDeadTime = memberInfo.get(0).getMemberDeadlineTime();
			//当前时间在会员资格到期时间前，返回true
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			boolean flag = date.before(memberDeadTime) || format.format(date).equals(format.format(memberDeadTime));
			
			if(flag){
				return true;
			} else {
				return false;
			}
		}else {
			return false;
		}
	}
	
	public boolean getMemberStatus(String idNum){
        
        List<CkuUser> memberInfo = ckuUserMapper.getUserMessage(idNum);
        if(memberInfo.size()>0){
            //系统时间
            Date date = new Date();
            //判断会员截止时间是否为空
            if("".equals(memberInfo.get(0).getMemberDeadlineTime())||memberInfo.get(0).getMemberDeadlineTime()==null){
                return true;
            }
            //会员资格到期时间
            Date memberDeadTime = memberInfo.get(0).getMemberDeadlineTime();
            //当前时间在会员资格到期时间前，返回true
            boolean flag = (date.before(memberDeadTime)&&"专业".equals(memberInfo.get(0).getMemberType()));
            
            if(flag){
                return true;
            } else {
                return false;
            }
        }else {
            return false;
        }
    }
	/**
	 * 
	 * @Description：查询会员是否在禁赛期内（禁赛为true）
	 * @author: zhuoHeng
	 * @version: 2016年3月17日 下午2:09:08
	 */
	public boolean  suspendStatus(String idNum){
		List<CkuUser> memberInfo = ckuUserMapper.getUserMessage(idNum);
		if(memberInfo.size()>0){
			//系统时间
			Date date = new Date();
			//判断会员禁赛时间是否为空,为空不在禁赛期
			if("".equals(memberInfo.get(0).getSsJstime())||memberInfo.get(0).getSsJstime()==null){
				return true;
			}
			//禁赛时间
			Date suspendTime = memberInfo.get(0).getSsJstime();
			//当前时间在禁赛期前，返回true
			boolean flag = date.before(suspendTime);
			
			if(flag){
				return false;
			} else {
				return true;
			}
		} else {
			return false;
		}
		
	}
	/**
	 * 已改
	 * @Description：犬只资格验证（包含：是否存在有效cku血统证书号cku、报名犬只失格次数是否小于3次disqualification
	 * 报名犬只年龄是否大于3个月ageStatus、犬只代数是否大于0 dogGenerations）
	 * @author: zhuoHeng
	 * @version: 2016年3月17日 下午2:57:55
	 * @throws ParseException 
	 */
	@SuppressWarnings("all")
	public Map dogStatus(String pedigreeNum,String dogId,String showNums) throws ParseException{
		List<CkuDog> dogMessage = ckuDogMapper.getMatchCost(pedigreeNum,dogId);
		//CkuDogScoreModel ckuDogScoreModel = ckuTabGradeMapper.getDogScore(pedigreeNum);
		Map<String, String> map = new HashMap<String,String>();
		if(dogMessage.size()>0){
			//查询是否报名了赛事
			List<CkuMatchSign> ckuMatchSign = ckuMatchSignMapper.getSignByStudbookNum(showNums.substring(0, 7),dogMessage.get(0).getPedigreeNum());
			if(ckuMatchSign.size()>0){
				map.put("repeated", "yes");
			}else{
				map.put("repeated", "no");
			}
			
			boolean bl = false;
			if(dogMessage.get(0).getMemberNum()!=null){
				bl=memberStatus(dogMessage.get(0).getMemberNum());
			}
			//是否有效会员
			if(bl){
				map.put("rightVip", "yes");
			}else{
				map.put("rightVip", "no");
			}
			boolean suspendFlag = false;
			if(dogMessage.get(0).getMemberNum()!=null){
				suspendFlag = suspendStatus(dogMessage.get(0).getMemberNum());
			}
			//是否禁赛期
			if(suspendFlag){
				map.put("banned", "yes");
			}else{
				map.put("banned", "no");
			}
			boolean flag = dogMessage.get(0).getPedigreeNum().contains("CKU");
			//犬只状态是否正常
			if("0".equals(dogMessage.get(0).getDelTag())||"5".equals(dogMessage.get(0).getDelTag())){
				map.put("status", "yes");
			}else{
				map.put("status", "no");
			}
			//证书号是否是CKU开头校验
			if(flag){
				map.put("cku", "yes");
			} else {
				map.put("cku", "no");
			}
			//TODO 失格次数校验
			map.put("disqualification", "yes");
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String date ="";
			if(showNums!=null&&!"".equals(showNums)){
				String[] strs = showNums.split(",");
				String strN ="";
				for (int i = 0; i < strs.length; i++) {
					strN+="'"+strs[i]+"',";
				}
				strN = strN.substring(0, strN.length()-1);
				EventRelatedModel eventRelatedModel = eventRelatedMapper.getSpecificEventByShowNums(strN);
				date = df.format(eventRelatedModel.getStarting_data());
			}else{
				date = df.format(new Date());
			}
			String dogBirthday = df.format(dogMessage.get(0).getDogBirthday()==null?new Date():dogMessage.get(0).getDogBirthday());
			//List<PublicModel> difference = publicMapper.getTimeDifference(date, dogBirthday);
			int monthAge = getMonthAge(df.parse(date), df.parse(dogBirthday));
			map.put("age", String.valueOf(monthAge));
			//犬龄资格校验
			if(monthAge>2){
				map.put("ageStatus", "yes");
			} else {
				map.put("ageStatus", "no");
			}
			if("1".equals(dogMessage.get(0).getBusinessBan())){
				map.put("dogBusinessBan", "yes");
			} else {
				map.put("dogBusinessBan", "no");
			}
			//犬只代数校验
			int i = 0;
			int fDogGeneration = getDogGeneration("fu", dogMessage.get(0).getPedigreeNum(), 0,0);
            int mDogGeneration = getDogGeneration("mu", dogMessage.get(0).getPedigreeNum(), 0,0);
            if(fDogGeneration>mDogGeneration){
                i = mDogGeneration;
            } else {
            	i = fDogGeneration;
            }
            System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"+mDogGeneration+":"+fDogGeneration);
			if(i>=2){
				map.put("dogGenerations", "yes");
			} else {
				map.put("dogGenerations", "no");
			}
			//犬只月龄大于15个月
			if(monthAge>14){
				map.put("dateStatus", "yes");
			} else {
				map.put("dateStatus", "no");
			}
			//DNA必须存档(dog pay_DNA=1)
			if(dogMessage.get(0).getPayDna()!=null && "1".equals(dogMessage.get(0).getPayDna())){
				map.put("payDnaStatus", "yes");
			}else{
				map.put("payDnaStatus", "no");
			}
			//犬只代数3代以上
			if(dogMessage.get(0).getDogGenertions()!=null && dogMessage.get(0).getDogGenertions()>2){
				map.put("dogGenerationsStatus", "yes");
			} else {
				map.put("dogGenerationsStatus", "no");
			}
			
		}
		return map;
	}
	/**
	 * 已改
	 * @Description：查询主赛事报名犬只是否达到上限、是否过了报名截止日期
	 * @author: zhuoHeng
	 * @version: 2016年3月21日 下午5:22:12
	 */
	public Map enrollStatus(String showNum){
		Map<String, Integer> map = new HashMap<String,Integer>();
		List<CkuMatchSign> list = ckuMatchSignMapper.getTopDog(showNum);
		int listSize = list.size();
		if(listSize>0){
			map.put("enrollNumber", listSize);
		}else {
			map.put("enrollNumber", 0);
		}
		return map;
	}
	
	private int getMonthAge(Date date, Date birthdate) {
		Calendar dateCalendar = Calendar.getInstance();
		Calendar birthdateCalendar = Calendar.getInstance();
		dateCalendar.setTime(date);
		birthdateCalendar.setTime(birthdate);
		int monthAge = dateCalendar.get(Calendar.MONTH) - birthdateCalendar.get(Calendar.MONTH);
		if (dateCalendar.get(Calendar.YEAR) != birthdateCalendar.get(Calendar.YEAR)) {
			monthAge = (dateCalendar.get(Calendar.YEAR) - birthdateCalendar.get(Calendar.YEAR)) * 12 + monthAge;
		}
		birthdateCalendar.add(Calendar.MONTH, monthAge);
		if (birthdateCalendar.getTime().after(dateCalendar.getTime())) {
			monthAge = monthAge - 1;
		}
		return monthAge;
	}
	
	
	public int getDogGeneration(String dogGender,String pedigreeCertifiedCode,int generation,int num){
        
        String pedigreeCertified = "";
        int i = num;
        Map<String,String> map = new HashMap<String, String>();
        map = dogRelatedServiceImpl.CkuDog(pedigreeCertifiedCode);
        if(!"".equals(map.get("fu"))&&!"-".equals(map.get("fu"))&&
                !"".equals(map.get("mu"))&&!"-".equals(map.get("mu"))){
            generation = generation+1;
            i++;
            if(i>9){
            	return generation;
            }
            pedigreeCertified = map.get(dogGender);
        } else {
            return generation;
        }
        return getDogGeneration(dogGender,pedigreeCertified,generation,i);
    }
}
