(function(KDApi, $){

	var valueControlList = ['valueBooleanSelectDiv', 'valueTextDiv', 'valueNumberDiv', 'valueEnumSelectDiv', 'valueDateDiv'];
	
    function TestCondition (model) {
        this._setModel(model)
    }

    TestCondition.prototype = {
        _setModel: function(model) {
            this.model = model;
			model.pageDom = $("#" + model.pageId);
        },
        init: function(props){
            initFunc(this.model, props)
        },
        update: function(props){
            updateFunc(this.model, props)
        },
        destoryed: function(){
        }
    }

    // Other Code
    var initFunc = function(model, props) {
        // KDApi.loadFile可以通过路径加载js或css文件，并且在html文件头生成script或者link标签，第一个参数是路径，第二个参数是model，第三个参数是加载完成后执行的回调函数
		KDApi.loadFile(['./js/selectivity-jquery.js','./css/selectivity-jquery.css'], model, function(){
			KDApi.loadFile('./css/testcondition.css', model, function() {
				// 后端插件通过setData传给前端的数据，前端可以通过props.data去获取
				var text = props.data && props.data.text || ''
				// 通过路径去获取html字符串，第一个参数是路径，第二个参数是model，第三个参数是HTML模板中变量的值
				KDApi.getTemplateStringByFilePath('./html/testcondition.html', model, {
					text: text
				}).then(function(data) {
					model.dom.innerHTML = data
					// 绑定DOM事件
					initEvent(model, props)
				})        
			})
		})
    }
	
	//事件绑定
    var initEvent = function(model, props){
		$("#ruletest", model.pageDom).on('click', function(){
			if(!$("#conditionpageap", model.pageDom).hasClass("hidden")){
				var conditionJson = getConditionJson(model);			
				model.invoke("testRuleEvent", conditionJson);
			}
		})
	
		$(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('keydown', '.valueDate:visible', function(){
			return false;
		});
		
		$(model.dom).on('blur', '.valueNumber:visible', function(){
			var value = $(this).val();
			value.replace(/^0*/, "").replace(/^0*\./, "0.");
			$(this).val(value)
		})
		
		$(model.dom).on('click', '.conditionValueSearch:visible', function(){
			var $tr = $(this).parent().parent().parent();
			var index = $tr.index();//从1开始
			model.invoke("openConditionParamF7Event", {entityNumber : getConditionParamValue(model, $tr), index : index, isMulti : true});	
        })
		
		$(model.dom).on('click', '.valueDateDiv:visible', 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);
		});
		
		$("#kd-theme").on("click", '#' + model.pageId + "date .rdtDay", function(){
			setTimeout(function(){
				$("#conditiondate", model.pageDom).find("input").blur(); 
			}, 100);
		})
		
		//点击删除
		$(model.dom).on('click', '.delete:visible', function(){
			$(this).parent().parent().closest("tr").remove();
        })
		
		$('#addCondition', model.dom).click(function(){
            insertCondition(model);
        })
    }

    var updateFunc = function(model, props) {		
		if(props.data){		
			if(props.data.param){	
				model._param = props.data.param;	
				clearCondition(model);
			}
			if(props.data.value){
				updateTextValue(model, props.data.value);
			}
			if(props.data.date){//这个要放最后，防止控件还没初始化完成
				updateDateValue(model, props.data.date);
			}	
		}
    }
	
	var clearCondition = function(model){
		$('#ruleCondition tr:visible', model.dom).remove();
		insertCondition(model);
	}
	
	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 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;
	}
	
	var showValueSearch = function(model, $tr){
		if(getConditionParamType(model, $tr) == 'dynamicObject'){										
			$tr.find(".conditionValueSearch").show();
			$tr.find(".valueText").attr("disabled", true);
		}else{
			$tr.find(".conditionValueSearch").hide();
			$tr.find(".valueText").attr("disabled", false);
		}
	}
	
	var insertCondition = function(model){
		var $tr = $('#templeteTr', model.dom).clone().removeAttr('id').show().css("display","inline-block");
		$('#ruleCondition', model.dom).append($tr);			
		
		createParamControl(model, $tr);
	}
	
	var showControl = function(model, $tr, controlKey){
		$.each(valueControlList, function(i, valueControlKey){
			if(valueControlKey == controlKey){
				$tr.find('.' + valueControlKey).show();
			}else{
				$tr.find('.' + valueControlKey).hide();
			}
		});	
	}
	
	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 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(){
			var $tr = $(this).parent().parent();
			clearValue(model, $tr);
			
			var paramType = getConditionParamType(model, $tr);
			if(isEnum4ParamType(model, $tr)){					
				showEnumSelectDiv(model, $tr);
			}else if(paramType == 'boolean'){	
				showBooleanSelectDiv(model, $tr);
			}else if(paramType == 'date'){
				showDateDiv(model, $tr);
			}else if(paramType == 'number'){
				showNumberDiv(model, $tr);
			}else{
				showTextDiv(model, $tr);
			}
		});
	}
	
	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 clearValue = function(model, $tr){		
		$tr.find(".valueDate").val('');
		$tr.find(".valueBoolean").val('');
		$tr.find(".valueNumber").val('');
		$tr.find(".valueText").val('');
	}
	
	//F7更新值
	var updateTextValue = function(model, data){
		$(".valueText", model.dom).eq(data.index).val(data.idList);
	}
	
	var updateDateValue = function(model, date){
		$(".valueDate", model.dom).eq(model.dateIndex).val(date);
	}
	
	//获取条件的List
	var getConditionJson = function(model){
		var paramTree = {};
		$("#ruleCondition tr:visible", model.dom).each(function(i){
			var key = getConditionParamValue(model, $(this));
			if(key){			
				var value = $(this).find('.valueTd input:visible').val() || $(this).find('.valueTd select:visible').val();
				var keys = key.split(".");
				
				if(keys.length == 1){
					//基本类型或者指标，直接覆盖
					paramTree[keys[0]] = value;
				}else{
					//对象类型，需要转换
					var tempObj = paramTree;
					for(var j=0;j<keys.length-1;j++){
						if(!tempObj[keys[j]]){
							tempObj[keys[j]] = {};				
						}
						tempObj = tempObj[keys[j]];				
					}		
					tempObj[keys[j]] = value || null;
				}
			}
		});		
		return JSON.stringify(paramTree);
	}
	
    KDApi.register('ruletestcondition', TestCondition)
})(window.KDApi, jQuery)
