(function(KDApi, $){

	var LOGIC_OR = ' 或者 ';
	var LOGIC_AND = ' 并且 ';
	var LOGIC_OR_EN = ' or ';
	var LOGIC_AND_EN = ' and ';
	var LEFT_BRACKET = ' ( ';
	var RIGHT_BRACKET = ' ) ';
	var valueControlList = ['valueParamSelectDiv', 'valueBooleanSelectDiv', 'valueTextDiv', 'valueNumberDiv', 'valueEnumSelectDiv', 'valueDateDiv'];
	var valueTypeMap = {"param" : "1", "value" : "2", "target" : "3"}
	
    function Condition (model) {
        this._setModel(model)
    }

    Condition.prototype = {
        _setModel: function(model) {
            this.model = model;
			this.model._conditionExpressList = new Array();
			model.pageDom = $("#" + model.pageId);
        },
        init: function(props){
            initFunc(this.model, props)
        },
        update: function(props){
			if(this.model.dom.innerHTML){
				this.model.init = props.data.init;
				updateFunc(this.model, props)
				this.model.init = "false";
			}            
        },
        destoryed: function(){
        }
    }

    // Other Code
    var initFunc = function(model, props) {
        // KDApi.loadFile可以通过路径加载js或css文件，并且在html文件头生成script或者link标签，第一个参数是路径，第二个参数是model，第三个参数是加载完成后执行的回调函数
		KDApi.loadFile(['./js/codemirror.js','./css/codemirror.css','./js/selectivity-jquery.js','./css/selectivity-jquery.css','./js/jquery-ui.min.js','./css/jquery-ui.min.css'], model, function(){
			KDApi.loadFile('./js/customruleMode.js', model, function () {
				KDApi.loadFile('./css/condition.css', model, function() {
					// 后端插件通过setData传给前端的数据，前端可以通过props.data去获取
					var text = props.data && props.data.text || ''
					// 通过路径去获取html字符串，第一个参数是路径，第二个参数是model，第三个参数是HTML模板中变量的值
					KDApi.getTemplateStringByFilePath('./html/condition.html', model, {
						text: text
					}).then(function(data) {
						model.dom.innerHTML = data
						//因为单选按钮的原因，不能写到html中
						createConditionTypeRadio(model);
						// 绑定DOM事件
						initEvent(model, props)
						//初始化数据
						model.invoke('initConditionControlDataEvent');
					})        
				})
			})
		})
    }

    var updateFunc = function(model, props) {		
		if(props.data){
			if(props.data.conditionExpress){
				createConditionExpress(model, props);
			}			
			if(props.data.param){					
				model._param = props.data.param;	
				model._valueParam = props.data.valueParam;
				
				clearCondition(model);//放到后面，初始化时需要用到param						
			}
			if(!model.comparisonOptMap && props.data.comparisonOpt){
				model.comparisonOptMap = props.data.comparisonOpt;
			}
			if(props.data.value){
				updateTextValue(model, props.data.value);
			}
			if(props.data.date){//这个要放最后，防止控件还没初始化完成
				updateDateValue(model, props.data.date);
			}
			if(props.configItems){
				$.each(props.configItems,function(i, item){
					if(item.key == 'valueType'){//初始化值类型
						initValueType(model, item.value.split(","));
					}
				});
			}		
			if(props.data.data){//这个要放最后，防止控件还没初始化完成
				initControl(model, JSON.parse(props.data.data));
			}
		}
    }
	
	var clearCondition = function(model){	
		$('#ruleCondition tr:visible', model.dom).remove();
		model._conditionExpressList=new Array();
		insertCondition(model);
	}
	
	var initValueType = function(model, itemValue){
		//获取option的值，如果option的值不再value中，remove		
		var valueType = getAllOption4Select(model, "valueType");
		$.each(valueType, function(i, value){
			if($.inArray(value, itemValue) == -1){
				$('.valueType option[value="' + value + '"]', model.dom).remove();
			}
		})
	}
	
	var getAllOption4Select = function(model, selectName){
		var ret = new Array();
		$("#templeteTr ."+selectName+" option", model.dom).each(function(){
			ret.push($(this).val());
		});
		return ret;
	}
	
	var createConditionTypeRadio = function(model){
		var html = "<div class='conditionTypeDiv'><input type='radio' name='conditionType" + model.pageId + "' value='0' checked>满足所有条件（并且）</div>"
			+ "<div class='conditionTypeDiv'><input type='radio' name='conditionType" + model.pageId + "' value='1'>满足任意条件（或者）</div>"
			+ "<div class='conditionTypeDiv'><input type='radio' name='conditionType" + model.pageId + "' value='2'>自定义逻辑</div>";
		$("#conditionTypeRadioDiv", model.dom).append(html);	
	}
	
	var initControl = function(model, data){
		//插入条件
		insertCondition(model, data.conditionList);
		//初始化逻辑连接符
		$("input[name='conditionType" + model.pageId + "'][value='" + data.conditionExpressType + "']", model.dom).attr('checked','true');
		
		//初始化逻辑表达式
		model._conditionExpressList = data.conditionExpressList || new Array();
		updateConditionExpress(model);
	}
	
	var disableInputValue = function(model, $tr){
		$tr.find(".valueType").val(0).attr("disabled",true);
		if($tr.find(".valueParam .selectivity-single-select").length > 0){
			$tr.find(".valueParam").selectivity('value', '').selectivity("setOptions",{"readOnly":true});
		}
		$tr.find(".valueEnum").val('').attr("disabled",true);
		$tr.find(".valueBoolean").val('').attr("disabled",true);
		$tr.find(".valueNumber").val('').attr("disabled",true);
		$tr.find(".valueText").val('').attr("disabled",true);
		$tr.find(".valueDate").val('').attr("disabled",true);
		$tr.find(".value").val('');
		$tr.find(".displayValue").val('');
		$tr.find(".conditionValueSearch").unbind('click');
		$tr.find(".valueDateDiv").unbind('click');
	}
	
	var enableInputValue = function(model, $tr){
		$tr.find(".valueType").attr("disabled",false);
		if($tr.find(".valueParam .selectivity-single-select").length > 0){
			$tr.find(".valueParam").selectivity("setOptions",{"readOnly":false});
		}
		$tr.find(".valueEnum").attr("disabled",false);
		$tr.find(".valueEnum").get(0).selectedIndex=0;
		$tr.find(".valueBoolean").val(1).attr("disabled",false);
		$tr.find(".valueNumber").attr("disabled",false);
		$tr.find(".valueText").attr("disabled",false);
		
		showValueSearch(model, $tr);
		
		$tr.find(".conditionValueSearch").unbind('click').bind('click', function(){
			var $tr = $(this).parent().parent().parent();
			var index = $tr.index();//从1开始
			var valueType = $tr.find(".valueType").val();
			if(valueType == valueTypeMap.value){//值
				var isMulti = $tr.find(".comparisonOpt").val() == "==" || $tr.find(".comparisonOpt").val() == "!=" ? false : true;
				model.invoke("openConditionParamF7Event", {entityNumber : getConditionParamValue(model, $tr), index : index, isMulti : isMulti});	
			}else if(valueType == valueTypeMap.target){//指标
				model.invoke("openConditionTargetF7Event", {paramType : getConditionParamType(model, $tr), index : index});	
			}			
		});
		
		$tr.find(".valueDateDiv").unbind('click').bind('click', function(){
			model.dateIndex = $(this).parent().parent().index();
			$("#conditiondate", $("#" + model.pageId)).find("input").click()
			
			var top = $(this).offset().top + 28;
			var left = $(this).offset().left;
			setTimeout(function(){
				$(".j-left").parent().css("top", top)
				$(".j-left").parent().css("left", left)
				$(".j-left").attr("id", model.pageId + "date")
			}, 50);
		});
	}
	
	var getConditionDisplayParamValue = function(model, $tr){
		return $tr.find(".conditionParam").selectivity('data') && $tr.find(".conditionParam").selectivity('data').text;
	}
	
	var getConditionParamValue = function(model, $tr){
		return $tr.find(".conditionParam").selectivity('value');
	}
	
	var getConditionParamType = function(model, $tr){
		return $tr.find(".conditionParam").selectivity('data') && $tr.find(".conditionParam").selectivity('data').type;
	}
	
	var getConditionParamIsTarget = function(model, $tr){
		return $tr.find(".conditionParam").selectivity('data') && $tr.find(".conditionParam").selectivity('data').target === "true";
	}
	
	var getConditionEnumList = function(model, $tr){
		return $tr.find(".conditionParam").selectivity('data') && $tr.find(".conditionParam").selectivity('data').enumList;
	}
	
	var isEnum4ParamType = function(model, $tr){
		return $tr.find(".conditionParam").selectivity('data') && $tr.find(".conditionParam").selectivity('data').enumList ? true : false;
	}
	
	/**
	 * 1.先获取参数类型
	 *   object:多选/单选切换时，清空值,is_null等操作时，解绑事件，否则绑定事件
	 *   date：is_null等操作时，解绑事件，否则绑定事件
	 *   string：is_null等操作时，解绑事件，否则绑定事件
	 *   number：is_null等操作时，解绑事件，否则绑定事件
	 *   boolean：不影响(只有等于/不等于)
	 *   enum:不影响(只有等于/不等于)
	 */
	var comparisonOptChangeEvent = function(model, $tr, value){
		var paramType = getConditionParamType(model, $tr);
		if(paramType == "boolean"){
			return;
		}
			
		// 天（/^[+-]*\dd$/）、周（/^[+-]*\dw$/）、月（/^[+-]*\dm$/）、季度（/^[+-]*\dq$/）、年（/^[+-]*\dy$/）
		// 过去/未来3个月（/^[+-]*\d+~[+-]*\dm$/）、小于等于今天（<=0d）、大于等于今天（>=0d）
		if("is_not_null" == value || "is_null" == value || /^[+-]*\dd$/.test(value) || /^[+-]*\dw$/.test(value)
			 || /^[+-]*\dm$/.test(value) || /^[+-]*\dq$/.test(value) || /^[+-]*\dy$/.test(value) 
			 || /^[+-]*\d+~[+-]*\dm$/.test(value) || "<=0d" == value || ">=0d" == value){
			disableInputValue(model, $tr);
		}else{
			var mysel = $tr.find(".comparisonOpt");
			var oldvalue = mysel.data("last");//这次改变之前的值
			mysel.data("last", mysel.val()); //每次改变都附加上去，以便下次变化时获取
			var newvalue = mysel.val();
			if(paramType == "dynamicObject"){//object类型多选切换成单选时，清空value值
				if((oldvalue == "==" || oldvalue == "!=") && (newvalue == "in" || newvalue == "not_in")){
					clearValue(model, $tr);
				}
				if((newvalue == "==" || newvalue == "!=") && (oldvalue == "in" || oldvalue == "not_in")){
					clearValue(model, $tr);
				}
			}
			enableInputValue(model, $tr);			
		}	
	}
	
	var showValueSearch = function(model, $tr){
		//显示搜索框（参数类型为object，值类型为值；值类型为指标）
		var paramType = getConditionParamType(model, $tr);
		
		var valueType = $tr.find(".valueType option:selected").val();
		if((paramType == 'dynamicObject' && valueType == valueTypeMap.value) || valueType == valueTypeMap.target){										
			$tr.find(".conditionValueSearch").show();
			$tr.find(".valueText").attr("disabled", true);
		}else{
			$tr.find(".conditionValueSearch").hide();
			$tr.find(".valueText").attr("disabled", false);
		}
	}
	
	var getNextConditionName = function(model){
		var max = 0;
		$("#ruleCondition", model.dom).find(".name:visible").each(function(i){	
			var temp = parseInt($(this).html().replace("T", ""));
			if(temp > max){
				max = temp;
			}
		});
		max = max+1;
		return max < 10 ? "T0" + max : "T" + max;	
	}
	
	var updateConditionExpressListName = function(model){
		$("#ruleCondition", model.dom).find(".name:visible").each(function(i){			
			model._conditionExpressList[i].name = $(this).html();
		});
		updateConditionExpress(model);
	}
	
	//事件绑定
    var initEvent = function(model, props){
		$("#ruleCondition", model.dom).sortable({  
			cursor: "move",  
			items: "tr",                       //只是tr可以拖动  
			opacity: 1.0,                      //拖动时，透明度为0.6  
			revert: false,                      //释放时，增加动画  
			update: function(event, ui) {      //更新排序之后  
				var categoryids = $(this).sortable("toArray");  
				var $this = $(this);  
				//更新expressList
				updateConditionExpressListName(model);
			}  
		});  
		$("#ruleCondition", model.dom).disableSelection(); 
			
		$(model.dom).on('keydown', '.valueDate:visible', function(e){
			return false;
		});
		
		$(model.dom).on('keydown', '.valueNumber:visible', function(e){
			var code = e.keyCode;
			//只允许输入数字和小数点
			if(!((code >= 48 && code<=57) || code== 190 || (code>=96&&code<=105) || code==110 || code==8 || code==37 || code==39 || code==46)){
				return false;
			}
		});
		
		//比较符改变（主要是日期类型需要做特殊处理）
		$(model.dom).on('change', '.comparisonOpt:visible', function(){
			comparisonOptChangeEvent(model, $(this).parent().parent(), $(this).val());
			conditionJsonChange(model);
		});
		
		$("#kd-theme").on("click", '#' + model.pageId + "date .rdtDay", function(){
			setTimeout(function(){
				$("#conditiondate", model.pageDom).find("input").blur(); 
			}, 100);
		})
		
		//值类型改变时，需要显示/隐藏值控件
		$(model.dom).on('change', '.valueType:visible', function(){		
			var $tr = $(this).parent().parent();	
			clearValue(model, $tr);
			
			var valueType = $(this).val();
			if(valueType == valueTypeMap.param){//参数
				showParamSelectDiv(model, $tr);
			}else if(valueType == valueTypeMap.value){//值	
				var paramType = getConditionParamType(model, $tr);
				if(paramType == 'boolean'){					
					showBooleanSelectDiv(model, $tr);
				}else if(isEnum4ParamType(model, $tr)){//枚举和boolean应该是不能切换的，先放着
					showEnumSelectDiv(model, $tr);
				}else if(paramType == 'date'){
					showDateDiv(model, $tr);
				}else if(paramType == 'number'){
					showNumberDiv(model, $tr);
				}else{
					showTextDiv(model, $tr);
				}				
			}else if(valueType == valueTypeMap.target){//指标
				showTextDiv(model, $tr);
			}

			conditionJsonChange(model);			
        })
		
		$(model.dom).on('change', '.valueBoolean:visible', function(){	
			setValue(model, $(this).parent().parent(), $(this).find("option:selected").html(), $(this).val());
		})
		
		$(model.dom).on('change', '.valueEnum:visible', function(){	
			setValue(model, $(this).parent().parent(), $(this).find("option:selected").html(), $(this).val());
		})
		
		$(model.dom).on('blur', '.valueNumber:visible', function(){
			var value = $(this).val();
			value.replace(/^0*/, "").replace(/^0*\./, "0.");
			$(this).val(value)
			setValue(model, $(this).parent().parent(), value, value);
		})
		
		$(model.dom).on('blur', '.valueText:visible', function(){
			setValue(model, $(this).parent().parent(), $(this).val(), $(this).val());
		})
		
		//点击复制
		$(model.dom).on('click', '.copy:visible', function(){
			model.copy = true;
			var $tr = $(this).parent().parent();
			var $tr2 = $tr.clone();
			$tr.after($tr2);
			
			createParamControl(model, $tr2);
			createValueParamControl(model, $tr2);
			$tr2.find(".conditionParam").selectivity('value', $tr.find(".conditionParam").selectivity('value'));
			$tr2.find(".comparisonOpt").val($tr.find(".comparisonOpt").val());
			$tr2.find(".valueType").val($tr.find(".valueType").val());
			if($tr.find(".valueParam").is(":visible")){
				$tr2.find(".valueParam").selectivity('value', $tr.find(".valueParam").selectivity('value'));
			}
			$tr2.find(".valueBoolean").val($tr.find(".valueBoolean").val());
			$tr2.find(".valueEnum").val($tr.find(".valueEnum").val());
			$tr2.find(".valueDate").val($tr.find(".valueDate").val());
			$tr2.find(".valueNumber").val($tr.find(".valueNumber").val());
			$tr2.find(".valueText").val($tr.find(".valueText").val());
			$tr2.find(".displayValue").val($tr.find(".displayValue").val());
			$tr2.find(".value").val($tr.find(".value").val());
			
			var name = getNextConditionName(model);			
			$tr2.find(".name").html(name);
			model._conditionExpressList.push({name:name});
			updateConditionExpress(model);  
			
			model.copy = false;
        })
		
		//点击删除
		$(model.dom).on('click', '.delete:visible', function(){
			$tr = $(this).parent().parent();
			var index = $tr.index();//从1开始,先获取index，再remove
			
			$tr.closest("tr").remove();
			
			model._conditionExpressList.splice(index - 1, 1);
			
			updateConditionExpress(model);      
			//conditionJsonChange(model);
        })
		
		$('#addCondition', model.dom).click(function(){
            insertCondition(model);
        })
		
		$('.expressView', model.dom).bind("click", function(){
			model.invoke("openExpressViewEvent");
        });
		
		$('#and', model.dom).click(function(){
			insertEditorValue(model, LOGIC_AND);
        })
		
		$('#or', model.dom).click(function(){
            insertEditorValue(model, LOGIC_OR);
        })
		
		$('#leftBracket', model.dom).click(function(){
            insertEditorValue(model, LEFT_BRACKET);
        })
		
		$('#rightBracket', model.dom).click(function(){
            insertEditorValue(model, RIGHT_BRACKET);
        })
		
		//逻辑连接符改变时
		$("input[name='conditionType" + model.pageId + "']", model.dom).change(function(){
			var conditionType = $("input[name='conditionType" + model.pageId + "']:checked", model.dom).val();
			var _conditionExpressList = model._conditionExpressList;
			if(conditionType == 0){
				$("#expressDiv", model.dom).hide();
				for(var i=0;i<_conditionExpressList.length-1;i++){//最后一个表达式不需要逻辑连接符
					_conditionExpressList[i].logical = LOGIC_AND_EN;
				}
			}else if(conditionType == 1){
				$("#expressDiv", model.dom).hide();
				for(var i=0;i<_conditionExpressList.length-1;i++){//最后一个表达式不需要逻辑连接符
					_conditionExpressList[i].logical = LOGIC_OR_EN;
				}
			}else{
				$("#expressDiv", model.dom).show();
			}
			updateConditionExpress(model);
			
			//conditionJsonChange(model);
        });	
    }
	
	var setValue = function(model, $tr, displayValue, value){
		$tr.find(".displayValue").val(displayValue);
		$tr.find(".value").val(value);
		
		conditionJsonChange(model);
	}
	
	var clearValue = function(model, $tr){	    
		if($tr.find(".valueParam .selectivity-single-select").length > 0){
			$tr.find(".valueParam").selectivity('value', '');
		}
		
		$tr.find(".valueBoolean").val('');
		$tr.find(".valueNumber").val('');
		$tr.find(".valueDate").val('');
		$tr.find(".valueText").val('');
		$tr.find(".displayValue").val('');
		$tr.find(".value").val('');
	}
	
	var conditionJsonChange = function(model){
		if(model.init !== "true"){
			var conditionJson = JSON.stringify(getConditionContrlJson(model));
			console.log(conditionJson);
			model.invoke("setConditionJsonEvent", conditionJson);
		}
	}
	
	var insertCondition = function(model, conditionList){
		if(conditionList && conditionList.length > 0){
			$('#ruleCondition tr:visible', model.dom).remove();
			for(var i=0;i<conditionList.length;i++){
				var $tr = $('#templeteTr', model.dom).clone().removeAttr('id').show();
				$('#ruleCondition', model.dom).append($tr);				
				createParamControl(model, $tr);
			}
			
			$.each(conditionList, function(i, conditionObj){
				var index = conditionObj.index + 1;
				$tr = $('#ruleCondition tr', model.dom).eq(index);
				$tr.find(".name").html(conditionObj.name);
				
				$tr.find(".conditionParam").selectivity('value', conditionObj.param)	
				
				var paramType = conditionObj.paramType;
				if(paramType != "boolean" && isEnum4ParamType(model, $tr)){
					paramType = "enum";
				}
				//初始化比较符控件并赋值
				createComparisonOptControl(model, $tr, paramType);
				$tr.find(".comparisonOpt").val(conditionObj.operators)
				comparisonOptChangeEvent(model, $tr, conditionObj.operators);
				
				//更新值类型
				$tr.find(".valueType").val(conditionObj.valueType)
				if(conditionObj.valueType == valueTypeMap.param){//参数
					//显示下拉
					showParamSelectDiv(model, $tr);
					$tr.find(".valueParam").selectivity('value', conditionObj.value);
				}else if(conditionObj.valueType == valueTypeMap.value){//值
					//参数初始化时，已经初始化了值控件，故不需要再显示
					if(paramType == "enum"){
						$tr.find(".valueEnum").val(conditionObj.value);
					}else if(paramType == "boolean"){
						$tr.find(".valueBoolean").val(conditionObj.value);
					}else if(paramType == "date"){
						$tr.find(".valueDate").val(conditionObj.value);
					}else if(paramType == "number"){
						$tr.find(".valueNumber").val(conditionObj.value);
					}else{
						$tr.find(".valueText").val(conditionObj.displayValue);
					}	
				}else if(conditionObj.valueType == valueTypeMap.target){//指标
					showTextDiv(model, $tr);
					$tr.find(".valueText").val(conditionObj.displayValue);
					$tr.find(".valueText").data("type", conditionObj.valueRealyType);
				}
				
				$tr.find(".displayValue").val(conditionObj.displayValue)
				$tr.find(".value").val(conditionObj.value)
			});
		}else{
			var tn = getNextConditionName(model);	
			
			var $tr = $('#templeteTr', model.dom).clone().removeAttr('id').show();
			$tr.find(".name").html(tn);
			$('#ruleCondition', model.dom).append($tr);			
			
			createParamControl(model, $tr);
			
			model._conditionExpressList.push({name:tn});
			updateConditionExpress(model);
			
			//conditionJsonChange(model);
		}
	}
	
	var showControl = function(model, $tr, controlKey){
		$.each(valueControlList, function(i, valueControlKey){
			if(valueControlKey == controlKey){
				$tr.find('.' + valueControlKey).show();
			}else{
				$tr.find('.' + valueControlKey).hide();
			}
		});	
	}
	
	var showParamSelectDiv = function(model, $tr){
		showControl(model, $tr, 'valueParamSelectDiv');
		createValueParamControl(model, $tr);
	}
	
	var showNumberDiv = function(model, $tr){
		showControl(model, $tr, 'valueNumberDiv');
	}
	
	var showTextDiv = function(model, $tr){
		showControl(model, $tr, 'valueTextDiv');
		showValueSearch(model, $tr);
	}
	
	var showBooleanSelectDiv = function(model, $tr){
		showControl(model, $tr, 'valueBooleanSelectDiv');
	}
	
	var showEnumSelectDiv = function(model, $tr){
		showControl(model, $tr, 'valueEnumSelectDiv');
		createValueEnumControl(model, $tr);
	}
	
	var showDateDiv = function(model, $tr){
		showControl(model, $tr, 'valueDateDiv');
	}
	
	var contains = function(model, express, n){
		if($(".name:visible", model.dom).eq(n) && express.indexOf($(".name:visible", model.dom).eq(n).html()) != -1){
			return true;
		}
		return false;
	}
	
	//只更新conditionExpressList
	var updateConditionExpressList = function(model){
		var conditionExpress = getEditorValue(model);
		var _conditionExpressList = model._conditionExpressList;
		var expressTemp = new Array();
		var index_or = conditionExpress.indexOf(LOGIC_OR);
		var index_and = conditionExpress.indexOf(LOGIC_AND);	
		var n=0;
		for(var i=0;index_or >= 0 || index_and >= 0;i++){
			if(index_or == 0){
				conditionExpress = conditionExpress.substring(LOGIC_OR.length);
			}else if(index_and == 0){
				conditionExpress = conditionExpress.substring(LOGIC_AND.length);
			}else if(0 < index_or && (index_or < index_and || index_and == -1)){//|在前
				var express = conditionExpress.substring(0, index_or);
				if(contains(model, express, n)){
					n++;
					expressTemp.push(express);					
					_conditionExpressList[i].logical = LOGIC_OR_EN;	
				}		
				conditionExpress = conditionExpress.substring(index_or + LOGIC_OR.length);
			}else if(0 < index_and && (index_and < index_or || index_or == -1)){//&在前
				var express = conditionExpress.substring(0, index_and);
				if(contains(model, express, n)){
					n++;
					expressTemp.push(express);					
					_conditionExpressList[i].logical = LOGIC_AND_EN;	
				}							
				conditionExpress = conditionExpress.substring(index_and + LOGIC_AND.length);
			}
			index_or = conditionExpress.indexOf(LOGIC_OR);
			index_and = conditionExpress.indexOf(LOGIC_AND);
		}
		if(contains(model, conditionExpress, n)){
			expressTemp.push(conditionExpress);
		}		

		$.each(expressTemp, function(i, conditionExpress){			
			_conditionExpressList[i].name = $(".name:visible", model.dom).eq(i).html();
			var bracket = conditionExpress.split(_conditionExpressList[i].name);
			_conditionExpressList[i].leftBracket = bracket[0] || '';			
			_conditionExpressList[i].rightBracket = bracket[1] || '';	
		});
		console.log(_conditionExpressList);
	}
	
	//更新conditionExpressList和conditionExpressStr
	var updateConditionExpress = function(model){
		var conditionExpressStr = '';
		$.each(model._conditionExpressList,function(i, conditionExpress){
			if(conditionExpress.name){
				conditionExpressStr += conditionExpress.leftBracket || '';
				conditionExpressStr += conditionExpress.name || '';
				conditionExpressStr += conditionExpress.rightBracket || '';
				if(i != model._conditionExpressList.length - 1){
					var logical = conditionExpress.logical;
					if(!logical){
						var conditionType = $("input[name='conditionType" + model.pageId + "']:checked", model.dom).val();
						if(conditionType == 1){
							conditionExpress.logical = LOGIC_OR_EN;
						}else{
							conditionExpress.logical = LOGIC_AND_EN;
						}
					}
					conditionExpressStr += conditionExpress.logical;
				}				
			}
		})
		
		setEditorValue(model, conditionExpressStr.replaceAll(LOGIC_AND_EN,LOGIC_AND).replaceAll(LOGIC_OR_EN,LOGIC_OR));
	}
	
	//创建参数控件
	var createParamControl = function(model, $tr){
		var dom = $tr || model.dom;
		$('.conditionParam', dom).selectivity({
			allowClear: true,
			items: model._param
		});
		
		//参数改变时，初始化比较符（可以优化，比较参数类型是否改变）
		$('.conditionParam:visible', dom).unbind('change').on('change', function(){
			if(model.copy){
				return;
			}
			
			var $tr = $(this).parent().parent();
			clearValue(model, $tr);
			
			var paramType = getConditionParamType(model, $tr);
			if($tr.find(".valueType").val() == "2"){				
				if(paramType == 'boolean'){	
					$tr.find(".valueType").val(2).attr("disabled", true);
					showBooleanSelectDiv(model, $tr);
				}else if(isEnum4ParamType(model, $tr)){					
					$tr.find(".valueType").val(2).attr("disabled", true);
					showEnumSelectDiv(model, $tr);
					paramType = "enum";
				}else if(paramType == 'date'){
					$tr.find(".valueType").attr("disabled", false);
					showDateDiv(model, $tr);
				}else if(paramType == 'number'){
					$tr.find(".valueType").attr("disabled", false);
					showNumberDiv(model, $tr);
				}else{
					$tr.find(".valueType").attr("disabled", false);
					showTextDiv(model, $tr);
				}
			}
			
			createComparisonOptControl(model, $tr, paramType, getConditionParamIsTarget(model, $tr));	
			
			conditionJsonChange(model);
		});
	}
	
	//创建比较符控件
	var createComparisonOptControl = function(model, $tr, type, isTarget){
		if(type && type !='undefined'){
			$tr.find(".comparisonOpt").html('<option></option>');//清空	
			$.each(model.comparisonOptMap[type], function(i, comparisonOperator){
				if(!isTarget || (isTarget && (comparisonOperator.value != "is_null" || comparisonOperator.value != "is_not_null"))){
					$tr.find(".comparisonOpt").append("<option value='" + comparisonOperator.value + "'>" + comparisonOperator.name + "</option>");
				}
			});
		}
	}
	
	//创建值参数控件
	var createValueParamControl = function(model, $tr){
		var dom = $tr || model.dom;
		$('.valueParam', dom).selectivity({
			allowClear: true,
			items: model._valueParam
		});
		
		//参数改变时，初始化比较符（可以优化，比较参数类型是否改变）
		$('.valueParam:visible', dom).unbind('change').on('change', function(){		
			if(model.copy){
				return;
			}
			
			var displayValue = $(this).selectivity('data') && $(this).selectivity('data').text || $(this).selectivity('value');
			setValue(model, $(this).parent().parent(), displayValue, $(this).selectivity('value'));			
			conditionJsonChange(model);
		});
	}
	
	var createValueEnumControl = function(model, $tr){
		var enumList = JSON.parse(getConditionEnumList(model, $tr));
		$tr.find('.valueEnum').html('');
		$.each(enumList,function(i, obj){
			$tr.find('.valueEnum').append('<option value ="' + obj.value + '">' + obj.name.zh_CN + '</option>');
		});
	}
	
	//更新值
	var updateTextValue = function(model, data){
		var index = data.index;
		$(".valueText", model.dom).eq(index).val(data.nameList);
		$(".valueText", model.dom).eq(index).data("type", data.valueRealyType);
		$(".displayValue", model.dom).eq(index).val(data.nameList);
		$(".value", model.dom).eq(index).val(data.idList);
		
		conditionJsonChange(model);
	}
	
	var updateDateValue = function(model, date){
		var index = model.dateIndex;
		$(".valueDate", model.dom).eq(index).val(date);
		$(".displayValue", model.dom).eq(index).val(date);
		$(".value", model.dom).eq(index).val(date);
		
		conditionJsonChange(model);
	}
	
	//获取条件的List
	var getConditionList = function(model){
		var conditionList = new Array();
		$("#ruleCondition tr:visible", model.dom).each(function(i){
			var conditionObj = {};
			conditionObj.index = i;
			conditionObj.name = $(this).find(".name").html();		
			conditionObj.displayParam = getConditionDisplayParamValue(model, $(this));
			conditionObj.param = getConditionParamValue(model, $(this));			
			conditionObj.paramType = getConditionParamType(model, $(this));		
			conditionObj.target = getConditionParamIsTarget(model, $(this));		
			conditionObj.operators = $(this).find(".comparisonOpt").val();
			
			var selectValue = $(this).find('.valueTd select:visible').val();
			conditionObj.valueType = $(this).find(".valueType").val();
			if(conditionObj.valueType == "1"){//参数
				conditionObj.valueRealyType = $(this).find(".valueParam").selectivity('data') && $(this).find(".valueParam").selectivity('data').type;
			}else if(conditionObj.valueType == "3"){//指标
				conditionObj.valueRealyType = $(this).find(".valueText").data("type");
			}else{//值
				conditionObj.valueRealyType = getConditionParamType(model, $(this));
			}			
			conditionObj.displayValue = $(this).find(".displayValue").val() || $(this).find('.valueTd select:visible option[value="' + selectValue + '"]').html();			
			conditionObj.value = $(this).find(".value").val() || selectValue;
			conditionList.push(conditionObj);
		});		
		return conditionList;
	}
	
	//条件控件的返回值
	var getConditionContrlJson = function(model){
		var data = {};
		data.conditionList = getConditionList(model);
		data.conditionExpressType = $("input[name='conditionType" + model.pageId + "']:checked", model.dom).val();
		data.conditionExpressList = model._conditionExpressList;		
		data.conditionExpressStr = getEditorValue(model).replaceAll(LOGIC_AND, LOGIC_AND_EN).replaceAll(LOGIC_OR, LOGIC_OR_EN);
		return data;
	}
	
	var createConditionExpress = function (model, props) {
		if(props.data.data && JSON.parse(props.data.data).conditionExpressType == "2"){
			$("#expressDiv", model.dom).show();
		}
		
		var conditionExpressValue = props.data.conditionExpress.value;
		conditionExpressValue = conditionExpressValue.replaceAll(LOGIC_AND_EN, LOGIC_AND).replaceAll(LOGIC_OR_EN, LOGIC_OR);
		
        var propertyKeyWord = ['并且', '或者', '(', ')'];
		  
        var tokenCComment = function (stream, state) {
			var maybeEnd = false; var ch
			while ((ch = stream.next()) != null) {
				if (maybeEnd && ch === '/') {
					state.tokenize = null
					break
				}
				maybeEnd = (ch === '*')
            }
			stream.backUp(1)
            return 'comment'
		}
		  
		var tokenLineComment = function (stream, state) {
            var maybeEnd = false; var ch
            while ((ch = stream.next()) != null) {
				if (maybeEnd && /\n/.test(ch)) {
					state.tokenize = null
					break
				}
				maybeEnd = /\n/.test(ch)
            }
            return 'comment'
		}
		  
		RuleConditionCodeMirror.defineMIME('text/customrule', {
            propertyKeyWord: propertyKeyWord,
            lineComment: '//',
            tokenHooks: {
				'/': function (stream, state) {
					if (stream.eat('/')) return tokenLineComment(stream, state)
					if (!stream.eat('*')) return false
					state.tokenize = tokenCComment
					return tokenCComment(stream, state)
				}
            },
            name: 'customrule'
		})
		  
		model.swcEditor = RuleConditionCodeMirror.fromTextArea($('#conditionExpress', model.dom)[0], {
            value: conditionExpressValue || '',
            lineNumbers: false, // 是否显示行号
            extraKeys: { 'Alt-/': 'autocomplete' }, // 定义自动补全的快捷键
            mode: 'customrule', // 自定义的mode名称
            lineWrapping: 'wrap'
		})
		
		setEditorValue(model, conditionExpressValue)	
		
		model.swcEditor.on("blur",function(){
			updateConditionExpressList(model);
			conditionJsonChange(model);
		});
    }
   
    var insertEditorValue = function (model, value) {	
		var pos = model.swcEditor.getCursor();
		if(!pos.sticky && pos.ch == 0 && pos.line == 0){
			model.swcEditor.setCursor(model.swcEditor.lineCount(), 0);
		}
		model.swcEditor.replaceSelection(value);
		model.swcEditor.focus();
		updateConditionExpressList(model);
		conditionJsonChange(model);
    }
	
    var getEditorValue = function (model) {
		if(model.swcEditor){
			return model.swcEditor.getValue().replace(/\s+/g,' ');//去除多余空格
		}else{
			return "";
		}
    }
	
    var setEditorValue = function(model, value) {
		if(model.swcEditor){
			model.swcEditor.setValue(value)
			model.swcEditor.save()
			conditionJsonChange(model);
		}
    }
	
    // 动态修改公式平台配置
    var setOption = function(property, model, value){
		model.swcEditor.setOption(property, value)
    }
	
    KDApi.register('rulecondition', Condition)
})(window.KDApi, jQuery)
