package com.iamberry.answer.web.questionnaire;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.logging.Logger;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import sun.misc.BASE64Decoder;

import com.iamberry.answer.face.questionnaire.QuestionnaireService;
import com.iamberry.answer.web.utils.AnswerUtils;
import com.iamberry.app.tool.des.MD5;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.questionnaire.AnswerReuslt;
import com.iamberry.wechat.core.entity.questionnaire.BMIReference;
import com.iamberry.wechat.core.entity.questionnaire.QuestionOptionDto;
import com.iamberry.wechat.core.entity.questionnaire.QuestionnaireAnswer;
import com.iamberry.wechat.core.entity.questionnaire.QuestionnaireAnswerDetailed;
import com.iamberry.wechat.core.entity.questionnaire.QuestionnaireBMI;
import com.iamberry.wechat.core.entity.questionnaire.QuestionnaireOption;
import com.iamberry.wechat.core.entity.questionnaire.QuestionnaireQuestion;
import com.iamberry.wechat.core.entity.questionnaire.QuestionnaireQuestionOptionDto;
import com.iamberry.wechat.file.FileType;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.StrUtils;
import com.iamberry.wechat.tools.loadResultUtil;
/**
 * 处理，营养自测前段接口
 * @author lc
 */
@Controller
@RequestMapping("/answer/questionnaire")
public class QuestionnaireHandler {
	
	@Autowired
	private QuestionnaireService questionnaireService;	//营养自测前台接口类
	
	@Autowired
	private AnswerUtils answerUtils;	//用户信息工具类
	
	private MD5 md5 = new MD5("ANSWERID");
	
	private Random random = new Random();
	
	public static String defautImagePath = "images/";			//上传的答题人的宝宝图片路径
	
	@SuppressWarnings("restriction")
	private BASE64Decoder decoder = new BASE64Decoder();  

	public static Map<Integer,Integer> type = new HashMap<Integer,Integer>(); //题目类型，总分
	public static Map<String,AnswerReuslt> result = new HashMap<String,AnswerReuslt>(); //结果tips
	public static Map<String,String> optiondesc = new HashMap<String,String>(); //选项教书
	
	public static Map<String,Double> babytouwei = new HashMap<String,Double>(); //宝宝头围
	
	static{
		//总分计算！
		type.put(1, 0); //营养
		type.put(2, 0); //发育
		type.put(3, 0); //健康
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();    
        ServletContext servletContext = webApplicationContext.getServletContext(); 
        String realPath =  servletContext.getContextPath();
		String imgFilePath = realPath +"/"+ defautImagePath;
		//男
		result.put("1_1", new AnswerReuslt("蜘蛛侠宝宝","超萌哒！宝宝营养吸收能力好强哦，活泼好动，努力长大中，将来好好保护妈妈哒！",imgFilePath+"zhizhu.png")); //营养
		result.put("1_2", new AnswerReuslt("钢铁侠宝宝","哇！给宝宝的强大发育点32个赞，精力充沛小达人，将来注定成为高富帅的节奏！",imgFilePath+"gangtie.png"));//发育
		result.put("1_3", new AnswerReuslt("超人宝宝","Super Baby非你莫属了！宝宝如小超人般，全方位健康指数爆棚，一定会蜕变为顶天立地的小男子汉哟！",imgFilePath+"icon-superman.png"));//健康
		//女
		result.put("2_1", new AnswerReuslt("白雪公主","营养补充得非常棒哦，小白雪公主宝宝果然是小美人儿，将来一定是妈妈的贴心小棉袄。",imgFilePath+"baixue.png"));//营养
		result.put("2_2", new AnswerReuslt("美人鱼公主","宝宝的科学发育指数已经秒杀大部分宝宝啦，美丽成长，一枚闪亮女神冉冉诞生中哦！",imgFilePath+"meirenyu.png"));//发育
		result.put("2_3", new AnswerReuslt("艾莎公主","妈妈快把育儿配方交出来！宝宝的健康指数已经美破天际，又拥有纯洁心灵，这以后是要祸害多少蓝孩纸啊！",imgFilePath+"bingxue.png"));//健康
		
		//选项描述
		Properties prop = new Properties();
		try {
			prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("optionDes.properties"));
			Enumeration enum1 = prop.propertyNames();//得到配置文件的名字
			while(enum1.hasMoreElements()) {
	              String strKey = (String) enum1.nextElement();
	              String strValue = prop.getProperty(strKey);
	              optiondesc.put(strKey, strValue); //放入
			}
		} catch (IOException e) {
			System.out.println("加载失败----------");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// 男
		babytouwei.put("3_1_b", 32.00);
		babytouwei.put("3_1_e", 41.25);
		babytouwei.put("6_1_b", 42.3);
		babytouwei.put("6_1_e", 44.32);
		babytouwei.put("12_1_b", 45.0);
		babytouwei.put("12_1_e", 46.8);
		babytouwei.put("15_1_b", 46.5);
		babytouwei.put("15_1_e", 47.4);
		babytouwei.put("18_1_b", 46.8);
		babytouwei.put("18_1_e", 47.8);
		babytouwei.put("24_1_b", 47.4);
		babytouwei.put("24_1_e", 48.8);
		babytouwei.put("30_1_b", 48.2);
		babytouwei.put("30_1_e", 49.0);
		babytouwei.put("36_1_b", 48.8);
		babytouwei.put("36_1_e", 49.9);
		babytouwei.put("48_1_b", 49.58);
		babytouwei.put("48_1_e", 51.0);
		babytouwei.put("60_1_b", 49.93);
		babytouwei.put("60_1_e", 51.0);
		//女
		babytouwei.put("3_2_b", 33.05);
		babytouwei.put("3_2_e", 39.90);
		babytouwei.put("6_2_b", 41.2);
		babytouwei.put("6_2_e", 43.20);
		babytouwei.put("12_2_b", 43.7);
		babytouwei.put("12_2_e", 45.8);
		babytouwei.put("15_2_b", 45.4);
		babytouwei.put("15_2_e", 46.2);
		babytouwei.put("18_2_b", 45.8);
		babytouwei.put("18_2_e", 46.7);
		babytouwei.put("24_2_b", 46.2);
		babytouwei.put("24_2_e", 47.7);
		babytouwei.put("30_2_b", 47.2);
		babytouwei.put("30_2_e", 48.0);
		babytouwei.put("36_2_b", 47.7);
		babytouwei.put("36_2_e", 48.3);
		babytouwei.put("48_2_b", 48.33);
		babytouwei.put("48_2_e", 50.0);
		babytouwei.put("60_2_b", 48.33);
		babytouwei.put("60_2_e", 50.5);

	}
	
	/**
	 * 点击，用户的分享，，
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/shareInfo")
	public ResultMsg getGoshareInfoQuestion(HttpServletRequest request,HttpServletResponse response,String answerid){
		
		ResultMsg resultMsg=getSuccessResult();
	
		try {
			answerid = md5.decrypt(answerid).split("-")[0];
		} catch (Exception e) {
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
	    	resultMsg.setMessage(ResultInfo.ERRORINFO+"用户不存在");
	    	resultMsg.setStatus(false);
	    	return resultMsg;
		}
		
		QuestionnaireAnswer answer  = questionnaireService.getQuestionnaireAnswerByid(answerid);	
		
		////System.out.println(answer);
		if(answer== null){
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
	    	resultMsg.setMessage(ResultInfo.ERRORINFO+"用户不存在");
	    	resultMsg.setStatus(false);
	    	return resultMsg;
		}
		if (answer.getAnswerScannedNumber() == null) {
			answer.setAnswerScannedNumber(1);		// 默认值
		}
		//保存，用户浏览次数
		answer.setAnswerScannedNumber(answer.getAnswerScannedNumber()+1);
		
		questionnaireService.updateQuestionnaireAnswer(answer);
		
		int type = answer.getAnswerIsFullmoon();
		AnswerReuslt results = getResult(type,answer.getAnswerBabySex());
		
		//tips获取
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", results.getName());  //白雪公主
		map.put("content", results.getContent()); //简介
		map.put("picture", results.getPicture()); //图片
		
		
		String defaultpic = "http://static.iamberry.com/super_baby/images/touxiang-1.jpg"; //分享的宝宝的默认头像
		if(StringUtils.isNotEmpty(answer.getAnswerBabyPic())){
			defaultpic =  answer.getAnswerBabyPic();	// 宝宝头像
		}
		
		map.put("babyPic", defaultpic);	// 宝宝头像
		
		
		
		map.put("type", String.valueOf(type)); //type 1营养 2 发育 3健康！
		
		// 防止XSS
		map.put("babyName", StringEscapeUtils.escapeHtml4(answer.getAnswerBabyName()));	// 宝宝昵称
		map.put("score", String.valueOf(answer.getAnswerUserScore()));
		resultMsg.setData(map);
		return resultMsg;
	}
	
	/**
	 * 分销首页的跳转
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/indexPage")
	public void  index(HttpServletRequest requestion ,HttpServletResponse response) {
		String url="/WEB-INF/nutrition_test/index.html";
		try {
			requestion.getRequestDispatcher(url).forward(requestion,response);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 分享的跳转
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/share")
	public void  share(HttpServletRequest requestion ,HttpServletResponse response) {
		String url="/WEB-INF/nutrition_test/share.html";
		try {
			requestion.getRequestDispatcher(url).forward(requestion,response);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	//获取，结果
	public AnswerReuslt getResult(int type,int sex){
		return  result.get(sex+"_"+type);
	} 
	
	/**
	 * 获取题目信息
	 * @param request 请求封装
	 * @param paper 试卷实体类
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getQuestionList")
	public ResultMsg getQuestionnaireQuestionList(HttpServletRequest request,Integer month){
		
		ResultMsg resultMsg=getSuccessResult();
		
		//参数验证！！
		if(month == null){ 
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
	    	resultMsg.setMessage(ResultInfo.ERRORINFO);
	    	resultMsg.setStatus(false);
	    	return resultMsg;
		}
		
	
		
		//根据宝宝，获取试卷，，id,,,参数验证
		if(month>60){
			month = 60;
		}
		if(month<1){
			month = 1;
		}
		
		List<QuestionnaireQuestionOptionDto> listquuestionOption=questionnaireService.getQuestionnaireQuestionList( month); //根据试卷获取，题目信息

		List<QuestionOptionDto>  queoptDtolist = new ArrayList<QuestionOptionDto>();
		List<QuestionnaireQuestionOptionDto> newquuestionOption = new ArrayList<QuestionnaireQuestionOptionDto>();
		if(listquuestionOption != null && listquuestionOption.size()>0){
			int quetionid = listquuestionOption.get(0).getQuestionId() ;
			
			//格式，
			for (int i = 0; i < listquuestionOption.size(); i++) {
				QuestionnaireQuestionOptionDto questionoptiondto = listquuestionOption.get(i);
				
				int otherquetionid = questionoptiondto.getQuestionId();
				
				if(quetionid == otherquetionid){ // id, 是否一样，一样，表示一个题目，然后不同选项，，这里拼凑选项！
					QuestionOptionDto dto = new QuestionOptionDto();
					dto.setOptionId(questionoptiondto.getOptionId());
					dto.setOptionName(questionoptiondto.getOptionName());
					dto.setOptionOrder(questionoptiondto.getOptionOrder());
					dto.setOptionQuesionId(questionoptiondto.getOptionQuesionId());
					dto.setOptionScore(questionoptiondto.getOptionScore());
					dto.setOptionIsChekcbox(questionoptiondto.getOptionIsChekcbox());
					queoptDtolist.add(dto);
				}else{ //新的
					QuestionnaireQuestionOptionDto questionoptiondtonew = listquuestionOption.get(i-1); //上次最后的，，，，
					questionoptiondtonew.setQuestionOptionDtos(queoptDtolist); //添加，题目，选项集合
					newquuestionOption.add(questionoptiondtonew); //添加
					
					queoptDtolist= new ArrayList<QuestionOptionDto>(); //清楚掉 选项集合
					quetionid = otherquetionid; //再次赋值，;
					//再来一次 。。
					QuestionOptionDto dto = new QuestionOptionDto();
					dto.setOptionId(questionoptiondto.getOptionId());
					dto.setOptionName(questionoptiondto.getOptionName());
					dto.setOptionOrder(questionoptiondto.getOptionOrder());
					dto.setOptionQuesionId(questionoptiondto.getOptionQuesionId());
					dto.setOptionScore(questionoptiondto.getOptionScore());
					dto.setOptionIsChekcbox(questionoptiondto.getOptionIsChekcbox());
					queoptDtolist.add(dto);
				}
				//最后一次，
				if(i == listquuestionOption.size()-1){ //最后一次！！！
					questionoptiondto.setQuestionOptionDtos(queoptDtolist); //添加，题目，选项集合
					newquuestionOption.add(questionoptiondto); //添加
				}
				//
				
			}
			
			//计算，分类信息，综合，存入list当中
			for (QuestionnaireQuestionOptionDto questionOption : newquuestionOption) {
				
				//获取题目信息			
				List<QuestionOptionDto> options = 	questionOption.getQuestionOptionDtos(); //选项，分数
				
				int detailedScore = 0; //获取分数
				if(questionOption.getQuestionCalculation()==1){ //计算方式 ，1累计，2 最大值
					detailedScore = getSumScore(options);
				}else{
					detailedScore =  getMaxScore(options);
				}
				
				//1.//营养 2.发育 3，健康 .. 总分，算出来
				type.put(questionOption.getQuestionType(), type.get(questionOption.getQuestionType())+detailedScore);
				
			}
		}
		////System.out.println("=="+type.get(1));
		////System.out.println("=="+type.get(2));
		////System.out.println("=="+type.get(3));
		
		resultMsg.setData(newquuestionOption);
		return resultMsg;
	}
	
	
	/**
	 * 获取bmi 公式为：体重/身高²   
	 * @param height 身高   cm 的单位
	 * @param weight 体重   kg 的单位
	 * @return
	 */
	public static Double getBmi(Double height,Double weight){
		BigDecimal  bg1 = new BigDecimal(height);
		BigDecimal   bg2 = new BigDecimal(weight);
		
		bg1 = bg1.multiply(bg1); //乘以
		bg1 = bg1.divide(new BigDecimal(10000)); //除以
		Double bg3 = bg2.divide(bg1,1,BigDecimal.ROUND_DOWN).doubleValue(); //除以
		return bg3;
	}
	
	/**
	 * 获取bmi 公式为：体重/身高²   
	 * @param height 身高   cm 的单位
	 * @param weight 体重   kg 的单位
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getBmi")
	public  ResultMsg getBMI(Double height,Double weight,Integer age,Integer sex){
		ResultMsg resultMsg=getSuccessResult();
		
		boolean flag = false;
		//参数验证！！
		if(height == null){ //身高
			////System.out.println("身高不能为空.");
			flag = true;
		}else if(weight == null){ //体重
			////System.out.println("体重不能为空.");
			flag = true;
		}else if(age == null){ //age
			//System.out.println("age不能为空.");
			flag = true;
		}else if(sex == null){ //sex
			//System.out.println("sex不能为空.");
			flag = true;
		}
		
		if(flag){
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
	    	resultMsg.setMessage(ResultInfo.ERRORINFO);
	    	resultMsg.setStatus(false);
	    	return resultMsg;
		}
		
		//年龄验证
		if(age>60){
			age = 60;
		}
		//性别，验证
		if(sex !=1 && sex !=2){
			return resultMsg;
		}
		
		
		Double bmi = getBmi( height, weight);
    	//男童鞋，，女童鞋，，，月龄，获取相对应的标准差 
    	BMIReference BMIreference = BMIReference.getBMI(age, sex);
    	
    	Double N3SD = BMIreference.getN3SD(); //-3SD
    	Double N2SD = BMIreference.getN2SD(); //-2SD
    	Double P1SD = BMIreference.getP1SD(); //1SD
    	Double P2SD = BMIreference.getP2SD(); //2SD
    	String tips = "";
    	if(bmi <= N3SD){
    		tips = "过低";
    	}else if(bmi<=N2SD){
    		tips = "偏低";
    	}else if( bmi<=P1SD){
    		tips = "正常";
    	}else if( bmi< P2SD ){
    		tips = "偏高";
    	}else if( bmi>= P2SD){
    		tips = "过高";
    	}
    	
    	Double N0SD = BMIreference.getN0SD(); // 正常值
    	
    	
    	HashMap<String, Object> map=new HashMap<String, Object>();
  	  
    	map.put("title", tips);
    	map.put("bmi", bmi.toString());
    	map.put("bmis", N2SD); //开始范围
    	map.put("bmie", P1SD); //借宿范围
    	resultMsg.setData(map);
		return resultMsg;
	}
	
	
	/**
	 * 添加，答题人信息
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/addQuestionnaireAnswer")
	public ResultMsg addQuestionnaireAnswer(HttpServletRequest request,HttpServletResponse response,Double height,Double weight,QuestionnaireAnswer answer) throws Exception{
		ResultMsg resultMsg=getSuccessResult();
		
		boolean flag = false;
		//参数验证！！
		if(height == null){ //身高
			flag = true;
		}else if(weight == null){ //体重
			flag = true;
		}
		
		if(flag){
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
	    	resultMsg.setMessage(ResultInfo.ERRORINFO);
	    	resultMsg.setStatus(false);
	    	return resultMsg;
		}
		
	
		
		
		//身高，体重，计算！ height cm  weight  kg
		
		answer.setAnswerBabyHeight(Double.valueOf(height*10).intValue()); //cm
		answer.setAnswerBabyWeight(Double.valueOf(weight*1000).intValue()); //kg
		
		answer.setAnswerScannedNumber(1);// 默认值
		
		QuestionnaireAnswer reanswer =questionnaireService.addQuestionnaireAnswer(answer);
	    HashMap<String, Object> map=new HashMap<String, Object>();
	    if(reanswer!=null){
	    	map.put("result", true);
	    	//bmi 计算
	    	Double bmi = getBmi( height, weight);
	    	answer.setBmi(bmi);
	    	//男童鞋，，女童鞋，，，月龄，获取相对应的标准差 
	    	
	    	int babyage = answer.getAnswerBabyAge();
	    	if(babyage>60){
	    		babyage = 60;
	    	}
	    	
	    	BMIReference BMIreference = BMIReference.getBMI(babyage, answer.getAnswerBabySex());
	    	String strage = BMIReference.getBMIText(babyage);
	 
	    	Double N3SD = BMIreference.getN3SD(); //-3SD
	    	Double N2SD = BMIreference.getN2SD(); //-2SD
	    	Double P1SD = BMIreference.getP1SD(); //1SD
	    	Double P2SD = BMIreference.getP2SD(); //2SD
	    	String tips = "";
	    	if(bmi <= N3SD){
	    		tips =  "1";
	    	}else if(bmi<=N2SD){
	    		tips = "2";
	    	}else if( bmi<=P1SD){
	    		tips = "3";
	    	}else if( bmi< P2SD ){
	    		tips = "4";
	    	}else if( bmi>= P2SD){
	    		tips = "5";
	    	}
	    	
	    	tips = BMIReference.bmitext.get(strage+tips);
	    	reanswer.setTips("宝贝tips的值："+bmi+" 参考范围："+N2SD+"~~"+P1SD+"<br/>"+tips);
	    	
	    	//宝宝头围
	    	
	    	
	    	if(babyage<=3){
	    		babyage = 3;
	    	}else if(babyage<=6){
	    		babyage = 6;
	    	}else if(babyage<=12){
	    		babyage = 12;
	    	}else if(babyage<=15){
	    		babyage = 15;
	    	}else if(babyage<=18){
	    		babyage = 18;
	    	}else if(babyage<=24){
	    		babyage = 24;
	    	}else if(babyage<=30){
	    		babyage = 30;
	    	}else if(babyage<=36){
	    		babyage = 36;
	    	}else if(babyage<=48){
	    		babyage = 48;
	    	}else if(babyage<=60){
	    		babyage = 60;
	    	}
	    	Double begind = babytouwei.get(babyage+"_"+reanswer.getAnswerBabySex()+"_b");
	    	Double endd = babytouwei.get(babyage+"_"+reanswer.getAnswerBabySex()+"_e");
	    	
	    	if(begind!=null&& endd!=null ){
	    		if(reanswer.getAnswerHeadWith()>begind){
	    			reanswer.setAnswerRemark("头围过大，应留意宝宝脑部健康发育。");
	    		}else if(reanswer.getAnswerHeadWith()<endd){
	    			reanswer.setAnswerRemark("头围过小，应留意宝宝脑部发育情况。");
	    		}
	    	}

//	    	System.out.println(reanswer.getAnswerHeadWith());
//	    	System.out.println(begind);
//	    	System.out.println(endd);
	    	
	    	//System.out.println(tips);
	    	//保存用户信息到，session中
	    	answerUtils.saveUserToSession(reanswer, request, response);
	    } else{
	    	resultMsg.setResultCode(ResultInfo.ERRORCODE);
	    	resultMsg.setMessage(ResultInfo.ERRORINFO);
	    	resultMsg.setStatus(false);
	    	map.put("result", false);
	    }
	    
		resultMsg.setData(map);
		return resultMsg;
	}
	
	
	
	/**
	 * 答题
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping("/addQuestionnaireAnswerDetailed")
	public ResultMsg addQuestionnaireAnswerDetailed(HttpServletRequest request,String answeList) {
		//String aa = "[{\"detailedQuestionId\":2,\"optionList\":[{\"optionId\":4,\"optionScore\":30},{\"optionId\":5,\"optionScore\":10}]}]";

		ResultMsg resultMsg=getSuccessResult();
		 Map<String,String> reoptiondes = new HashMap<String,String>(); //结果tips

		if(StringUtils.isEmpty(answeList)){ //参数为空
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setMessage(ResultInfo.ERRORINFO);
			resultMsg.setStatus(false);
			return resultMsg;
		}
		List<QuestionnaireAnswerDetailed> answerDetailedList =  new ArrayList<QuestionnaireAnswerDetailed>();
		try {
			
			JSONObject  json = JSONObject.fromObject(answeList);
			
			Iterator<String> it = json.keys();  
	        while(it.hasNext()){  
	        	QuestionnaireAnswerDetailed detailed = new QuestionnaireAnswerDetailed();
	        	String key =  (String) it.next().toString();
	        	String value = json.get(key).toString();
	        	detailed.setDetailedQuestionId(Integer.parseInt(key));
	        	String[] values = value.split(",");
	        	 List<QuestionOptionDto> optionList =  new ArrayList<QuestionOptionDto>(); // 选项信息
	        	for (int i = 0; i < values.length; i++) {
	        		QuestionnaireOption option = questionnaireService.getQuestionnaireOptionByid(values[i]);
	        		QuestionOptionDto dto = new QuestionOptionDto();
	        		dto.setOptionId(Integer.valueOf(values[i]));
	        		dto.setOptionScore(option.getOptionScore());
	        		//放入信息
	        		if(StringUtils.isNotEmpty(option.getOptionDesc())){
	        			reoptiondes.put(option.getOptionDesc(), optiondesc.get(option.getOptionDesc()));
	        		}
	        		optionList.add(dto);
				}
	        	detailed.setOptionList(optionList);
	        	answerDetailedList.add(detailed);
	        }  
			
		} catch (Exception e) {
			//System.out.println("字符串解析错误！请输入正确的格式");
			e.printStackTrace();
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setMessage(ResultInfo.ERRORINFO);
			resultMsg.setStatus(false);
			return resultMsg;
		}
//		QuestionnaireAnswer answer =questionnaireService.getQuestionnaireAnswerByid("244");
		QuestionnaireAnswer answer;
		try {
			answer = answerUtils.getUserBySession(request);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//System.out.println("获取用户信息异常");
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
	    	resultMsg.setMessage(ResultInfo.ERRORINFO);
	    	resultMsg.setStatus(false);
			e.printStackTrace();
			return resultMsg;
		}
		int result=0;
		//总分，
		Double  SumScore1= 0.0;
		Double  SumScore2= 0.0;
		Double  SumScore3= 0.0;
		int SumScore = 0;
		//类型，得分
		for (QuestionnaireAnswerDetailed answerdetailed : answerDetailedList) {
			//获取题目信息
			QuestionnaireQuestion question =  questionnaireService.getQuestionnaireQuestionByid(String.valueOf(answerdetailed.getDetailedQuestionId()));
			
			List<QuestionOptionDto> options = 	answerdetailed.getOptionList(); //选项，分数
			
			int detailedScore = 0; //获取分数
			if(question.getQuestionCalculation()==1){ //计算方式 ，1累计，2 最大值
				detailedScore = getSumScore(options);
			}else{
				detailedScore =  getMaxScore(options);
			}
			
			answerdetailed.setDetailedAnswerId(answer.getAnswerId()); //答题人
			answerdetailed.setDetailedScore(detailedScore); //分数
			answerdetailed.setDetailedType(question.getQuestionType()); //答题类型.....
			for (int i = 0; i < options.size(); i++) {
				answerdetailed.setDetailedOptionId(options.get(i).getOptionId()); //选项id
				//添加记录
			    result=questionnaireService.addQuestionnaireAnswerDetailed(answerdetailed); //添加数据
			}
			
			if(answerdetailed.getDetailedType() == 1 ) { //营养
				SumScore1 += answerdetailed.getDetailedScore();
			}else if(answerdetailed.getDetailedType() == 2 ) { //发育
				SumScore2 += answerdetailed.getDetailedScore();
			}else if(answerdetailed.getDetailedType() == 3 ) { //健康
				SumScore3 += answerdetailed.getDetailedScore();
			}
			SumScore += answerdetailed.getDetailedScore();
			
		}
		
		
			//百分比
		if(type.get(1)>0){
			SumScore1 = new BigDecimal(SumScore1).divide(new BigDecimal(type.get(1)),2,BigDecimal.ROUND_DOWN).doubleValue()  ; //除以
			}else {SumScore1 =0.0;}
		if(type.get(2)>0){
			SumScore2 = new BigDecimal(SumScore2).divide(new BigDecimal(type.get(2)),2,BigDecimal.ROUND_DOWN).doubleValue() ;//除以
		}else {SumScore2 =0.0;}
		if(type.get(3)>0){
			SumScore3 = new BigDecimal(SumScore3).divide(new BigDecimal(type.get(3)),2,BigDecimal.ROUND_DOWN).doubleValue();//除以
		}else {SumScore3 =0.0;}
			//比较大小....
			double max = SumScore1;
			int type = 1;
		
			if(SumScore2>max){
				max = SumScore2;  type = 2;
			}
			if(SumScore3>max){
				max = SumScore3;  type = 3;
			}
//			
//			System.out.println("总qqqq:"+SumScore1);
//			System.out.println("总qqqqq:"+SumScore2);
//			System.out.println("总qqqq:"+SumScore3);
			
			
			AnswerReuslt results = getResult(type,answer.getAnswerBabySex());
				
			SumScore = 65+SumScore; //基数
			if(SumScore< 80){
				SumScore = 80;
			}else if(SumScore>100){
				SumScore = 100;
			}
			//tips获取
			String tips = answer.getTips();
			Map<String, Object> map = new HashMap<String, Object>();
			//遍历结果，顺序
			int topnum = 0;
						
			String[] shunxu  = {
			"1B","7B","8B","8D","6A","6B","6C","6D","6E","6F","126C","9C","D","E","2A","2D","2E","11G","12A","12B","12C","12D","12E","12F","12G","3A","4B"};

			if(answer.getAnswerRemark()!= null){
				topnum = 1;
				tips += "<br/>1、"+answer.getAnswerRemark();
			}	
			
			
			
			for (int i = 0; i < shunxu.length; i++) {
				if(topnum >2){
					i = shunxu.length;
					break;
				}
				if(reoptiondes.containsKey(shunxu[i])){
					if(tips.indexOf(reoptiondes.get(shunxu[i])) == -1){
						tips += "<br/>"+(topnum+1)+"、"+reoptiondes.get(shunxu[i]);
						topnum++;
					}
				}
			}
			
		
			map.put("score", SumScore); // 分数
			map.put("tips", tips);	//tips
			try {
				// 随机数，防止预测ID
				String userId = md5.encrypt(answer.getAnswerId().toString() + "-" + random.nextInt(10000));
				map.put("id", userId); //用户id
			} catch (Exception e) {
				e.printStackTrace();
			}
			map.put("name", results.getName());  //白雪公主
			map.put("content", results.getContent()); //简介
			map.put("picture", results.getPicture()); //图片
			map.put("type", type);  //type 1营养 2发育 3健康
			//保存，用户分数
			answer.setAnswerUserScore(SumScore); 
			answer.setAnswerIsFullmoon(type); //这里字段，存取，测试结果类型，不存放是否足月
			
			
			answer.setAnswerRemark(results.getName()+":"+results.getContent());
			
			questionnaireService.updateQuestionnaireAnswer(answer);
	    if (result>0) {
	    	map.put("result", true);
	    } else{
	    	resultMsg.setResultCode(ResultInfo.ERRORCODE);
	    	resultMsg.setMessage(ResultInfo.ERRORINFO);
	    	resultMsg.setStatus(false);
	    	map.put("result", false);
	    }
	    
		resultMsg.setData(map);
		return resultMsg;
	}
	
	//返回处理结果
	public Integer getMaxScore(List<QuestionOptionDto> options){
		Integer max = options.get(0).getOptionScore();
		
		for (int i = 1; i < options.size(); i++) {
			Integer score = options.get(i).getOptionScore();
			////System.out.println.out.println(score);
			if(score>max){
				max = score;
			}
		}
		return max;
	}
	public Integer getSumScore(List<QuestionOptionDto> options){
		Integer max =  0 ;
		for (int i = 0; i < options.size(); i++) {
			QuestionOptionDto dto = options.get(i);
			Integer score = dto.getOptionScore();
			////System.out.println(score);
				max += score;
		}
		return max;
	}
	
	
	//返回处理结果
	public ResultMsg getSuccessResult(){
		ResultMsg remsg=new ResultMsg();
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setMessage(ResultInfo.SUCCESSINFO);
		remsg.setStatus(true);
		return remsg;
	}
	
	/**
	 * base图片上传
	 * @throws IOException 
	 */
	@SuppressWarnings({ "deprecation", "restriction" })
	@ResponseBody
	@RequestMapping("/addPicture")
	public ResultMsg uploadPicture(HttpServletRequest req) throws IOException{
		ResultMsg rm = new ResultMsg();
	
		//取到前台传过来的 base64图片 并创建要存放在项目中的路径
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();    
        ServletContext servletContext = webApplicationContext.getServletContext(); 
        String realPath = servletContext.getRealPath("/");  
		String imgFilePath = realPath + defautImagePath;
		try {
			isExitsPath(imgFilePath);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//创建分享对象 并存入数据库
		String postParams = StrUtils.getPostParamsStr(req);		//data:image/png;base64,iVBORw0
		String[] shareImgUrlArr = org.apache.commons.lang3.StringUtils.split(postParams, ",");
		String imgUrl = "";
		HashMap<String, String> map = new HashMap<String, String>();
		if(shareImgUrlArr != null && shareImgUrlArr.length > 0){
			// 防止内存溢出
			String suffixName = new String (shareImgUrlArr[0].split(";")[0].split("/")[1]);
			String shareImgUrl = new String (shareImgUrlArr[1]);
			
			// 通过文件头判断后缀
			byte [] b = new byte[28];
			shareImgUrl.getBytes(0, 27, b, 0);
			String temp = new String(b);
			b = decoder.decodeBuffer(temp);
			
			// 二进制转换文件头
			String type = null;
			String fileHead = byte2hex(b);
			fileHead = fileHead.toUpperCase();
			
			// 获取系统支持的文件类型，如果不支持，返回默认的图片
			FileType [] fileTypes = FileType.values();
			for (FileType fileType : fileTypes) {
				if (fileHead.startsWith(fileType.getValue())) {
					type = fileType.getSuffix();
					break;
				}
			}
			if (type == null) {
				System.err.println("用户图片异常..." + fileHead);
				imgUrl = "/iamberry/default.png";
			} else {
				String fileName = getFileName(suffixName, type);
				boolean flag = generateImage(shareImgUrl, imgFilePath + "/" + fileName);
				if(flag){
					imgUrl = defautImagePath + fileName;
				}else{
					imgUrl = "/iamberry/default.png";
				}
			}
		}
		
		//返回值拼凑 
		String requurl = req.getContextPath();//获取web项目的路径
		
		map.put("imgUrl", requurl+"/"+imgUrl);
		
		rm.setStatus(true);
		rm.setResultCode(ResultInfo.SUCCESSCODE);
		rm.setMessage(ResultInfo.SUCCESSINFO);
		rm.setData(map);
	
		return rm;
	}
	
	 public static String byte2hex(byte[] b) { //一个字节的数，
        // 转成16进制字符串
        String hs = "";
        String tmp = "";
        for (int n = 0; n < b.length; n++) {
            //整数转成十六进制表示
            tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (tmp.length() == 1) {
                hs = hs + "0" + tmp;
            } else {
                hs = hs + tmp;
            }
        }
        tmp = null;
        return hs;
    }
	
	/**
	 * 获取 file 的文件名
	 * create date 2016年6月1日
	 * @author 穆再兴
	 * @param realPath
	 * @param openid
	 * @return
	 */
	private String getFileName(String suffixName, String type){
		long time = new Date().getTime();
		Long timeStr = new Long(time);
		return  timeStr + "." + type;
	}
	
	/**
	 * 判断路径是否存在 不存在则创建
	 * create date 2016年6月1日
	 * @author 穆再兴
	 * @param path
	 * @return
	 * @throws InterruptedException
	 */
	public boolean isExitsPath(String path)throws InterruptedException{
		String [] paths=path.split("/");
		StringBuilder fullPath=new StringBuilder();
		for (int i = 0; i < paths.length; i++) {
			fullPath.append(paths[i]).append("/");
			File file=new File(fullPath.toString());
			if(!file.exists()){
				file.mkdir();
			}
		}
		File file=new File(fullPath.toString());//目录全路径
		if (!file.exists()) {
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 对字节数组字符串进行Base64解码生成图片 并存入对应的路径
	 * create date 2016年6月1日
	 * @author 穆再兴
	 * @param imgStr Base64字符串
	 * @param imgFilePath 存入的路径
	 * @return
	 */
	private boolean generateImage(String imgStr, String imgFilePath) {  
		if (imgStr == null) {return false;}// 图像数据为空
		try {
			// Base64解码  
			@SuppressWarnings("restriction")
			byte[] bytes = decoder.decodeBuffer(imgStr);  
			for (int i = 0; i < bytes.length; ++i) {  
				if (bytes[i] < 0) {// 调整异常数据  
					bytes[i] += 256;  
				}  
			}  
			// 生成图片 
			File file = new File(imgFilePath);
			FileUtils.writeByteArrayToFile(file, bytes);
			return true;  
		} catch (Exception e) {
			e.printStackTrace();
			return false;  
		}  
	}  
}
