package com.cku.service;


import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cku.core.ExecResultModel;
import com.cku.dao.CkuDogMapper;
import com.cku.dao.CkuTabGradeDdzMapper;
import com.cku.dao.CkuTabGradeMapper;
import com.cku.model.CkuDog;
import com.cku.model.CkuDogLoginType;
import com.cku.model.CkuDogMessageForLoginType;
import com.cku.model.CkuDogScoreModel;
import com.cku.model.CkuTabGrade;
import com.cku.model.CkuTabGradeDdz;
import com.cku.util.PageBean;
import com.cku.util.PedigreeCertifiedCodeUtil;
import com.google.common.collect.ImmutableSet;
/**
 *
 * <p>Title:DogRelatedServiceImpl </p>
 * <p>Description: 犬类相关服务层</p>
 * <p>Company: </p>
 * @author zhuoHeng
 * @date 2016年3月16日 下午4:40:18
 */
@Service("dogRelatedServiceImpl")
public class DogRelatedServiceImpl{

	@Autowired
	public CkuDogMapper ckuDogMapper;

	@Autowired
	public PublicService publicService;
	@Autowired
	public CkuTabGradeMapper ckuTabGradeMapper;

	@Autowired
	public CkuTabGradeDdzMapper ckuTabGradeDdzMapper;

	private static final Set<String> DOG_BREED_SET = ImmutableSet.of("292", "15C");


	/**
	 *
	 * @Description：根据cku证书号/犬只芯片号获取犬信息（带校验）
	 * @author: zhuoHeng
	 * @version: 2016年3月16日 下午5:07:59
	 * @throws ParseException
	 */
	@SuppressWarnings("all")
	public String getEventList(String pedigreeNum,String dogId,String showNums) throws ParseException{

		ExecResultModel<CkuDog> resultModel = new ExecResultModel<CkuDog>();
		Map<String,String> map = publicService.dogStatus(pedigreeNum, dogId,showNums);
		String message ="";
		//犬只资格验证（需满足cku血统、失格次数<3、犬龄>3个月、犬只代数>=2）
		if("yes".equals(map.get("cku"))&&"yes".equals(map.get("disqualification"))&&
				"yes".equals(map.get("ageStatus"))&&"yes".equals(map.get("dogGenerations"))
				&&"yes".equals(map.get("rightVip"))
				&&"yes".equals(map.get("banned"))
				&&"no".equals(map.get("repeated"))
				&&"yes".equals(map.get("status"))){

			List<CkuDog> eventIntroduce = ckuDogMapper.getMatchCost(pedigreeNum,dogId);
			eventIntroduce.get(0).setAge(map.get("age"));
			//查询犬只是否存在比赛成绩
			eventIntroduce.get(0)
			.setShowResult(eventIntroduce.get(0).getShowResult() == null?"":eventIntroduce.get(0).getShowResult());
			//查询犬只是否存在有效的冠军登录记录
			int countChampionLogin = ckuDogMapper.getChampionLogin(pedigreeNum);
			if(countChampionLogin > 0) {
				eventIntroduce.get(0).setChampionLogin(true);
			} else {
				eventIntroduce.get(0).setChampionLogin(false);
			}
			resultModel.setItems(eventIntroduce);
			resultModel.setRc(0);
			resultModel.setMsg("返回正常结果");
			resultModel.setTotal((long)eventIntroduce.size());
		}else{
			if("yes".equals(map.get("dogBusinessBan"))){
				resultModel.setRc(109);
				message = "该犬为禁止参赛状态，无法办理该业务";
			}else if("no".equals(map.get("cku"))){
				resultModel.setRc(100);
				message = "犬只血统证书不合格";
			}else if("no".equals(map.get("disqualification"))){
				resultModel.setRc(101);
				message = "犬只失格次数大于3次";
			}else if("no".equals(map.get("ageStatus"))){
				resultModel.setRc(102);
				message = "犬只年龄不足3个月";
			}else if("no".equals(map.get("dogGenerations"))){
				resultModel.setRc(103);
				message = "犬只参赛仅限2代及以上血统犬只报名";
			}else if("no".equals(map.get("rightVip"))){
				resultModel.setRc(105);
				message="犬主人会员无效";
			}else if("no".equals(map.get("banned"))){
				resultModel.setRc(106);
				message="犬主人在禁赛期内";
			}else if("yes".equals(map.get("repeated"))){
				resultModel.setRc(107);
				message="重复报名";
			}else if("no".equals(map.get("status"))){
				resultModel.setRc(108);
				message="犬只状态不正常";
			}else {
				resultModel.setRc(104);
				message = "无相应结果";
			}
			resultModel.setItems(new ArrayList<CkuDog>());
			resultModel.setMsg(message);
			resultModel.setTotal((long)0);
		}
		return resultModel.getToJson();
	}
	/**
	 *
	 * @Description：查询犬只家族信息
	 * @author: zhuoHeng
	 * @version: 2016年3月24日 上午11:13:39
	 */
	@SuppressWarnings("all")
	public Map getDogFamily(String pedigreeNum,String dogId){

		Map<String,Map<String,String>> newMap = new HashMap<String, Map<String,String>>();
		ExecResultModel<Map> resultModel = new ExecResultModel<Map>();
		List<Map> list = new ArrayList<Map>();
		Map<String,String> map1 = CkuDog(pedigreeNum.toUpperCase());

		Map<String,String> map21 = CkuDog(map1.get("fuOld"));
		Map<String,String> map22 = CkuDog(map1.get("muOld"));

		Map<String,String> map211 = CkuDog(map21.get("fuOld"));
		Map<String,String> map212 = CkuDog(map21.get("muOld"));
		Map<String,String> map221 = CkuDog(map22.get("fuOld"));
		Map<String,String> map222 = CkuDog(map22.get("muOld"));

		newMap.put("fdai", map1);
		newMap.put("sdaif", map21);
		newMap.put("sdaim", map22);
		newMap.put("tdaiff", map211);
		newMap.put("tdaifm", map212);
		newMap.put("tdaimf", map221);
		newMap.put("tdaimm", map222);


		return newMap;
	}
	/**
	 *
	 * @Description：查询犬只家族信息支持方法
	 * @author: zhuoHeng
	 * @version: 2016年3月24日 下午3:29:50
	 */
	@SuppressWarnings("all")
	public Map CkuDog(String zicku){
		Map<String,String> map = new HashMap<String, String>();
		if(StringUtils.isBlank(zicku)) {
			map.put("fu", "");
			map.put("fuOld", "");
			map.put("fuName","");
			
			map.put("mu","");
			map.put("muOld","");
			map.put("muName","");
			return map;
		}
	
		List<CkuDog> eventIntroduce = "".equals(zicku)?new ArrayList<CkuDog>():ckuDogMapper.getMatchCost(zicku,null);
		if(eventIntroduce.size()!=0&&StringUtils.isNotBlank(eventIntroduce.get(0).getfPedigreeNum())){
			String f_ckuNum = eventIntroduce.size()==0?"":eventIntroduce.get(0).getfPedigreeNum();//父cku
			List<CkuDog> ListF = "".equals(f_ckuNum)?new ArrayList<CkuDog>():ckuDogMapper.getMatchCost(f_ckuNum,null);
			map.put("fu", f_ckuNum ==null?"":PedigreeCertifiedCodeUtil.getCode(f_ckuNum));
			map.put("fuOld", f_ckuNum ==null?"":f_ckuNum);
			map.put("fuName", ListF.size()==0?"":ListF.get(0).getDogEgName()==null?"":ListF.get(0).getDogEgName());
		}else{
			map.put("fu", "");
			map.put("fuName","");
		}

		if(eventIntroduce.size()!=0&&StringUtils.isNotBlank(eventIntroduce.get(0).getmPedigreeNum())){
			String m_ckuNum = eventIntroduce.size()==0?"":eventIntroduce.get(0).getmPedigreeNum();//母cku
			List<CkuDog> ListM = "".equals(m_ckuNum)?new ArrayList<CkuDog>():ckuDogMapper.getMatchCost(m_ckuNum,null);
			map.put("mu", m_ckuNum==null?"":PedigreeCertifiedCodeUtil.getCode(m_ckuNum));
			map.put("muOld", m_ckuNum==null?"":m_ckuNum);
			map.put("muName", ListM.size()==0?"":ListM.get(0).getDogEgName()==null?"":ListM.get(0).getDogEgName());
		}else{
			map.put("mu","");
			map.put("muName","");
		}

		return map;

	}
	/**
	 *
	 * @Description：根据cku证书号/犬只芯片号获取犬信息（无校验）
	 * @author: zhuoHeng
	 * @version: 2016年3月24日 下午3:30:23
	 */
	public String getDogMessageForIndex(String pedigreeNum,String dogId){
		ExecResultModel<CkuDog> resultModel = new ExecResultModel<CkuDog>();
		if(StringUtils.isBlank(pedigreeNum)&&StringUtils.isBlank(dogId)) {
			resultModel.setRc(-1);
			resultModel.setMsg("证书号或芯片号必填！");
			return resultModel.getToJson();
		}
		
		List<CkuDog> eventIntroduce = ckuDogMapper.getMatchCost(pedigreeNum,dogId);
	
		resultModel.setRc(0);
		resultModel.setMsg("");
		resultModel.setTotal((long)eventIntroduce.size());
		//犬只状态为已删除、未审核、已注销、已冻结的提示
		for(CkuDog ckuDog:eventIntroduce){
			String dogState = ckuDog.getDelTag();
			if ("1".equals(dogState)
					||"2".equals(dogState)
					||"3".equals(dogState)
					||"4".equals(dogState)) {
				resultModel.setRc(-1);
				resultModel.setMsg("此证书状态异常，详情请致电宠爱王国客服热线。400-660-7000");
				break;
			}
			ckuDog.setPedigreeNum(PedigreeCertifiedCodeUtil.getCode(ckuDog.getPedigreeNum()));
			ckuDog.setOverseasRegCertifi(PedigreeCertifiedCodeUtil.getCode(ckuDog.getOverseasRegCertifi()));
		}
		resultModel.setItems(eventIntroduce);
		return resultModel.getToJson();
	}
	/**
	 *
	 * @Description：根据cku证书号查询犬只（全犬种）比赛结果
	 * @author: zhuoHeng
	 * @version: 2016年3月24日 下午5:17:33
	 */
	public String getDogGradeList(String pedigreeNum,String charTime){

		ExecResultModel<CkuTabGrade> resultModel = new ExecResultModel<CkuTabGrade>();
		//犬种为杜高直接返回空
		if(StringUtils.isNotBlank(pedigreeNum)){
			String[] array = pedigreeNum.split("-");
			if(array.length>=2&&array[1].length()>=3){
				if(DOG_BREED_SET.contains(array[1].substring(0, 3))){
					resultModel.setItems(new ArrayList<CkuTabGrade>());
					resultModel.setRc(0);
					resultModel.setMsg("");
					resultModel.setTotal(0L);
					return resultModel.getToJson();
				}
			}
		}
		//若客户端未传递“时间”参数，查询
		if("".equals(charTime)||charTime==null){
			List<CkuTabGrade> getDogGradeMonth = ckuTabGradeMapper.getDogGradeMonth(pedigreeNum);
			//若所输入CKU证书号犬只存在全犬种比赛成绩
			if(getDogGradeMonth.size()>0){
				//将集合中的第一个对象的赛事结束时间取出，赋值给“时间”参数（默认进入全犬种比赛成绩界面返回全犬种数据）
				charTime = getDogGradeMonth.get(0).getGradeMonth();
			}
		}
		List<CkuTabGrade> eventIntroduce = ckuTabGradeMapper.getDogGradeList(pedigreeNum,charTime);
		if(eventIntroduce.size()>0){
			resultModel.setItems(eventIntroduce);
			resultModel.setRc(0);
			resultModel.setMsg("");
			resultModel.setTotal((long)eventIntroduce.size());
		}else{
			resultModel.setItems(new ArrayList<CkuTabGrade>());
			resultModel.setRc(0);
			resultModel.setMsg("");
			resultModel.setTotal((long)eventIntroduce.size());
		}
		return resultModel.getToJson();
	}
	/**
	 *
	 * @Description：根据cku证书号查询犬只（单独展）比赛结果
	 * @author: zhuoHeng
	 * @version: 2016年3月24日 下午6:10:02
	 */
	public String getDogGradeDdzList(String pedigreeNum,String charTime){

		ExecResultModel<CkuTabGradeDdz> resultModel = new ExecResultModel<CkuTabGradeDdz>();
		//犬种为杜高直接返回空
		if(StringUtils.isNotBlank(pedigreeNum)){
			String[] array = pedigreeNum.split("-");
			if(array.length>=2&&array[1].length()>=3){
				if(DOG_BREED_SET.contains(array[1].substring(0, 3))){
					resultModel.setItems(new ArrayList<CkuTabGradeDdz>());
					resultModel.setRc(0);
					resultModel.setMsg("");
					resultModel.setTotal(0L);
					return resultModel.getToJson();
				}
			}
		}
		//若客户端未传递“时间”参数，查询
		if("".equals(charTime)||charTime==null){
			List<CkuTabGradeDdz> getDogGradeMonth = ckuTabGradeDdzMapper.getDogGradeDdzMonth(pedigreeNum);
			//若所输入CKU证书号犬只存在全犬种比赛成绩
			if(getDogGradeMonth.size()>0){
				//将集合中的第一个对象的赛事结束时间取出，赋值给“时间”参数（默认进入全犬种比赛成绩界面返回全犬种数据）
				charTime = getDogGradeMonth.get(0).getGradeMonth();
			}
		}
		List<CkuTabGradeDdz> eventIntroduce = ckuTabGradeDdzMapper.getDogGradeDdzList(pedigreeNum,charTime);
		if(eventIntroduce.size()>0){
			resultModel.setItems(eventIntroduce);
			resultModel.setRc(0);
			resultModel.setMsg("");
			resultModel.setTotal((long)eventIntroduce.size());
		}else{
			resultModel.setItems(new ArrayList<CkuTabGradeDdz>());
			resultModel.setRc(0);
			resultModel.setMsg("");
			resultModel.setTotal((long)eventIntroduce.size());
		}
		return resultModel.getToJson();
	}
	/**
	 *
	 * @Description：冠军登录犬只信息查询（犬只冠军登录申请资格校验）
	 * @author: zhuoHeng
	 * @version: 2016年4月6日 上午9:53:15
	 * @param pb
	 * @throws ParseException
	 */
	@SuppressWarnings("all")
	public String getDogMessageByLoginUser(String userNum,String pedigreeNum) throws ParseException{
		ExecResultModel<CkuDogMessageForLoginType> resultModel = new ExecResultModel<CkuDogMessageForLoginType>();
		List<CkuDogMessageForLoginType> eventIntroduce = ckuDogMapper.getMatchCostByPedigreeNum(userNum,pedigreeNum);
		String message ="";
		if(eventIntroduce.size()>0){
			Map<String,String> map = publicService.dogStatus(eventIntroduce.get(0).getPedigreeNum(), null,null);
			CkuDogScoreModel ckuDogScoreModel = ckuTabGradeMapper.getDogScore(pedigreeNum);
			List<CkuDogLoginType> loginTypeList = new ArrayList<CkuDogLoginType>();
			int CC = ckuDogScoreModel.getCC();
			int JCC = ckuDogScoreModel.getJCC();
			int RCC = ckuDogScoreModel.getRCC();
			int BOB = ckuDogScoreModel.getBOB();
			int BOW = ckuDogScoreModel.getBOW();
			int BIS = ckuDogScoreModel.getBIS();
			int BIG = ckuDogScoreModel.getBIG();
			int BOS = ckuDogScoreModel.getBOS();
			int CACIB = ckuDogScoreModel.getCACIB();
			//*****************世界冠军登录*********
			CkuDogLoginType ckuDogLoginType = new CkuDogLoginType();
			ckuDogLoginType.setLoginType("世界冠军登录");
			ckuDogLoginType.setFlag(false);
			if("no".equals(map.get("dateStatus"))){//犬龄资格校验
				resultModel.setRc(107);
				message = "犬龄小于15个月";
				ckuDogLoginType.setFlag(false);
			}else if("no".equals(map.get("payDnaStatus"))){//dna存档校验
				resultModel.setRc(108);
				message = "dna未存档";
				ckuDogLoginType.setFlag(false);
			}else if("no".equals(map.get("dogGenerationsStatus"))){//犬只代数校验
				resultModel.setRc(109);
				message = "犬龄代数未到3代";
			}else if(CACIB>3){//累计获得4张以上CACIB卡
				ckuDogLoginType.setFlag(false);
			} else{
				//符合世界冠军登录的信息存储
				ckuDogLoginType.setFlag(true);
			}
			//*********************************
			//*****************铜质登录***********
			CkuDogLoginType ckuDogLoginType1 = new CkuDogLoginType();
			ckuDogLoginType1.setLoginType("铜质冠军登录");
			ckuDogLoginType1.setFlag(false);
			if("no".equals(map.get("dateStatus"))){//犬龄资格校验
				message = "犬龄小于15个月";
				ckuDogLoginType1.setFlag(false);
			}else if("no".equals(map.get("payDnaStatus"))){//dna存档校验
				message = "dna未存档";
				ckuDogLoginType1.setFlag(false);
			}else if((CC>0)&&(CC+JCC>3)&&(CC+JCC+RCC/2)>7&&(BOB>0||BOS>0||BOW>0)){
				ckuDogLoginType1.setFlag(true);
			}
			//*********************************
			//*****************银质登录***********
			CkuDogLoginType ckuDogLoginType2 = new CkuDogLoginType();
			ckuDogLoginType2.setLoginType("银质冠军登录");
			ckuDogLoginType2.setFlag(false);
			if("no".equals(map.get("dateStatus"))){//犬龄资格校验
				message = "犬龄小于15个月";
				ckuDogLoginType2.setFlag(false);
			}else if("no".equals(map.get("payDnaStatus"))){//dna存档校验
				message = "dna未存档";
				ckuDogLoginType2.setFlag(false);
			}else if((CC>0)&&(CC+JCC>7)&&(CC+JCC+RCC/2)>11&&(BOB>1)){
				ckuDogLoginType2.setFlag(true);
			}
			//*********************************
			//*****************金质登录***********
			CkuDogLoginType ckuDogLoginType3 = new CkuDogLoginType();
			ckuDogLoginType3.setLoginType("金质冠军登录");
			ckuDogLoginType3.setFlag(false);
			if("no".equals(map.get("dateStatus"))){//犬龄资格校验
				message = "犬龄小于15个月";
				ckuDogLoginType3.setFlag(false);
			}else if("no".equals(map.get("payDnaStatus"))){//dna存档校验
				message = "dna未存档";
				ckuDogLoginType3.setFlag(false);
			}else if((CC>0)&&(CC+JCC>11)&&(CC+JCC+RCC/2)>19&&(BIG>1)){
				ckuDogLoginType3.setFlag(true);
			}
			//*********************************
			//*****************超级登录***********
			CkuDogLoginType ckuDogLoginType4 = new CkuDogLoginType();
			ckuDogLoginType4.setLoginType("超级冠军登录");
			ckuDogLoginType4.setFlag(false);
			if("no".equals(map.get("dateStatus"))){//犬龄资格校验
				message = "犬龄小于15个月";
				ckuDogLoginType4.setFlag(false);
			}else if("no".equals(map.get("payDnaStatus"))){//dna存档校验
				message = "dna未存档";
				ckuDogLoginType4.setFlag(false);
			}else if((CC>0)&&(CC+JCC>11)&&(CC+JCC+RCC/2)>19&&(BIG>1)){
				ckuDogLoginType4.setFlag(true);
			}
			//*********************************

			loginTypeList.add(ckuDogLoginType);
			loginTypeList.add(ckuDogLoginType1);
			loginTypeList.add(ckuDogLoginType2);
			loginTypeList.add(ckuDogLoginType3);
			loginTypeList.add(ckuDogLoginType4);
			eventIntroduce.get(0).setLoginTypeList(loginTypeList);
			resultModel.setItems(eventIntroduce);
			resultModel.setRc(0);
			resultModel.setMsg("");
		}else{
			resultModel.setRc(101);
			resultModel.setMsg("该犬只不在登录会员名下");
		}
		return resultModel.getToJson();
	}
	/**
	 *
	 * @Description：获取登录会员的CKU犬只列表
	 * @author: zhuoHeng
	 * @version: 2016年4月6日 下午6:24:24
	 * @param pb
	 */
	public String getDogListByLoginUser(String userNum, PageBean pb){
		ExecResultModel<CkuDog> resultModel = new ExecResultModel<CkuDog>();
		List<CkuDog> eventIntroduce = ckuDogMapper.getDogListByLoginUser(userNum,pb.get_limit(),pb.get_start());
		long count=ckuDogMapper.getCountByLoginUser(userNum);
		resultModel.setItems(eventIntroduce);
		resultModel.setRc(0);
		resultModel.setMsg("");
		resultModel.setTotal(count);
		return resultModel.getToJson();
	}
}
