<%@ page language="java" contentType="application/x-javascript; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.qmth.qrzk.repository.utils.General"%>
<%@ taglib uri="/WEB-INF/taglib/c.tld" prefix="c"%>
<c:set var="ctx" value="<%=General.getBasePath(request)%>" scope="request"/>
var Current_Page=1;
function search(url, currentPage) {
		Current_Page = currentPage;
		var course = $("#courseId").val();
		var book = $("#bookId").val();
		var assessmentDemand = $("#assessmentDemand").val();
		var estimateDifficultyCode = $("#estimateDifficultyCode").val();
		var type = $("#quesTypeId").val();
		var chapter = $("#chapter").val();
		var section = $("#section").val();
		var item = $("#item").val();
		var page = $("#ye").val();
		var abilityCode = $("#abilityCode").val();
		var status = $("#status").val();
		var score=$("#score").val();
		var keyword = $("#keyword").val();
		var questionId;
		var obj;
		if(false){  			//判断关键字输入栏是否是数字
			questionId=keyword;
			obj = {
					"id" :questionId,
					"courseId" : course,
					"typeId" : type,
					"bookId" : book,
					"estimateDifficultyCode" : estimateDifficultyCode,
					"assessmentDemand" : assessmentDemand,
					"abilityCode" : abilityCode,
					"chapter" : chapter,
					"section" : section,
					"item" : item,
					"page" : page,
					"statusCode" : status,
					"score":score
				};
		}else{
			obj = {
					"courseId" : course,
					"typeId" : type,
					"bookId" : book,
					"estimateDifficultyCode" : estimateDifficultyCode,
					"assessmentDemand" : assessmentDemand,
					"abilityCode" : abilityCode,
					"chapter" : chapter,
					"section" : section,
					"item" : item,
					"page" : page,
					"statusCode" : status,
					"keyword" : keyword,
					"score":score
				};
		}
		var Question = JSON.stringify(obj);
		waitingDialog.show('正在查询中，请稍等...');
		$.ajax({
					type : "POST",
					url : url + "/question/zujuanSearch?currentPage=" + currentPage + "&paperId=" + $("#paperId").val() + "&filterBySkel=" + $("#filterBySkel").is(":checked") + "&quesOperType=" + quesOperType + "&paperDetailId=" + $("#detailId").val(),
					data : Question,
					contentType : "application/json; charset=utf-8",
					dataType : "json",
					success : function(callback) {
						waitingDialog.hide();
						var ReHtml = "";
						callback = eval(callback);
						var count = callback[1];
						currentPage = callback[2];
						Current_Page = currentPage;
						callback = callback[0];
						var role=$("#role").val();
						var userId=$("#userId").val();
						for (var i = 0; i < callback.length; i++) {
							var type_id=callback[i].typeId;
							var type=$("#"+type_id+"_type").text();
							var cc = $("#course option:selected").text();
							var checkBtnHtml = "<input type=\"button\" value=\"选中\" class=\"btn\" onclick=\"checkQuestion("+callback[i].id+")\" />";
							
							//var questionIdTD = "<td vertical-align='top' width='100px'><div><a href="+url+"/question/view/"+callback[i].id+" id=\"questionId\">" + callback[i].questionNo + "</a></div><div style='margin-top:25px;' id="+callback[i].id+"_log></div><div style='margin-top:15px;' id="+callback[i].id+"_div>"+checkBtnHtml+"</div></td>";
							var questionIdTD = "<td vertical-align='top'><div>" + callback[i].questionNo + "</div><div style='margin-top:25px;' id="+callback[i].id+"_log></div><div style='margin-top:15px;' id="+callback[i].id+"_div>"+checkBtnHtml+"</div></td>";
							
							var assessmentDemandText = codeMap['ASSESSMENT_DEMAND-' + callback[i].assessmentDemand];
							if(!assessmentDemandText){
								assessmentDemandText = '';
							}
							var abilityText = codeMap['ABILITY-' + callback[i].abilityCode];
							if(!abilityText){
								abilityText = '';
							}
							var estimateDifficultyText = codeMap['QUESTION_DIFFICULTY-' + callback[i].estimateDifficultyCode];
							if(!estimateDifficultyText){
								estimateDifficultyText = '';
							}
							
							var questionBasicInfoTD = "<td style='text-align:left'><div>题型：" +callback[i].typeName 
								+ "</div><div>教材：" + callback[i].bookName
								+ "</div><div>分值：" + callback[i].score
								+ "</div><div>知识点：" + callback[i].chapter + "章" + trimStr(callback[i].section,'-') + "节" + trimStr(callback[i].item,'-') + "目" + trimStr(callback[i].page,'-') + "页"
								+ "</div><div>认知层次：" + trimStr(abilityText,'-')
								+ "</div><div>考核要求：" + trimStr(assessmentDemandText)
								+ "</div><div>预计难度：" + trimStr(estimateDifficultyText)
								+ "</div><div>命题教师：" + trimStr(callback[i].setTeacherName)
								+ "</div><div>命题时间：" + formatDate(callback[i].setTime)
								+ "</div><div>启用时间：" + shortFormatDate(callback[i].enableTime)
								+ "</div>";
							if(callback[i].paperTasks.length == 0){
								questionBasicInfoTD = questionBasicInfoTD + '<div>此试题未被使用</div>';
							}else{
								var content = '<div style="color:#000">此题已被<span style="font-weight:bold;">' + callback[i].paperTasks.length + '</span>个试卷使用：</div>';
             					content = content + '<table cellpadding="0" cellspacing="0" border="0" style="width:270px;border-collapse:collapse;border:none;">';
             					content = content + '<tr><td class="myTd3" nowrap="nowrap">试卷名称</td><td class="myTd3" nowrap="nowrap">状态</td></tr>'
             					for(var j=0;j<callback[i].paperTasks.length;j++){
             						var task = callback[i].paperTasks[j];
             						content = content + '<tr><td class="myTd4" width="50%"><a href="' + url + '/zujuan/manualAdd?taskId=' + task.id + '" target="viewPaper_' + task.id + '">' + task.paperName + '</a></td><td class="myTd4">' + task.statusName + '</td></tr>';
             					}
             					content = content + '</table>';
								questionBasicInfoTD = questionBasicInfoTD + content;
							}
							questionBasicInfoTD = questionBasicInfoTD + "</td>";
							
							var questionContentTD = "<td width='70%' style='text-align: left;' onclick=\"openinfo("+callback[i].id+","+type_id+")\" >"
							+ "<div id="+callback[i].id+" title='点击显示答案和分析'>"
							+ "<div class='question-body'>" +
								"<div>"+callback[i].bodyHtml+"</div>";

							if(callback[i].options != null && callback[i].options.length > 0){
								questionContentTD += "<div style='text-align: left;'><table class='optionTable'>";
								for(var j = 0; j < callback[i].options.length; j++){
									if(callback[i].options[j].isCorrectOption == 1){
										questionContentTD += "<tr style='color:red;'><td>&nbsp;</td><td>";
									}else{
										questionContentTD += "<tr><td>&nbsp;</td><td>";
									}
									questionContentTD += callback[i].options[j].optionNoString + "\.&nbsp;</td><td>" + callback[i].options[j].contentHtml + "</td></tr>";
								}
								questionContentTD += "</table></div>";
							}else{
								questionContentTD += "<div style='border-top:1px dashed #cccccc;margin-top:5px;margin-bottom:5px;' id='"+callback[i].id+"_line'></div>" +
										  "<div id='"+callback[i].id+"_question'>" + callback[i].answerHtml + "</div>";
							}
							
							questionContentTD += "</div></div></td>";
							
							ReHtml += "<tr align='center'>"
								+ questionIdTD
								+ questionBasicInfoTD
								+ questionContentTD
								+ "</tr>";
							
							if (callback.length != (i + 1)) {
								var intervalTR = "<tr class='interval'><td colspan='3' ></td></tr>";
								ReHtml += intervalTR;
							}

						}
						var size = "<span>需要填充的试题数量：<span id=\"blankQuesNumFowShow\">" + $("#blankQuesNum").val() + "</span>，查询满足条件试题数量："+ count + "</span>";
						$("#row").html(size);
						$(".info tbody").html(ReHtml);
						//if (currentPage == "1")
							pageShow(currentPage, count, "false");
					}
				});
	//}
}
var restQuesDetailsMap = {};
var curToChange = null;
function checkQuestion(id){
	curToChange = id;
	if(quesOperType == "ADD_INTO_PAPER" && $("#blankQuesNum").val() - 0 == 0){
		//alertify.error("该题型的题已经组好了，不用再选题了!");
		return false;
	}
	$.ajax({
		type : "POST",
		url : "${ctx}/question/checkQuestion/"+id + "?paperId=" + $("#paperId").val() + "&quesTypeId=" + $("#quesTypeId").val() + "&score=" + $("#score").val() + "&quesOperType=" + quesOperType + "&paperDetailId=" + $("#detailId").val(),
		data : "",
		contentType : "application/json; charset=utf-8",
		dataType : "json",
		success : function(callback) {
			callback = eval(callback);
			if(callback.type=="success"){
				var question=callback.question;
				if(quesOperType == "ADD_INTO_PAPER" && parent.manualAddQues($("#pqtId").val(),question)){    //传入question对象
					$("#blankQuesNum").val($("#blankQuesNum").val()-1);
					$("#blankQuesNumFowShow").text($("#blankQuesNum").val());
					$("#"+id+"_div").find("input[type=button]").attr("disabled",true);
					$("#"+id+"_div").find("input[type=button]").val("已选");
					setTimeout(function(){search('${ctx}',Current_Page)},100);
					if($("#blankQuesNum").val() - 0 == 0){
						//alertify.error("该题型的题已经组好了，不用再选题了!");
						return false;
					}
				}
				if(quesOperType == "CHANGE_INTO_PAPER"){
					parent.updateQues($("#detailId").val(),question);
					setTimeout(function(){parent.closeChangeQuesWin()},100);
				}
			}else{
				alertify.confirm("该题不允许添加到试卷中，原因：该题不符合细目表规则。现在是否将此题的属性修改成符合细目表规则的属性？", function (data) {
		            if (data) {
		            	$.post('${ctx}/question/calcRestQuesDetails',{"paperId":$("#paperId").val(),"quesTypeId":$("#quesTypeId").val(),"score":$("#score").val()},function(res){
							if(res.flag=='failed'){
					           alertify.error(res.msg);
					           return false;
							}else{
								var calcDetails = res;
								if(quesOperType == "ADD_INTO_PAPER" || !$("#quesId").val()){
									$("#restQuesDetails").empty();
									loadRestQuesDetails(calcDetails);
									showSelectQuesAttrWin();
								}else{
									$.post('${ctx}/question/quesDetail/' + $("#quesId").val(),{},function(res){
										if(res.flag=='failed'){
								           alertify.error(res.msg);
								           return false;
										}else{
											$("#restQuesDetails").empty();
											{
												var qd = {
														"chapterNo" : res.question.chapter,
														"estimateDifficultyCode":res.question.estimateDifficultyCode,
														"estimateDifficultyText":$("#estimateDifficultyCode").find("option[value='" + res.question.estimateDifficultyCode + "']").text(),
														"abilityCode":res.question.abilityCode,
														"abilityText":$("#abilityCode").find("option[value='" + res.question.abilityCode + "']").text()
														};
												var value = qd.chapterNo + "_" + qd.estimateDifficultyCode + "_" + qd.abilityCode + "_self";
												var text = "当前：第" + qd.chapterNo + "章，认知层次：" + qd.abilityText + "，预计难度：" + qd.estimateDifficultyText;
												restQuesDetailsMap[value] = qd;
												$("<option value='" + value + "'>" + text + "</option>").appendTo($("#restQuesDetails"));
											}
											loadRestQuesDetails(calcDetails);
											showSelectQuesAttrWin();
										}
									});
								}
							}
						});
		            }
		        });
				//$.messager.alert('提示', callback.msg, 'error');
			}
		}
	});
}

function loadRestQuesDetails(calcDetails){
	for(var i=0;i<calcDetails.restQuesDetails.length;i++){
		var qd = calcDetails.restQuesDetails[i];
		if(qd.quesNum > 0){
			var value = qd.chapterNo + "_" + qd.estimateDifficultyCode + "_" + qd.abilityCode;
			var text = "第" + qd.chapterNo + "章，认知层次：" + qd.abilityText + "，预计难度：" + qd.estimateDifficultyText;
			restQuesDetailsMap[value] = qd;
			$("<option value='" + value + "'>" + text + "</option>").appendTo($("#restQuesDetails"));
		}
	}
}

function showSelectQuesAttrWin(){
	$('#selectQuesAttrDiv').window({
		left:($(document).width() - $("#selectQuesAttrDiv").width()) / 2,
		top:$(document).scrollTop() + 60
	});
	$('#selectQuesAttrDiv').window('open');
}

function audit(id){
	$.ajax({
		type : "POST",
		url : "${ctx}/question/updateAudit/"+id,
		data : "",
		contentType : "application/json; charset=utf-8",
		dataType : "json",
		success : function(callback) {
			callback = eval(callback);
			if(callback.type=="success"){
				$("#"+id+"_status").html("状态："+callback.status);
				$("#"+id+"_div").hide();
			}
		}
	});
}

function openinfo(id,type_id){
	if($("#"+id+"_question").is(":hidden")){
		$("#"+id+"_question").show();
		$("#"+id+"_line").css("border-top","1px dashed #cccccc");
		
		$("#"+id+"_line").show();
	}else{
		$("#"+id+"_question").hide();
		$("#"+id+"_line").hide();
	}
}

function pageShow(ThisPage, PageCount, flag) {
	if (flag == "false") {
	} else {
		search('${ctx}', ThisPage);
	}

	// ThisPage = 当前页
	// PageCount = 总条数
	// 获取当前页之后，可通过Ajax进行返值。
	$(function() {
		// 每页条数
		var pageText = 3;
		// 分页总数
		var pageNumber = Math.ceil(PageCount / pageText);
		// page分割数量
		var pageFor = 6;
		var pageSlipt = pageFor / 2;
		var pageHTML = new Array;
		
		// 首页
		if(PageCount!=0){
			pageHTML += "<a href=\"javascript:pageShow(1,'" + PageCount+ "');\" >第一页</a>";
		}else{
			pageHTML += "<a href=\"javascript:pageShow(1,'" + PageCount+ "','false');\" >第一页</a>";
		}
		
		if (pageNumber > pageFor) {
			if (ThisPage > pageSlipt) { // 如果当前页大于分割数量的一半就开始分页
				/*
				 * 最后几页的算法
				 */
				if (ThisPage >= (pageNumber - pageSlipt)) { // 如果当前页大于等于总页数减去分割数量的一半
					if (ThisPage == pageNumber) { // 如果当前页等于总页数不在往后加页数
						countPage = (((ThisPage - pageSlipt) + pageFor) - pageSlipt);
					} else {
						countPage = (((ThisPage - pageSlipt) + pageFor)- pageSlipt + 1);
					}
				} else {
					countPage = ((ThisPage - pageSlipt) + pageFor);
				}

				for (var i = (ThisPage - pageSlipt); i <= countPage; i++) {
					if (i == ThisPage) {
						pageHTML += "<a href=\"javascript:pageShow(" + i + ",'"+ PageCount + "');\" class=\"this\" >" + i+ "</a>";
					} else {
						pageHTML += "<a href=\"javascript:pageShow(" + i + ",'"+ PageCount + "');\"  >" + i + "</a>";
					}
				}
			} else {
				for (var i = 1; i < pageFor; i++) {
					if (i == ThisPage) {
						pageHTML += "<a href=\"javascript:pageShow(" + i + ",'"+ PageCount + "');\" class=\"this\" >" + i+ "</a>";
					} else {
						pageHTML += "<a href=\"javascript:pageShow(" + i + ",'"+ PageCount + "');\" >" + i + "</a>";
					}
				}
			}
		} else { //原始的那种分页
			for (var i = 1; i <= pageNumber; i++) {
				if (i == ThisPage) {
					pageHTML += "<a href=\"javascript:pageShow(" + i + ",'"+ PageCount + "');\" class=\"this\"  >" + i+ "</a>";
				} else {
					pageHTML += "<a href=\"javascript:pageShow(" + i + ",'"+ PageCount + "');\"  >" + i + "</a>";
				}
			}
		}
		//末页
		if(PageCount!=0){
			pageHTML += "<a href=\"javascript:pageShow(" + pageNumber + ",'"+ PageCount + "');\" >最后一页</a>";
		}else{
			pageHTML += "<a href=\"javascript:pageShow(" + pageNumber + ",'"+ PageCount + "','false');\" >最后一页</a>";
		}
		
		$(".pages").html(pageHTML);
	});
}
	
	function formatDate2(d){
		if(!d){
			return "";
		}
		return d.getFullYear()+"-"+formatTo00(d.getMonth()+1)+"-"+formatTo00(d.getDate());
	}
	


function trimStr(str,defaultStr){
	if(defaultStr == null){
		defaultStr = '';
	}
	if(str == null || str == '' || typeof(str) == "undefined"){
		return defaultStr;
	}else{
		return str;
	}
}