<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="/WEB-INF/taglib/c.tld" prefix="c"%>
<script type="text/javascript">
var treeData;
var blockData;
var groupData;
if ('${hasData}'=='true') {
	try{
		treeData = ${treeData};
		blockData = ${blockData};
		groupData = ${groupData};
	}catch(err){  
	}
} else {
	treeData = [];
	blockData = [];
	groupData = [];
}
var treeSetting = {
	data : {
		simpleData : {
			enable : true,
			idKey: "id",
			pIdKey: "pId",
			rootPId: 0,
		}
	},
	<c:if test="${flag==false}">
	edit: {
		enable: true,
		showRemoveBtn : canRemove,
		removeTitle: "删除",
		showRenameBtn : false,
		drag: {
			isCopy: false,
			isMove: true,
			prev: true,
			next: true,
			inner: canMoveInner
		}
	},
	</c:if>
	callback : {
		onClick : onNodeClick,
		beforeRemove: function(treeId, treeNode){
			if(treeNode.isParent){
				return confirm("确定删除这个组吗？")
			}else{
				return confirm("确定删除这个大题吗？")
			}
		},
		onRemove: onNodeRemove
	}
};

var blockArray = [];
var groupArray = [];
var treeObject;
var currentNode;

$(document).ready(function(){
	treeObject = $.fn.zTree.init($("#block-tree"), treeSetting, treeData);
	initDataArray();
	$('#add-block-button').click(addBlock);
	$('#add-group-button').click(addGroup);
	<c:if test="${flag==false}">
	$('#block-info-div .info-input').keyup(function(){
		if(currentNode.blockData!=undefined){
			validInfoInput($(this), currentNode.blockData);
			updateBlockNode(currentNode.blockData);
		}
	});
	$('#block-info-div select').change(function(){
		if(currentNode.blockData!=undefined){
			validInfoInput($(this), currentNode.blockData);
		}
	});
	$('#group-info-div .info-input').keyup(function(){
		if(currentNode.groupData!=undefined){
			validInfoInput($(this), currentNode.groupData);
			validGroupInput(currentNode.groupData);
		}
	});
	</c:if>
	$('#mark-link').click(function(){
		if(currentNode.blockData!=undefined){
			var block = currentNode.blockData;
			if(validAllInfo(block)){
				$('#main-div').hide();
				//if(block.stepList==undefined || !$.isArray(block.stepList) || block.stepList.length==0){
				//	$('#mark-select-div').show();
				//}else{
					//if(block.hasStep){
					//	initStepMark(block);
					//}else{
					//	initWholeMark(block);
					//}
				//}
				initMarkStep(block);
			}
		}
	});
	$('#picture-link').click(function(){
		if(currentNode.blockData!=undefined){
			var block = currentNode.blockData;
			if(initPictureConfig(block)){
				$('#main-div').hide();
			}
		}
	});
	$('#clear-all-button').click(function(){
		if(confirm('确定要删除所有的主观大题吗？')){
			$('#submit-form').attr('action', '${ctx}/admin/exam-param/subjective/clear');
			$('#submit-form').submit();
		}	
	});
	$('#save-all-button').click(function(){
		var blockList = [];
		var groupList = [];
		var flag = true;
		var blockNumber = 1;
		var groupNumber = 1;
		$.each(treeObject.getNodes(), function(index, node){
			if(node.blockData!=undefined){
				node.blockData.number = (blockNumber++);
				if(validBlock(node.blockData)){
					blockList.push(node.blockData);
				}else{
					flag = false;
					return false;
				}
			}else{
				node.groupData.number = (groupNumber++);
				var subList=[];
				var subFlag=true;
				$.each(node.children, function(subIndex, subNode){
					if(subNode.blockData!=undefined){
						subNode.blockData.number = (blockNumber++);
						subNode.blockData.groupNumber = node.groupData.number;
						if(validBlock(subNode.blockData)){
							blockList.push(subNode.blockData);
							subList.push(subNode.blockData);
						}else{
							subFlag=false;
							return false;
						}
					}
				});
				if(subFlag && validGroup(node.groupData, subList)){
					groupList.push(node.groupData);
				}else{
					flag = false;
					return false;
				}
			}
		});
		if(flag){
			if(blockList.length>0){
				$.each(blockList, function(index, block){
					block.node=undefined;
				});
				$.each(groupList, function(index, group){
					group.node=undefined;
				});
				$('#submit-form input[name="blockValue"]').val(JSON.stringify(blockList));
				$('#submit-form input[name="groupValue"]').val(JSON.stringify(groupList));
				$('#submit-form').submit();
			}else{
				alert('请添加主观题块');
			}
		}
	});
});

function initDataArray(){
	$.each(blockData,function(index, obj){
		blockArray[obj.number-1]=obj;
	});
	$.each(groupData,function(index, obj){
		groupArray[obj.number-1]=obj;
	});
	$.each(treeObject.transformToArray(treeObject.getNodes()), function(index, node){
		if(node.isParent){
			node.groupData=groupArray[node.id-1001];
			node.groupData.node=node;
		}else{
			node.blockData=blockArray[node.id-1];
			node.blockData.node=node;
		}
	});
}

function onNodeClick(event, treeId, treeNode, clickFlag) {
	currentNode = treeNode;
	if (treeNode.isParent) {
		$('#add-group-li').hide();
		$('#block-info-div').hide();
		selectGroup(treeNode.groupData);
	}else{
		$('#add-group-li').show();
		$('#group-info-div').hide();
		selectBlock(treeNode.blockData);
	}
}

function onNodeRemove(event, treeId, treeNode){
	currentNode = undefined;
	if (treeNode.isParent) {
		removeGroup(treeNode.groupData);
	}else{
		removeBlock(treeNode.blockData);
	}
}

function canMoveInner(treeId, nodes, targetNode) {
	return targetNode!=undefined && targetNode.groupData!=undefined;
}

function canRemove(treeId, treeNode){
	if(${flag}){
		return false;
	}else{
		return true;
	}
}

function addBlock(){
	var block = {viewTotal:false, hasStep:false, groupNumber:0, stepList:[], pictureConfig:'', canViewTotal:0, baseSubjectId:0};
	$('#block-info-div .info-input').each(function(){
		eval('block.'+$(this).attr('name')+'=""');
	});
	var node = {id:blockArray.push(block), pid:0, name:'主观大题', isParent:false};
	if(currentNode!=undefined && currentNode.groupData!=undefined){
		node = treeObject.addNodes(currentNode, node)[0];
	}else{
		node = treeObject.addNodes(null, node)[0];
	}
	node.blockData = block;
	block.node = node;
	treeObject.selectNode(node);
	onNodeClick('click', node.tld, node, 1);
}

function selectBlock(block){
	if(block==undefined){
		return;
	}
	for(var p in block){
		if(typeof(block[p])!="function"){ 
			$('#block-info-div .info-input[name='+p+']').val(block[p]);
			$('#block-info-div select[name='+p+']').val(block[p]);
        }
	}
	$('#block-info-div').show();
}

function removeBlock(block){
	blockArray = $.grep(blockArray, function(index, obj){
		return obj!=block;
	});
	$('#block-info-div').hide();
}

function updateBlockNode(block){
	if(block.title.length>0){
		block.node.name=block.title;
		treeObject.updateNode(block.node);
	}else{
		block.node.name='评卷大题';
		treeObject.updateNode(block.node);
	}
}

function validBlock(block){
	if(block.totalScore>0 && block.mistakeValue>=0 
			&& block.mistakeValue<=block.totalScore && block.reMarkPercent>=0 && block.reMarkPercent<=1 
			&& block.markSelfFrequency>=0 && block.standardFrequency>=0){
		//if(block.pictureConfig==undefined || block.pictureConfig==''){
		//	alert('第'+block.number+'大题图片划块未设置！');
		//	return false;
		//}
		if(block.stepList.length>0){
			var flag = true;
			$.each(block.stepList, function(index, step){
				if(!validStep(step)){
					flag = false;
					return false;
				}
			});
			if(!flag){
				alert('第'+block.number+'大题给分板设置有误！');
			}
			block.viewTotal=block.canViewTotal=='1';
			block.canViewTotal=undefined;
			return flag;
		}else{
			alert('第'+block.number+'大题给分板未设置！');
			return false;
		}
	}
	alert('第'+block.number+'大题参数设置有误！');
	return false;
}

function validStep(step){
	if(step.totalScore>=0 && step.defaultScore>=0 && step.min>=0 && step.max>=step.min 
			&& step.defaultScore<=step.totalScore && step.max<=step.totalScore 
			&& step.max>=step.defaultScore && step.min<=step.defaultScore
			&& step.scoreList.length>0){
		var flag = true;
		if(step.levelList.length>0){
			$.each(step.levelList, function(index, level){
				if(!validLevel(step, level)){
					flag = false;
					return false;
				}
			});
		}
		return flag;
	}
	return false;
}

function validLevel(step, level){
	if(level.max<=step.max && level.min>=step.min && level.max>=level.min){
		return true;
	}else{
		return false;
	}
}

function addGroup(){
	var group = {title:'', blockCount:1, selectCount:1};
	var node = {id:groupArray.push(group), pid:0, name:'选做题组', isParent:true, isOpen:true};
	node = treeObject.addNodes(null, node)[0];
	node.groupData = group;
	group.node = node;
	treeObject.selectNode(node);
	onNodeClick('click', node.tld, node, 1);
}

function selectGroup(group){
	if(group==undefined){
		return;
	}
	for(var p in group){
		if(typeof(group[p])!="function"){ 
			$('#group-info-div .info-input[name='+p+']').val(group[p]);
        }
	}
	$('#group-info-div').show();
}

function removeGroup(group){
	groupArray = $.grep(groupArray, function(index, obj){
		return obj!=group;
	});
	$('#add-group-li').show();
	$('#group-info-div').hide();
}

function validGroup(group, subList){
	if(group.blockCount>0 && group.selectCount>0 && group.selectCount<=group.blockCount){
		if(subList!=undefined && $.isArray(subList) && group.blockCount==subList.length){
			return true;
		}else{
			alert('第'+group.number+'组大题数量与设置不符！');
			return false;
		}
	}else{
		alert('第'+group.number+'组参数设置有误！');
		return false;
	}
}

function validGroupInput(group){
	var result = true;
	if(group.title.length>0){
		group.node.name=group.title;
		treeObject.updateNode(group.node);
	}else{
		group.node.name='选做题组';
		treeObject.updateNode(group.node);
	}
	if(group.selectCount>group.blockCount){
		var inputObj = $('#group-info-div .info-input[name="selectCount"]');
		inputObj.parent().parent().addClass('error');
		inputObj.next('span.help-inline').html('必选个数不能大于块个数');
		result = false;
	}
	return result;
}

function validAllInfo(block){
	var flag=true;
	$('#block-info-div .info-input').each(function(){
		flag = validInfoInput($(this)) && flag;
	});
	$('#block-info-div select').each(function(){
		validInfoInput($(this), block);
	});
	if(flag){
		var totalScore = parseFloat($('#block-info-div input[name="totalScore"]').val());
		var mistake = parseFloat($('#block-info-div input[name="mistakeValue"]').val());
		if(mistake>totalScore){
			var inputObj = $('#block-info-div input[name="mistakeValue"]');
			inputObj.parent().parent().addClass('error');
			inputObj.parent().find('span.help-inline').html('输入内容必须不大于'+totalScore);
			flag=false;
		}
	}
	return flag;
}

function validInfoInput(inputObj, dataObj){
	var name = inputObj.attr('name');
	var value = inputObj.val();
	var min = inputObj.attr('data-min');
	var max = inputObj.attr('data-max');
	var gt = inputObj.attr('data-gt');
	if(inputObj.hasClass('required-input') && value.length==0){
		inputObj.parent().parent().addClass('error');
		inputObj.parent().find('span.help-inline').html('输入内容不能为空');
		return false;
	}
	if(inputObj.hasClass('number-input')){
		if(!$.isNumeric(value)){
			inputObj.parent().parent().addClass('error');
			inputObj.parent().find('span.help-inline').html('输入内容必须为数字');
			return false;
		}
		if(max!=undefined && max.length>0 && value>max){
			inputObj.parent().parent().addClass('error');
			inputObj.parent().find('span.help-inline').html('输入内容必须不大于'+max);
			return false;
		}
		if(min!=undefined && min.length>0 && value<min){
			inputObj.parent().parent().addClass('error');
			inputObj.parent().find('span.help-inline').html('输入内容必须不小于'+min);
			return false;
		}
		if(gt!=undefined && gt.length>0 && value<=gt){
			inputObj.parent().parent().addClass('error');
			inputObj.parent().find('span.help-inline').html('输入内容必须不大于'+gt);
			return false;
		}
		if(dataObj!=undefined){
			eval('dataObj.'+name+'='+value);
		}
	}else{
		if(dataObj!=undefined){
			eval("dataObj."+name+"='"+value+"'");
		}
	}
	inputObj.parent().parent().removeClass('error');
	inputObj.parent().find('span.help-inline').html('');
	return true;
}
</script>