(function(){
	var tempVersion = new Date().getTime();

	angular.module("app")
	.directive("flipInfo",flipInfo)
	.directive("flipInfoDy",flipInfoDy)
	.directive("selectList",["ToolService",selectList])
	.directive("selectTList",selectTList)
	.directive("selectMoreList",selectMoreList)
	.directive("selectParams",["ToolService",selectParams])
	.directive("delTip",delTip)
	.directive("wincrmTip",wincrmTip)
	.directive("okcrmTip",['ToolService',okcrmTip])
	.directive("stopEvent",stopEvent)
	.directive("minChart",["OptionService","$window","$timeout","HttpService","UtilService","ToolService","$rootScope",minChart])
	.directive("exportButton",["HttpService","UtilService","ToolService","$rootScope",exportButton])
	.directive("ngEnter",ngEnter)
	.directive("popTip",popTip)
	.directive("isLoading",isLoading)
	.directive("dateRange",["ToolService",dateRange])
	.directive("selectChannel",["$state","$rootScope",selectChannel])
	.directive("numberTxt",numberTxt)
	.directive("integerTxt",integerTxt)
	.directive("fixHeader",["$timeout",fixHeader])
	.directive("helpTip",["ToolService","$rootScope",helpTip])
	.directive("helpWinTip",["ToolService","$rootScope","$filter",helpWinTip])
	.directive("noData",[noData])
	.directive("customEvent",["UtilService","ToolService","$timeout","HttpService","$rootScope",customEvent])
	.directive("fileModel",["$parse",fileModel])
	.directive("searchGroup",[searchGroup])
	.directive("bigTable",["$timeout","$compile",bigTable])
	.directive("dragOrder",[dragOrder]);

	function delTip(){
	    return{
	        restrict : "E",
	        replace : true,
	        templateUrl : '/template/common/delwin.html?r='+tempVersion,
	        transclude:true,
	        scope:{
	            delfn:"&",
	            status :"=",
	            okTitle :"@"
	        },
	        link:function($scope,el){
	        	$scope.btnname = $scope.okTitle ? $scope.okTitle : "确定"
	            $scope.hideWin = function(){
	                $scope.status = false;
	            }
	        }
	    }
	}

	function wincrmTip(){
	    return{
	        restrict : "E",
	        replace : true,
	        templateUrl : '/template/common/wincrm.html?r='+tempVersion,
	        transclude:true,
	        scope:{
	            okfn:"&",
	            nofn:"&",
	            title:"@",
	            status :"=",
	            okTitle:"@",
	            noTitle:"@"
	        },
	        link:function($scope,el){
	        	if(angular.isUndefined($scope.okTitle)){
	        		$scope.okTitle = "确定";
	        	}
	        	if(angular.isUndefined($scope.noTitle)){
	        		$scope.noTitle = "取消";
	        	}
	            $scope.hideWin = function(){
	                $scope.status = false;
	                $scope.nofn();
	            }
	            $scope.crmWin = function(){
	            	$scope.status = false;
	            	$scope.okfn();
	            }
	        }
	    }
	}

	function okcrmTip(ToolService){
	    return{
	        restrict : "E",
	        replace : true,
	        templateUrl : '/template/common/okcrm.html?r='+tempVersion,
	        transclude:true,
	        scope:{
	            title:"@",
	            status :"=",
	            okfn : "&"
	        },
	        link:function($scope,el){
	        	$scope.$watch("status",function(n){
	        		if(angular.isDefined(n) && n == true){
	        			ToolService.showAlp();
	        		}
	        	});
	            $scope.crmWin = function(){
	            	$scope.status = false;
	            	ToolService.hideAlp()
	            	$scope.okfn();
	            }
	        }
	    }
	}

	function stopEvent(){
	    return {
	        restrict: "A",
	        link: function($scope, el) {
	            jQuery(el).on("click",function(event){
	                event.stopPropagation();
	            });
	        }
	    }
	};

	function selectList(ToolService){
	    return {
	        restrict: 'E',
	        replace: true,
	        templateUrl: '/template/common/select.html?r='+tempVersion,
	        scope: {
	            meauInfo:'=', //列表数据
	            meauName:"=", //初始name，eg:请选择
	            meauId:"@", //select的id
	            meauId2:"=",//动态ID
	            meauData:"=", //初始选择的id值
	            meauRefresh:"=", //强制刷新下拉框
	            keyname:"@", //显示名
	            keyid:"@",//传递ID
	            meauNull:"=", //置空
	            meauRed:"=", //红色框
	            nosearch:"@", //为true，强制不显示搜索框
	            operationSel:"=", //当前sel可否操作
	            iconType:"@", //true箭头白色
	            meauSpe:"="
	        },
	        link: function($scope,$element) {
	        	// console.log(angular.element($element).getBoundingClientRect().bottom)
	        	// console.log($(".selList").offset().top,$(window).height(),$element.getBoundingClientRect().bottom)
	             $scope.selme = false;
	             $scope.meauId = $scope.meauId || $scope.meauId2;
	             $scope.clickMeau = function(meau){
	             	if(!$scope.operSel || (meau[$scope.keyid]=='pie' && $scope.meauSpe)){
	             		ToolService.showTips("饼状图只适用于有分组的事件分析。");
	             		return false;
	             	}

	             	$scope.currentInfo = meau;
	                $scope.selName = meau[$scope.keyname];
	                $scope.selId = meau[$scope.keyid];
	                $scope.meauRed = false;
	                $scope.$emit($scope.meauId,{info:meau})
	             }
	             $scope.$watch("operationSel",function(n){
	             	if(angular.isUndefined($scope.operationSel)){
		             	$scope.operSel = true;
		            }
		            else{
		            	$scope.operSel = n;
		            }
	             });

	             $scope.showsearch = $scope.nosearch != 'true';
	             if(angular.isUndefined($scope.keyname)){
	             	$scope.keyname = "name";
	             }
	             if(angular.isUndefined($scope.keyid)){
	             	$scope.keyid = "id";
	             }
	             $scope.$watch("meauData+meauName+meauRefresh+meauInfo",function(){
	                if($scope.meauInfo && angular.isDefined($scope.meauData) && $scope.meauData!=-1){
	                    var temp = $scope.meauInfo.filter(function(item){
	                        return item[$scope.keyid] == $scope.meauData;
	                    });
	                    if(temp.length>0){
	                        $scope.clickMeau(temp[0]);
	                    }else{
	                        $scope.selName = $scope.meauName;
	                        $scope.selId = "";
	                    }
	                 }else{
	                    $scope.selName = $scope.meauName;
	                    $scope.selId = "";
	                 }
	             });
	             $scope.$watch("meauNull",function(n){
	             	if(angular.isDefined(n)){
	             		$scope.selName = $scope.meauName;
	             		$scope.selId = "";
	             	}
	             });
	        }
	    }
	};
	//有分类间隔线的下拉框
	function selectTList(){
	    return {
	        restrict: 'E',
	        replace: true,
	        templateUrl: '/template/common/selectT.html?r='+tempVersion,
	        scope: {
	            meauInfo:'=', //列表数据
	            meauName:"=", //初始name，eg:请选择
	            meauId:"@", //select的id
	            meauId2:"=",//动态ID
	            meauData:"=", //初始选择的id值
	            meauType:"=",
	            meauRefresh:"=", //强制刷新下拉框
	            keyname:"@", //显示名
	            keyid:"@",//传递ID
	            meauNull:"=", //置空
	            meauRed:"=", //红色框
	            meauTypekey:"@",
	            meauTypename:"@",
	            operationSel:"=" //当前sel可否操作
	        },
	        link: function($scope,$element) {
	        	 if(angular.isDefined($scope.meauTypekey)){
	        	 	$scope.typeKey = eval($scope.meauTypekey);
	        	 	$scope.typeName = eval($scope.meauTypename);
	        	 }
	        	 $scope.$watch("operationSel",function(n){
	             	if(angular.isUndefined($scope.operationSel)){
		             	$scope.operSel = true;
		            }
		            else{
		            	$scope.operSel = n;
		            }
	             });
	             $scope.selme = false;
	             $scope.meauId = $scope.meauId || $scope.meauId2;
	             $scope.clickMeau = function(meau){
	             	if(!$scope.operSel){return false;}

	                $scope.selName = meau[$scope.keyname];
	                $scope.selId = meau[$scope.keyid];
	                $scope.meauRed = false;
	                $scope.$emit($scope.meauId,{info:meau})
	             }

	             if(angular.isUndefined($scope.keyname)){
	             	$scope.keyname = "name";
	             }
	             if(angular.isUndefined($scope.keyid)){
	             	$scope.keyid = "id";
	             }
	             $scope.$watch("meauData+meauName+meauRefresh+meauInfo",function(){
	                if($scope.meauInfo && angular.isDefined($scope.meauData) && $scope.meauData!=-1){
	                    var temp = $scope.meauInfo.filter(function(item){
	                        return item[$scope.keyid] == $scope.meauData && (item.type == $scope.meauType || !$scope.meauType);
	                    });
	                    if(temp.length>0){
	                        $scope.clickMeau(temp[0]);
	                    }else{
	                        $scope.selName = $scope.meauName;
	                    }
	                 }else{
	                    $scope.selName = $scope.meauName;
	                 }
	             });

	             $scope.haslist = function(type){
	             	if(!$scope.meauInfo){return false;}

	             	var bol  = false;
	             	for(var i=0;i<$scope.meauInfo.length;i++){
	             		if($scope.meauInfo[i].type== type || $scope.meauInfo[i].dimensionType == type){
	             			bol = true;
	             			break;
	             		}
	             	}
	             	return bol;
	             }
	             $scope.$watch("searchlitxt",function(n){
	                 if(angular.isUndefined(n) || !n){return false;}
	                 $scope.virtual = "";
	                 $scope.nature = "";
	                 $scope.meauInfo.filter(function(item){
	                     if(angular.uppercase(item.name).indexOf(angular.uppercase(n))>-1 && item.type=="virtual"){
	                         $scope.virtual = item.type;
	                     }
	                     if(angular.uppercase(item.name).indexOf(angular.uppercase(n))>-1 && item.type=="nature"){
	                         $scope.nature = item.type;
	                     }
	                 });
	             });
	        }
	    }
	};

	//多选
	function selectMoreList(){
	    return {
	        restrict: 'E',
	        replace: true,
	        templateUrl: '/template/common/selectmore.html?r='+tempVersion,
	        scope: {
	            meauInfo:'=', //列表数据
	            meauName:"=", //初始name，eg:请选择
	            meauId:"@", //select的id
	            meauData:"=", //初始选择的id值
	            meauRefresh:"=", //强制刷新下拉框
	            keyname:"@", //显示名
	            keyid:"@",//传递ID
	            meauRed:"="//红色框
	        },
	        link: function($scope,$element) {
	        	 $scope.ischeckall = false;
	        	 $scope.selme = false;

	        	 if(angular.isUndefined($scope.keyname)){
	             	$scope.keyname = "name";
	             }
	             if(angular.isUndefined($scope.keyid)){
	             	$scope.keyid = "id";
	             }

	             $scope.clickMeau = function(meau){
	             	$scope.meauRed = false;
	             	var idx = $scope.selIDS.indexOf(meau[$scope.keyid]);
	             	if(idx>-1){
	             		$scope.selIDS.splice(idx,1);
	             		$scope.selNames.splice(idx,1);
	             		$scope.ischeckall = false;
	             	}else{
	             		$scope.selIDS.push(meau[$scope.keyid]);
	             		$scope.selNames.push(meau[$scope.keyname]);
	             	}
	             }

	             $scope.okSelect = function(){
	             	$scope.$emit($scope.meauId,{info:$scope.selIDS.join(",")});
	             	$scope.selme = false;
	             }
	             $scope.$watch("selme",function(){
	             	if(!$scope.selme && $scope.keyid=='eventName' && $scope.selIDS){
	             		$scope.$emit($scope.meauId,{info:$scope.selIDS.join(",")});
	             	}
	             });
	             $scope.$watch("meauData+meauName+meauRefresh+meauInfo",function(){
	             	$scope.selIDS = [];
	             	$scope.selNames = [];
	             	$scope.ischeckall = false;
	                if($scope.meauInfo && angular.isDefined($scope.meauData) && $scope.meauData!=-1
	                	&& typeof($scope.meauData)=='string'){
	                	var arr = $scope.meauData.split(",");
	                    var temp = $scope.meauInfo.filter(function(item){
	                        return arr.indexOf(item[$scope.keyid])>-1;
	                    });
	                    if(temp.length>0){
	                    	angular.forEach(temp,function(item){
	                    		$scope.clickMeau(item);
	                    	})
	                    }else{
	                        $scope.selName = $scope.meauName;
	                    }
	                 }else{
	                    $scope.selName = $scope.meauName;
	                 }
	             });

	             $scope.checkAll = function(){
	             	$scope.ischeckall = !$scope.ischeckall;
	             	$scope.meauInfo.filter(function(meau){
	             		var idx = $scope.selIDS.indexOf(meau[$scope.keyid]);
		             	if(!$scope.ischeckall && idx>-1){
		             		$scope.selIDS.splice(idx,1);
		             		$scope.selNames.splice(idx,1);
		             	}

		             	if($scope.ischeckall && idx==-1){
		             		$scope.selIDS.push(meau[$scope.keyid]);
		             		$scope.selNames.push(meau[$scope.keyname]);
		             	}
	             	});
	             }
	        }
	    }
	};

	//多选
	function selectParams(ToolService){
	    return {
	        restrict: 'E',
	        replace: true,
	        templateUrl: '/template/common/selectparams.html?r='+tempVersion,
	        scope: {
	            meauInfo:'=', //列表数据
	            meauName:"=", //初始name，eg:请选择
	            meauId:"@", //select的id
	            meauRefresh:"="
	        },
	        link: function($scope,$element) {
	        	$scope.selme = false;
	        	$scope.secondSel = false;
	        	$scope.showSelWin = function(){
	        		$scope.selme = true;
	        		if($scope.selId){
	        			$scope.secondSel = true;
	        		}
	        	}
	            $scope.clickMeau = function(meau){
	            	var w = $($element).find(".optionList:eq(0)").width();
	            	if($scope.selId!=meau.id){
	            		$scope.secIDS = [];
	            		$scope.secKeys = [];
	            	}
	             	$scope.selId = meau.id;
	             	$scope.selN = meau.name;
	             	$scope.evtType = meau.type;

	             	$scope.secondSel = true;
	             	$scope.secondList = meau.value;
	             	$scope.secKeyList = meau.key;
	             	$scope.secondStyle = {left:w+"px"}
	            }
	            $scope.clickSecMeau = function(v,midx){
	            	var idx = $scope.secIDS.indexOf(v);
	            	if(idx>-1){
	            		$scope.secIDS.splice(idx,1);
	            		if($scope.secKeyList){
	            			$scope.secKeys.splice(idx,1);
	            		}
	            	}else{
	            		$scope.secIDS.push(v);
	            		if($scope.secKeyList){
	            			$scope.secKeys.push($scope.secKeyList[midx]);
	            		}
	            	}
	            }
	            $scope.okSelect = function(){
	            	var pv = "";
	            	if($scope.selId && $scope.selId != ""){
	            		var pas = {};

	            		if($scope.secIDS.length == 0 || $scope.secIDS.length>10){
	            			ToolService.showTips("请选择10个以内对比属性值");
	            			return false;
	            		}
	            		if($scope.secKeyList){
	            			pas[$scope.selId] = $scope.secKeys.join(",");
	            		}
	            		else{
	            			pas[$scope.selId] = $scope.secIDS.join(",");
	            		}

	            		pas.type = $scope.evtType;
	            		pv = JSON.stringify(pas);

	            		// $scope.selName = $scope.selN + "=" + $scope.secIDS.join(",");
	            		$scope.selName = $scope.selN;
	            	}else{
	            		$scope.selName = $scope.meauName;
	            	}
	            	$scope.$emit($scope.meauId,{info:pv,name:$scope.selN});

	            	$scope.selme = false;
	        		$scope.secondSel = false;
	            }
	            $scope.$watch("meauName+meauInfo+meauRefresh",function(){
	                if($scope.meauInfo){
	                    $scope.secIDS = [];
	                    $scope.secondList = [];
	                    $scope.selId = "";
	        			$scope.secondSel = false;
	                }
	                $scope.selName = $scope.meauName;
	            });

	            angular.element(document).on("click",function(){
	            	$scope.$apply(function(){
	            		$scope.selme=false;
	            		$scope.secondSel=false;
	            	});
	            });
	        }
	    }
	};

	//分页
	function flipInfo(){
	    return {
	        restrict : "E",
	        replace : true,
	        templateUrl : '/template/common/flipinfo.html?r='+tempVersion,
	        scope:{
	            listInfo:"=", //数据数组
	            searchTxt:"=",//搜索值
	            searchName:"@",//匹配字段
	            listKey:"@", //列表key，用于同一个页面多个翻页区分
	            searchKey:"=", //匹配字段,scope动态
	            listRefresh:"=" //排序跳转到第一页
	        },
	        link:function($scope,el){
	            $scope.everyId = "everyId";
	            $scope.everyList = [
	                {"id":10,"name":"每页10条"},
	                {"id":20,"name":"每页20条"},
	                {"id":30,"name":"每页30条"}
	            ];
	            $scope.minNum = $scope.everyInit = $scope.everyList[0].id;
	            $scope.$on($scope.everyId,function(e,msg){
	                var num = msg.info.id;
	                if(num == 'all'){
	                    $scope.everyNum = $scope.listInfo.length;
	                }else{
	                    $scope.everyNum = num;
	                }
	            });

	            $scope.page = {};
	            $scope.$watch("listInfo+everyNum",function(n){
	                if(angular.isDefined($scope.listInfo)){
	                    var totalLen = 0;
	                    if(angular.isDefined($scope.searchTxt) && $scope.searchTxt!=''){
	                    	totalLen = $scope.filterCurList.length;
	                    }
	                    else{
	                    	totalLen = $scope.listInfo.length;
	                    }
	                    $scope.refreshInfos(totalLen);
	                }
	            });

	            //模糊搜索的时候，重新记录翻页数据
	            $scope.$watch("searchTxt",function(n){
	                if(angular.isDefined(n) && $scope.listInfo){
	                	$scope.searchN = $scope.searchName || $scope.searchKey;
			            if(angular.isDefined($scope.searchN)){
			            	$scope.searchNames = $scope.searchN.split(",");
			            }
	                    var infos = $scope.listInfo.filter(function(item){
	                    	var has = false;
	                    	for(var i=$scope.searchNames.length-1;i>=0;i--){
	                    		if(item[$scope.searchNames[i]] && angular.uppercase(String(item[$scope.searchNames[i]])).indexOf(angular.uppercase(n))>-1){
	                    			has = true;
	                    			break;
	                    		}
	                    	}
	                    	return has;
	                    });
	                    $scope.filterCurList = infos;
	                    $scope.refreshInfos(infos.length);
	                };
	            });

	            $scope.refreshInfos = function(totalLen){
	                var emitnum = $scope.everyNum ? $scope.everyNum :  $scope.everyInit;

	                $scope.page.totals = totalLen; //总条数
	                $scope.page.totalpages = Math.ceil($scope.page.totals/emitnum); //总页数
	                $scope.page.curpage = 1;//当前页

	                $scope.sendData();
	            }

	            $scope.goto = function(flag,p){
	                switch(flag){
	                    case 0: //跳转
	                        $scope.page.curpage = p;
	                        break;
	                    case 2: //上一页
	                        if($scope.page.curpage > 1){
	                            $scope.page.curpage --;
	                        }
	                        break;
	                    case 3://下一页
	                        if($scope.page.curpage < $scope.page.totalpages){
	                            $scope.page.curpage ++;
	                        }
	                        break;
	                    case 4: //末页
	                        $scope.page.curpage = $scope.page.totalpages;
	                        break;
	                    case 5://跳转
	                    	if($scope.gonum!='' && angular.isNumber($scope.gonum) && $scope.gonum <= $scope.page.totalpages){
	                    		$scope.page.curpage = $scope.gonum;
	                    	}
	                    	else{
	                    		$scope.gonum = '';
	                    	}
	                        break;
	                    default:
	                        break;
	                }
	                $scope.sendData();
	            }

	            $scope.$watch("page.curpage",function(n){
	            	if(angular.isDefined(n)){
	            		$scope.gonum = n;
	            	}
	            });
	            $scope.$watch("listRefresh",function(n){
	            	if(angular.isDefined(n)){
	            		$scope.goto(0,1);
	            	}
	            });

	            $scope.sendData = function(){
	                var start = ($scope.page.curpage -1) * $scope.everyNum - 1;
	                var end = $scope.page.curpage * $scope.everyNum;

	                $scope.$emit("flipinfo",{start:start,end:end,listkey:$scope.listKey,pagen:$scope.everyNum});
	            }
	        }
	    }
	}

	//动态分页
	function flipInfoDy(){
	    return {
	        restrict : "E",
	        replace : true,
	        templateUrl : '/template/common/flipinfody.html?r='+tempVersion,
	        scope:{
	            totalNum:"=", //总条数
	            listKey:"@", //列表key，用于同一个页面多个翻页区分
	            listRefresh:"=" //排序跳转到第一页
	        },
	        link:function($scope,el){
	            $scope.everyId = "everyId";
	            $scope.everyList = [
	                {"id":20,"name":"每页20条"},
	                {"id":50,"name":"每页50条"},
	                {"id":100,"name":"每页100条"}
	            ];
	            $scope.minNum = $scope.everyInit = $scope.everyList[0].id;
	            $scope.$on($scope.everyId,function(e,msg){
	                var num = msg.info.id;
	                if(num == 'all'){
	                    $scope.everyNum = $scope.totalNum;
	                }else{
	                    $scope.everyNum = num;
	                }
	            });

	            $scope.page = {};
	            $scope.$watch("totalNum+everyNum+listRefresh",function(n){
	                if(angular.isDefined($scope.totalNum)){
	                    $scope.refreshInfos($scope.totalNum-1);
	                }
	            });

	            $scope.refreshInfos = function(totalLen){
	                var emitnum = $scope.everyNum ? $scope.everyNum :  $scope.everyInit;
	                $scope.page.totals = totalLen; //总条数
	                $scope.page.totalpages = Math.ceil($scope.page.totals/emitnum); //总页数
	                $scope.page.curpage = 1;//当前页

	                $scope.sendData();
	            }

	            $scope.goto = function(flag,p){
	            	var dis = false;
	                switch(flag){
	                    case 0: //跳转
	                    	if($scope.page.curpage == p){
	                    		dis = true;
	                    	}
	                        $scope.page.curpage = p;
	                        break;
	                    case 2: //上一页
	                    	if($scope.page.curpage==1){
	                    		dis = true;
	                    	}
	                        if($scope.page.curpage > 1){
	                            $scope.page.curpage --;
	                        }
	                        break;
	                    case 3://下一页
	                    	if($scope.page.curpage == $scope.page.totalpages || $scope.page.totalpages<=1){
	                    		dis = true;
	                    	}
	                        if($scope.page.curpage < $scope.page.totalpages){
	                            $scope.page.curpage ++;
	                        }
	                        break;
	                    case 4: //末页
	                    	if($scope.page.curpage == $scope.page.totalpages){
	                    		dis = true;
	                    	}
	                        $scope.page.curpage = $scope.page.totalpages;
	                        break;
	                    case 5://跳转
	                    	if($scope.gonum!='' && angular.isNumber($scope.gonum) && $scope.gonum <= $scope.page.totalpages){
	                    		if($scope.page.curpage == $scope.gonum){
	                    			dis = true;
	                    		}
	                    		$scope.page.curpage = $scope.gonum;
	                    	}
	                    	else{
	                    		$scope.gonum = '';
	                    	}
	                        break;
	                    default:
	                        break;
	                }
	                if(!dis){
	                	$scope.sendData();
	                }
	            }

	            $scope.$watch("page.curpage",function(n){
	            	if(angular.isDefined(n)){
	            		$scope.gonum = n;
	            	}
	            });

	            $scope.sendData = function(){
	                $scope.$emit("flipinfo",{current:$scope.page.curpage,pagenum:$scope.everyNum,listkey:$scope.listKey});
	            }
	        }
	    }
	}

 	var exportTips = "导出成功，请到数据导出-下载报表处进行下载",
 		expTimeTips = "请1分钟后再点",expLimitTime = 1000 * 60;
 	function minChart(OptionService,$window,$timeout,HttpService,UtilService,ToolService,$rootScope){
	    return{
	        restrict : "E",
	        replace : true,
	        templateUrl : '/template/common/chart.html?r='+tempVersion,
	        scope:{
	            chartTitle:"@", //图描述标题
	            chartData :"=", //图数据
	            chartType:"@", //图类型
	            chartTp:"=",
	            chartConfig:"=",
	            chartLoading:"=",
	            chartResize:"@", //yes需要重新resize
	            chartCondition:"=",
	            chartBack:"="//回传显示数值
	        },
	        link:function($scope,el){
	            var chartInstance = echarts.init($(el).find(".chartInfo").get(0));

	            $scope.$watch("chartLoading",function(){
	                if($scope.chartLoading == true){
	                    // chartInstance.showLoading();
	                }
	            });
	            var predate = 0;
	            $scope.$watch("chartData",function(){
	                if(angular.isUndefined($scope.chartData)){
	                    return false;
	                }
	                predate = 0;
	                $scope.chartType = $scope.chartTp || $scope.chartType;
	                var options = null;
	                if($scope.chartType == 'funnel'){
	                	var bw = $(el).find(".chartInfo").width();
	                	$scope.chartConfig.barwidth = bw;
	                }

	                // if(angular.isDefined($scope.chartTp)){
	                	chartInstance.clear();
	                // }
	                if($scope.chartType == 'pie'){
	                	options = OptionService.getPieOption($scope.chartData,$scope.chartType,$scope.chartConfig || {});
	                }
	                else if($scope.chartType == 'map'){
	                	options = OptionService.getMapOption($scope.chartData,$scope.chartType,$scope.chartConfig || {});
	                }
	                else{
	                	options = OptionService.getOption($scope.chartData,$scope.chartType,$scope.chartConfig || {});
	                }

	                if($scope.chartType == 'funnel' && $scope.chartConfig.barwidth==0){

	                }else{
	                	chartInstance.setOption(options);
	                	var bw = $(el).find(".chartInfo").width();
	                	if($scope.chartResize && $scope.chartResize=='yes'){
	                		chartInstance.resize();
	                	}
	                	else if(bw == 0){
	                		$timeout(function(){
				                chartInstance.resize();
			                },500);
	                	}
	                }

	                $timeout(function(){
	                	if($scope.chartType == 'funnel' && $scope.chartConfig.barwidth == 0){
                			var bw = $(el).find(".chartInfo").width();
	                		$scope.chartConfig.barwidth = bw;
	                		options = OptionService.getOption($scope.chartData,$scope.chartType,$scope.chartConfig || {});
               				chartInstance.setOption(options);
		                }
		                chartInstance.resize();
	                },200);
	                chartInstance.hideLoading();

	                angular.element($window).bind('resize', function(){
	                    chartInstance.resize();
	                });
	                //菜单伸缩
	                $scope.$on("conentresize",function(){
	                	$timeout(function(){
			                chartInstance.resize();
		                },50);
		        	});
	            },true);

	            $scope.isChart = true;
	            $scope.changeChart = function(bol){
	            	$scope.isChart = bol;
	            	if(bol){
	            		$timeout(function(){
	            			chartInstance.resize();
	            		},100);
	            	}
	            }

	            $scope.exportData = function(){
	            	var nowdate = new Date().getTime();
	            	if(predate>0){
	            		if(nowdate - predate <= expLimitTime){
	            			predate = nowdate;
	            			ToolService.showTips(expTimeTips);
	            			return false;
	            		}
	            	}
	            	predate = nowdate;
	            	ToolService.showLoading();
	            	var expPM = HttpService.postInfo("mng/export/report/"+$scope.chartCondition.app+"/generatefile",$scope.chartCondition);
	            	expPM.then(function(data){
	            		ToolService.hideLoading();
	            		ToolService.showTips(exportTips);
	            	});
	            }
	        }
	    }
	}
	//列表导出
	function exportButton(HttpService,UtilService,ToolService,$rootScope){
		return {
            restrict: "E",
            transclude: true,
            replace:true,
             templateUrl : '/template/common/export.html?r='+tempVersion,
            scope:{
                exportCondition:"="
            },
            link: function($scope, el) {
            	$scope.style1 = {"float":"right","margin-top":"11px","margin-right":"10px"};
            	var predate = 0;
            	$scope.$watch("exportCondition",function(){
            		predate = 0;
            	});
                $scope.exportData = function(){
                	var nowdate = new Date().getTime();
	            	if(predate>0){
	            		if(nowdate - predate <= expLimitTime){
	            			predate = nowdate;
	            			ToolService.showTips(expTimeTips);
	            			return false;
	            		}
	            	}
	            	predate = nowdate;
                	ToolService.showLoading();
		            var expPM = HttpService.postInfo("mng/export/report/"+$scope.exportCondition.app+"/generatefile",$scope.exportCondition);
		            expPM.then(function(data){
		            	ToolService.hideLoading();
		                ToolService.showTips(exportTips);
		            });
		        }


            }
        }
	}

	function ngEnter(){
		return function (scope, element, attrs) {
	        element.bind("keydown keypress", function (event) {
	            if(event.which === 13) {
	                scope.$apply(function (){
	                    scope.$eval(attrs.ngEnter);
	                });

	                event.preventDefault();
	            }
	        });
	    };
	}

	function selectChannel($state,$rootScope){
		 return{
	        restrict : "E",
	        replace : true,
	        templateUrl : '/template/common/channel.html?r='+tempVersion,
	        scope:{
	            channelList:"=", //渠道列表
	            appOs:"=",//游戏操作类型
	            type:"="//是否为H5类型
	        },
	        link:function($scope,el){
	        	$scope.isSuper = $rootScope.isSuper;
	        	if($scope.type){
	        		$scope.channType = null;
	        	}else{
	        		$scope.channType = "ry_coop";
	        	}
	        	$scope.category = 'ADVERTISING';
		        $scope.letter = "";

		        $scope.popchannellist = false;
		        angular.element(el).parent().bind("click",function(){
		        	$scope.$broadcast("popchannel",{});
		        	$scope.$apply();
		        });

		        $scope.$on("popchannel",function(){
		        	$scope.popchannellist = true;
		        });

	        	$scope.$watch("appOs",function(n){
	        		if(angular.isDefined(n)){
	        			$scope.appplattype = n;
	        		}
	        	});

	        	$scope.changeType = function(type){
	        		$scope.channType = type;
	        		$scope.category = 'ADVERTISING';
	        		$scope.letter = "";
	        	};

	        	$scope.$watch("channType+appplattype+channelList+category",function(n){
	        		if(angular.isDefined($scope.channelList) && angular.isDefined($scope.appplattype) && angular.isDefined($scope.category)){
	        			if($scope.appplattype==2){
	        				if($scope.channType!='ry_bd'){
	        					$scope.curChannelList = $scope.channelList.filter(function(channel){
			        				return channel.type == $scope.channType && channel.osAndroid && channel.category == $scope.category;
			        			});
	        				}
	        				else{
	        					$scope.curChannelList = $scope.channelList.filter(function(channel){
			        				return channel.type == $scope.channType && channel.osAndroid;
			        			});
	        				}

	        			}
	        			else if($scope.appplattype==1){
	        				$scope.curChannelList = $scope.channelList.filter(function(channel){
		        				return channel.type == $scope.channType && channel.osIos && channel.category == 'ADVERTISING';
		        			});
	        			}else{
	        				$scope.curChannelList = $scope.channelList.filter(function(channel){
		        				return channel.type == $scope.channType && channel.osWeb;
		        			});
	        			}

	        		}
	        	});


	        	$scope.clickChannel = function(channel){
	        		$scope.$emit("curchannel",{info:channel});
	        		$scope.curchid = channel.id;
	        		$scope.popchannellist = false;
	        	}

	        	$scope.goChannel = function(){
	        		$state.go("collect.channel");
	        	}
	        }
	    };
	}

	function popTip(){
		return {
            restrict: "E",
            transclude: true,
            replace:true,
            template:'<div class="opIcon p" ng-mouseleave="showtip=false" style="height:30px;"><span ng-transclude  ng-click="clickTip()"></span><div class="poptips" ng-show="showtip"><div class="poparrow"></div>{{tipinfo}}</div></div>',
            scope:{
                tipinfo:"="
            },
            link: function($scope, el) {
                $scope.showtip = false;

                $scope.clickTip = function(){
                    $scope.showtip = !$scope.showtip;
                }
            }
        }
	}

	function isLoading(){
		return {
            restrict: "E",
            replace:true,
            templateUrl : '/template/common/loading.html?r='+tempVersion,
            scope:{
                doLoading:"="
            },
            link: function($scope, el) {
            	$scope.myLoading = false;
                $scope.$watch("doLoading",function(n){
                	if(angular.isDefined(n)){
                		$scope.myLoading = n;
                	}
                });
            }
        }
	}

	function noData(){
		return {
            restrict: "E",
            replace:true,
            templateUrl : '/template/common/nodata.html?r='+tempVersion,
            scope:{

            },
            link: function($scope, el) {

            }
        }
	}

	function dateRange(ToolService){
		return {
            restrict: "E",
            replace:true,
            templateUrl : '/template/common/daterange.html?r='+tempVersion,
            scope:{
                nodrange:"@",
                noToday:"@",
                datekey:"@",
                maxRange:"@"
            },
            link: function($scope, el) {
            	if(angular.isUndefined($scope.nodrange)){
        			$scope.nodrange = false;
        		}

        		if(ToolService.isDemoUser()){
        			$scope.nodrange = true;
        		}

        		if(angular.isUndefined($scope.noToday)){
					$scope.noToday = true;
        		}
        		else{
        			$scope.noToday = $scope.noToday!='false' && $scope.noToday!=false;
        		}

            	if(angular.isUndefined($scope.datekey)){
        			$scope.datekey = "curdate";
        		}


        		var today = ToolService.getToday(),yesDay = ToolService.getYesDay();
            	$scope.changeDate = function(flag){
		            switch (flag){
		                case 'today':
		                    $scope.subfix = "hour";
		                    $scope.mydate = today;
		                    break;
		                case 'yesday':
		                    $scope.subfix = "hour";
		                    $scope.mydate = yesDay;
		                    break;
		                case 'd7':
		                    $scope.subfix = "ds";
		                    $scope.mydate = ToolService.getLastDays(-7,0);
		                    break;
		                case 'd14':
		                    $scope.subfix = "ds";
		                    $scope.mydate = ToolService.getLastDays(-14,0);
		                    break;
		                case 'd30':
		                    $scope.subfix = "ds";
		                    $scope.mydate = ToolService.getLastDays(-30,0);
		                    break;
		                default:
		                    break;
		            }
		            $scope.timeflag = flag;
		        }

		        $scope.maxDay = 0;
		        if($scope.noToday==true){
		        	$scope.changeDate('yesday');
		        	$scope.maxDay = -1;
		        }else{
		        	$scope.changeDate('today');
		        }
		        $scope.myrangeday = $scope.maxRange;

		        $scope.$on("dateCustos",function(e,msg){
		        	if(msg.startDate == msg.endDate && msg.startDate == today.startDate){
		        		$scope.timeflag = "today";
		        		$scope.subfix = "hour";
		        	}
		        	else if(msg.startDate == msg.endDate && msg.startDate == yesDay.startDate){
		        		$scope.timeflag = "yesday";
		        		$scope.subfix = "hour";
		        	}
		        	else{
		        		$scope.timeflag = msg.dateflag;
		        		$scope.subfix = "ds";
		        	}
		            $scope.mydate = msg;
		        });

		        $scope.$watch("mydate",function(n){
		        	if(angular.isDefined(n)){
		        		$scope.datestr = $scope.mydate.startDate + "至" + $scope.mydate.endDate;

		        		$scope.$emit($scope.datekey,{date:$scope.mydate,subfix:$scope.subfix,timeflag:$scope.timeflag})
		        	}
		        },true);
            }
        }
	}

	//输入框只能输入数字和小数点
	function numberTxt(){
		return {
            restrict: "A",
            link: function($scope, el) {
            	el.bind("keydown",function(event){
            		event = window.event || event;
            		if((event.keyCode>=48 && event.keyCode<=57) || (event.keyCode>=96 && event.keyCode<=105) || event.keyCode==8 || event.keyCode==190){

            		}else{
            			event.preventDefault();
            		}
            	})
            	.bind("input propertychange",function(){
            		// var v = $(el).val().replace(/[^\x00-\x80A-Za-z]/gi,"");
            		// $(el).val(v);
            	});
            }
        }
	}
	//输入框只能输入数字
	function integerTxt(){
		return {
            restrict: "A",
            link: function($scope, el) {
            	el.bind("keydown",function(event){
            		event = window.event || event;
            		if((event.keyCode>=48 && event.keyCode<=57) || (event.keyCode>=96 && event.keyCode<=105) || event.keyCode==8){

            		}else{
            			event.preventDefault();
            		}
            	})
            	.bind("input propertychange",function(){
            		var v = $(el).val().replace(/\D/g,"");
            		$(el).val(v);
            	});
            }
        }
	}

	function helpTip(ToolService,$rootScope){
		return {
            restrict: "E",
            replace:true,
            scope:{
            	name:"@",
            	dname:"=",
            	dn2:"=",
            	hidx:"@",
            	red:"="
            },
            templateUrl : '/template/common/helptip.html?r='+tempVersion,
            link: function($scope, el) {
            	$scope.showtip=false;
            	var hidx = $scope.hidx ? $scope.hidx : 2;
            	$scope.spanStyle = {"z-index":hidx};

            	var now = $(el).find(".helpTipWrap"),zIdx = Number($(el).parent().css("z-index"));
            	now.hide();
            	$scope.showTip = function(){
            		zIdx = Number($(el).parent().css("z-index"));
            		if(angular.isNumber(zIdx)){
        				$(el).parent().css("z-index",zIdx+1);
        			}
        			$(".helpTipWrap").not(now).parent().parent().css("z-index",zIdx);
            		$(".helpTipWrap").not(now).hide().animate({opacity:0});
            		now.show().animate({opacity:1},100,'linear');
            	}
            	angular.element(document).on("click",function(){
            		if(angular.isNumber(zIdx)){
	            		now.parent().parent().css("z-index",zIdx);
	            	}
	            	now.animate({opacity:0}).hide();
	            });

	            $scope.$watch('name+dname+dn2',function(n){
	            	var name = $scope.name ? $scope.name : $scope.dname;
	            	if(angular.isDefined($scope.dn2)){
	            		name += $scope.dn2;
	            	}

	            	if(angular.isDefined(name)){
	            		$scope.tipname = name;
	            		$scope.tipcontent = ToolService.getMenuTip($scope.tipname);
	            	}
	            });

	            $rootScope.$watch("currentPageTips",function(){
	            	$scope.tipcontent = ToolService.getMenuTip($scope.tipname);
	            });
            }
        }
	}

	function helpWinTip(ToolService,$rootScope,$filter){
		return {
            restrict: "E",
            scope:{
            	name:"@",
            	dname:"=",
            	zIndex:"=",
            	titlev:"@",
            	helpw:"@"
            },
            replace:true,
            template : '<span ng-click="showTip()" title="{{titlev}}" stop-event></span>',
            link: function($scope, el) {
            	angular.element(document).on("click",function(){
            		 $("#winTC").hide();
	            });
	            $scope.showTip = function(){
	            	var name = $scope.name ? $scope.name : $scope.dname;

	            	var offset = $(el).offset(),
	            		left = offset.left,
	            		top = offset.top
	            		h = $(el).innerHeight(),
	            		w = $(el).innerWidth(),
	            		winWidth = $(window).width();

	            	top = Math.ceil(top + h);

	            	var cssStyle = {top:top,'display':'block',opacity:1},winObj = $("#winTC");
	            	if($scope.zIndex){
	            		winObj.css("z-index",$scope.zIndex);
	            	}
	            	if($scope.helpw){
	            		winObj.css("width",$scope.helpw+"px");
	            	}
	            	else{
	            		winObj.css("width","200px");
	            	}
	            	if($(el).hasClass("rightTip")){
	            		winObj.addClass("rightPosition");
	            		left =  Math.ceil(left - winObj.innerWidth() + w);
	            	}
	            	else{
	            		winObj.removeClass("rightPosition");
	            	}
	            	if(winWidth-left<200){
	            		winObj.addClass("rightPosition");
	            		left =  Math.ceil(left - winObj.innerWidth() + w);
	            	}
	            	cssStyle.left = left;
	            	winObj.html(ToolService.getMenuTip(name)).css(cssStyle);
	            }
            }
        }
	}

	/*固定首行or首列*/
   function fixHeader($timeout) {
        return {
            restrict: "A",
            scope:{
                titleName:"=", //动态表头列表
                fixFirtd:"@", //固定首列
                fixList:"=" //列表数据
            },
            link: function($scope, el) {

                var obj = $(el),p = obj.parent(),fixTd = 0,firTds = null,zidx = 1;
                //固定首列
                if(angular.isDefined($scope.fixFirtd)){
                    fixTd = Number($scope.fixFirtd);
                    zidx = 2;
                }
                //固定首行
                $scope.$watch("titleName",function(){
                    $timeout(function() {
                        obj.find("thead th").css({"position":"relative","z-index":zidx});
                        p.scroll(function(){
                            var t = $(this).scrollTop();
                            if(t>5){t--;}
                            obj.find("thead th").css({"top":t+"px"});
                        });

                    });
                });

                //固定首列
                if(fixTd>0){
                    $scope.$watch("fixList",function(){
                        $timeout(function() {
                            firTds = obj.find("tr td:nth-child("+fixTd+")");
                            firTds.css({"position":"relative","z-index":1});
                            p.scroll(function(){
                                var l = $(this).scrollLeft();
                                if(l > 5){l-=2;}
                                firTds.css({"left":l+"px"});
                            });
                        });
                    });
                }
            }
        }
    };

    //看单事件
    function customEvent(UtilService,ToolService,$timeout,HttpService,$rootScope){
    	return {
            restrict: "E",
            replace:true,
            templateUrl : '/template/common/custom.html?r='+tempVersion,
            scope:{
                type:"=", //报表类型，1事件分析，2留存分析，3漏斗分析
                eventList:"=",//事件列表
                oldInfo:"="//初始化事件详情
            },
            link: function($scope, el) {
            	var rmd = new Date().getTime();
            	$scope.$watch("oldInfo",function(e){
            		if(angular.isDefined($scope.oldInfo)){
            			if($scope.type == 'eventstats'){
            				$scope.changeEvent(null,$scope.oldInfo);
            			}
            			else{
            				$scope.eventInfo = [],evts = [],evtvals = [];

		                    $scope.oldInfo.filter(function(item){
		                        var temp = {event:item.event,param:[]};
		                        var pppm = UtilService.cloneJSON(item.params);
		                        pppm.filter(function(pm){
		                            temp.param.push(pm.attr);
		                        });
		                        evts.push(item.event);
		                        evtvals.push(temp);
		                    });
		                    ToolService.showLoading();
		                    var evtprofilePM = HttpService.getInfo($rootScope.appid+"/event/find/param?names="+evts.join(",")+"&params="+JSON.stringify(evtvals));
		                    evtprofilePM.then(function(pros){
		                        pros.filter(function(evt){
		                            for(var i=0;i<$scope.eventList.length;i++){
		                                if(evt.eventName == $scope.eventList[i].eventName){
		                                    $scope.eventList[i].profiles = evt.profiles;
		                                    break;
		                                }
		                            }
		                        });
		                        $scope.oldInfo.filter(function(e){
		                            e.oldparams = UtilService.cloneJSON(e.params);
		                            delete e.params;
		                            $scope.addEvent(e);
		                        });
		                        ToolService.hideLoading();
		                    });
            			}
            		}
            	});

            	$scope.$on("eventId",function(e,msg){
		            $scope.changeEvent(msg.info);
		        });
            	$scope.initEvent = function(){
		            $scope.eventinitname = "全部事件";
		            $scope.eventInit = 0 - rmd;

		            $scope.event = {};
		            $scope.propertyList = [];
		            $scope.sumtypeList = [];
		        }
            	$scope.changeEvent = function(event,obj){

		            if(obj){ //编辑查找
		            	$scope.initEvent();
		                $scope.eventinitname = obj.event;
		                $scope.properinitname = obj.viewField;

		                var nowEvents = $scope.eventList.filter(function(item){
		                    return item.eventName == obj.event;
		                });
		                if(nowEvents.length>0){
		                	event = nowEvents[0];
			                $scope.eventinitname = event.eventNameAlias;
			                $scope.evnullevent = false;
		                }
		                else{
		                	$scope.evnullevent = true;
		                }
		            }
		           	$scope.event = {
		                id:"evt_"+rmd,
		                params:[],
		                paramsList:[],
		                relation:"and"
		            }

		            if(!UtilService.isNullStr(event)){
		            	$scope.eventId = event.eventName;
		            	$scope.eventstatsEvtName = event.eventNameAlias;

		            	var setattr = function(){
		            		$scope.propertyList = event.firstLevelAttr;
			            	$scope.sumtypeList = event.secondLevelAttr;
			            	$scope.event.paramsList = event.profiles;
		            	}
		            	if(event.secondLevelAttr){
		            		setattr();
		            	}
		            	else{
		            		var evtvals = [],temp = {event:$scope.eventId,param:[]};
			                if(obj){
			                    obj.params.filter(function(pitem){
			                        temp.param.push(pitem.attr);
			                    });
			                    evtvals.push(temp);
			                }

			                ToolService.showLoading();
			                var evtprofilePM = HttpService.getInfo($rootScope.appid+"/event/find/param?names="+$scope.eventId+"&params="+JSON.stringify(evtvals));
			                evtprofilePM.then(function(pros){
			                    pros.filter(function(evt){
			                        for(var i=0;i<$scope.eventList.length;i++){
			                            if(evt.eventName == $scope.eventList[i].eventName){
			                                $scope.eventList[i].profiles = evt.profiles;
			                                $scope.eventList[i].firstLevelAttr = evt.firstLevelAttr;
			                                $scope.eventList[i].secondLevelAttr = evt.secondLevelAttr;
			                                break;
			                            }
			                        }
			                    });
			                    setattr();
			                    ToolService.hideLoading();
			                });
		            	}
		            }

		            if(obj){
		            	$scope.event.relation = obj.relation;
		                $timeout(function(){
		                    $scope.propertyInit = obj.viewField;
		                    $scope.prorefresh = ++rmd;

		                    $scope.event.secondval = obj.fieldOperate;
		                    if(obj.fieldOperate!=''){
			                	$scope.event.second = true;
			                	$scope.suminitname = obj.fieldOperate;
			                }
		                    obj.params.filter(function(pitem){
		                    	pitem.attrMatch = false;
		                        $scope.addEventParams($scope.event,pitem);
		                    });
		                });
		            }
		            else{
		                $scope.propertyInit = $scope.propertyList[0].attr;
		                $scope.prorefresh = ++rmd;
		            }
		        }
		        //属性
		        $scope.$on("propertyId",function(e,msg){
		            $scope.event.proId = msg.info.attr;
		            $scope.event.sumId = "";
		            if(msg.info.type!='default'){
		                $scope.event.second = true;
		                if($scope.event.secondval){
		                    $scope.sumtypeInit = $scope.event.secondval;
		                    delete $scope.event.secondval;
		                }
		                else{
		                    $scope.sumtypeInit = $scope.sumtypeList[0].attr;
		                }
		            }
		            else{
		                $scope.sumtypeInit = "";
		                $scope.event.second = false;
		            }
		        });
		        //属性聚合形式
		        $scope.$on("sumtypeId",function(e,msg){
		            $scope.event.sumId = msg.info.attr;
		        });

            	$scope.getEventNum = function(){
		            if(!$scope.eventInfo){return 20;}

		            var es = $scope.eventInfo.filter(function(item){
		                return item.show!=false;
		            });
		            return es.length;
		        }
            	$scope.setEventSteps = function(){
		            if(!$scope.eventInfo){return 20;}

		            var idx = -1;
		            var len = $scope.eventInfo.length;
		            $scope.eventInfo.filter(function(item,i){
		                if(item.show!=false){
		                    idx ++;
		                    item.steps = ['一','二','三','四','五','六','七','八','九','十'][idx];
		                    item.style = {'z-index':len-i};
		                }
		            });
		        }
		        $scope.addEvent = function(obj){

		            rmd ++;
		            var temp = {id:"evt_"+rmd,eventid:"event_"+rmd,relation:"and"};

		            if(obj){
		                for(var k in obj){
		                    temp[k] = obj[k];
		                }
		                temp.eventinit = obj.event;
		                temp.eventinitname = obj.event;
		                temp.params = [];

		                var evts = $scope.eventList.filter(function(item){
		                	return item.eventName == obj.event;
		                });
		                if(evts.length == 0){
		                	temp.nullevent = true;
		                	if(temp.oldparams){
		                        temp.oldparams.filter(function(pm){
		                            $scope.addEventParams(temp,pm);
		                        });
		                        delete temp.oldparams;
		                    }
		                }
		            }
		            (function(temp){
		                $scope.$on(temp.eventid,function(e,msg){
		                    temp.params = [];
		                    temp.event = msg.info.eventName;
		                    temp.evtname = msg.info.eventNameAlias;
		                    temp.nullevent = false;

		                    var setparams = function(){
		                        temp.paramsList = msg.info.profiles;
		                        if(temp.oldparams){
		                            temp.oldparams.filter(function(item){
		                                $scope.addEventParams(temp,item);
		                            });
		                            delete temp.oldparams;
		                        }
		                    }
		                    if(angular.isArray(msg.info.profiles)){
		                        setparams(msg.info.profiles);
		                    }
		                    else{
		                        var proPM = HttpService.getInfo($rootScope.appid+"/event/find/param?names="+temp.event);
		                        proPM.then(function(data){
		                            msg.info.profiles = data[0].profiles;
		                            setparams();
		                        });
		                    }

		                });
		            })(temp);

		            $scope.eventInfo.push(temp);
		            $scope.setEventSteps();
		        }
		        $scope.removeEvent = function(event){
		            if($scope.getEventNum()<=2 && $scope.type == 'funnel'){
		                ToolService.showTips("漏斗步骤不能少于2步");
		                return false;
		            }

		            for(var i=0;i<$scope.eventInfo.length;i++){
		                if($scope.eventInfo[i].id == event.id){
		                    $scope.eventInfo[i].show = false;
		                    break;
		                }
		            }
		            $scope.setEventSteps();
		        }
		        $scope.changeRel = function(event){
		            event.relation = event.relation == 'and' ? "or" : 'and';
		        }
		        $scope.getEventParamsNum = function(event){
		            if(!event.params){return 5;}

		            var eps = event.params.filter(function(item){
		                return item.show!=false;
		            });
		            return eps.length;
		        }
		        $scope.addEventParams = function(event,obj){
		            if(!event.params || $scope.getEventParamsNum(event)>=3){return false;};
		            rmd ++;
		            var tempparam = {id:"pam_"+rmd,pid:event.id};
		            if(obj){
		                for(var k in obj){
		                    tempparam[k] = obj[k];
		                }
		            }
		            event.params.push(tempparam);
		        }
		        $scope.removeEventParams = function(event,param){
		            for(var i=0;i<event.params.length;i++){
		                if(event.params[i].id == param.id){
		                    event.params[i].show = false;
		                    break;
		                }
		            }
		        }
		        $scope.$on("event",function(e,msg){
		        	if($scope.type == 'eventstats'){
		        		var params = $scope.event.params;
			            for(var j=0;j<params.length;j++){
			                if(params[j].id == msg.id){
			                    params[j] = msg;
			                    break;
			                }
			            }
		        	}
		        	else{
		        		for(var i=0;i<$scope.eventInfo.length;i++){
			                if($scope.eventInfo[i].id == msg.pid){
			                    var params = $scope.eventInfo[i].params;
			                    for(var j=0;j<params.length;j++){
			                        if(params[j].id == msg.id){
			                            params[j] = msg;
			                            break;
			                        }
			                    }
			                }
			            }
		        	}
		        });

		        $scope.okSave = function(){
		        	var hasNull = false;
		            var eventInfo = [],myEvents = [];

		            $scope.eventInfo.filter(function(item){
		                if(item.show!=false){
		                    var temp = {event:item.event,relation:item.relation,params:[],eventMatch:true};
		                    if(UtilService.isNullStr(item.event) || item.nullevent == true){
		                        item.nullevent = true;
		                        hasNull = true;
		                    }
		                    else{
		                        item.nullevent = false;
		                        item.params.filter(function(pm){
		                            if(pm.show!=false){
		                                var pms = {};
		                                for(var k in pm){
		                                    if(k!='id' && k!='pid'){
		                                        if(k!='value'){
		                                            pms[k] = pm[k];
		                                        }else{
		                                            pms[k] = pm[k].join(",");
		                                        }
		                                        if(UtilService.isNullStr(pm[k])){
		                                            $scope.$broadcast(pm.id, "null");
		                                            hasNull = true;
		                                        }
		                                    }
		                                }
		                                temp.params.push(pms);
		                            }
		                        });
		                    }
		                    eventInfo.push(temp);
		                    myEvents.push(item.evtname);
		                }
		            });
		            if(!hasNull && eventInfo.length>0){
		                $scope.$emit("matchok",{info:eventInfo,names:myEvents});
		            }
		            else{
		                ToolService.showTips("信息没填全或数据有误，请检查");
		            }
		        }

		        $scope.eventSave = function(){
		        	if(!$scope.event.params){return false;}
		            var hasNull = false;
		            var eventInfo = {event:$scope.eventId,relation:$scope.event.relation,params:[]};
		            eventInfo.viewField = $scope.event.proId;
		            if($scope.event.second){ //有二级选项
		                eventInfo.fieldOperate = $scope.event.sumId;
		            }
		            else{
		                eventInfo.fieldOperate = "";
		            }
		            $scope.event.params.filter(function(pm){
		                if(pm.show!=false){
		                    if(UtilService.isNullStr(pm.attr)){
		                        $scope.$broadcast(pm.id, "error");
		                        hasNull = true;
		                    }
		                    var pms = {};
		                    for(var k in pm){
		                        if(k!='id' && k!='pid'){
		                            if(k!='value'){
		                                pms[k] = pm[k];
		                            }else{
		                                pms[k] = pm[k].join(",");
		                            }
		                            if(UtilService.isNullStr(pm[k])){
		                                $scope.$broadcast(pm.id, "error");
		                                hasNull = true;
		                            }
		                        }
		                    }
		                    eventInfo.params.push(pms);
		                }
		            });
		            if(hasNull || !$scope.eventId){
		                ToolService.showTips("信息没填全或数据有误，请检查");
		            }
		            else{
		            	$scope.$emit("matchok",{info:eventInfo,names:[$scope.eventstatsEvtName]});
		            }
		        }
            }
        }
    }

    //文件上传
    function fileModel($parse){
    	return {
	        restrict: 'A',
	        scope:{

	        },
	        link: function(scope, element, attrs) {
	          var model = $parse(attrs.fileModel);
	          var modelSetter = model.assign;

	          element.bind('change', function(){
	          	var val = angular.element(element).val();
	          	if(val == ''){return false;}

	            scope.$apply(function(){
	            	var myFile = element[0].files;
		            if (attrs.multiple) {
		                modelSetter(scope, element[0].files);
		            }
		            else {
		                modelSetter(scope, element[0].files[0]);
		                myFile = element[0].files[0];
		            }
		            scope.$emit("myFile",myFile);
		            angular.element(element).val("");
	            });
	          });
	        }
	    };
    }

    //文件上传
    function searchGroup(){
    	return {
	        restrict: 'E',
	        replace:true,
	        scope:{
	        	filterfn:"&",
	        	initTxt:"=",
	        	initf5:"=",
	        	list:"="
	        },
	        templateUrl : '/template/common/searchGroup.html?r='+tempVersion,
	        link: function($scope, element, attrs) {

	        	$scope.query = function(){
	        		if($scope.preTxt == $scope.srhTxt){
	        			return false;
	        		}
	        		$scope.filterfn({txt:$scope.srhTxt});
	        		$scope.preTxt = $scope.srhTxt;
	        	}
	        	$scope.$watch("initTxt+initf5+list",function(){
	        		$scope.srhTxt = $scope.preTxt = $scope.initTxt || "";
	        	});

	        	$scope.doNull = function(){
	        		$scope.srhTxt = "";
	        		$scope.query();
	        	}
	        }
	    };
    }
    //固定表格
    function bigTable($timeout,$compile){
    	return {
	        restrict: 'A',
	        replace:true,
	        scope:{
	        	fixedCol:"@", //固定列数
	        	fixChange:"=", //列表变化，翻页排序等，只需要更新滑动条即可
	        	infoList:"=", //列表数据
	        	initf5:"=", //初始化列表,一般是数据列表重新查询
	        	noScroll:"@",
	        	noAllScroll:"@",
	        	noEmpty:"="
	        },
	        link: function($scope, element) {
	        	var tableSpline = $(element).find(".tableSpline"),
	        		tableHeader = $(element).find(".tableHeader"),
	        		tableInfo = $(element).find(".tableInfo");
	        	var copyColWrap = $(element).find(".copyColWrap"),copyTable = copyColWrap.find("table");

	        	var totalLeft = 0, infoh = 0, isEmpty = false, before = 0, after = 0,preLeft = 0;
	        	var helpTip = $(".helpTipWrap");
	        	if(tableSpline.length==0){
	        		$(element).append("<div class='tableSpline'></div>");
	        		tableSpline = $(element).find(".tableSpline");
	        	}
	        	if(copyColWrap.length==0){
	        		$(element).prepend("<div class='copyColWrap'><table></table></div>");
	        		copyColWrap = $(element).find(".copyColWrap");
	        		copyTable = copyColWrap.find("table");
	        		if($scope.noAllScroll){
	        			copyColWrap.css({"max-height":"233px","top":"35px"});
	        		}
	        	}
	        	var init = function(){
	        		totalLeft = 1; //1像素边框
        		    tableHeader.scrollLeft(0);
        		    tableInfo.scrollLeft(0);
        		    tableInfo.scrollTop(0);
        		    infoh = tableInfo.find("table").height();
        		    for(var i = 0; i < $scope.fixedCol; i++){
        		    	totalLeft += tableHeader.find("#title_"+i).parent().width();
        		    }
        		    tableSpline.css({"left":totalLeft});
        		    $(element).find(".tableHeader th:lt("+$scope.fixedCol+")").css("left","0px");
        		    preLeft = 0;
	        	}
	        	var updateBar = function(){
	        		var info = tableInfo.find("table"),
                		header = tableHeader.find("table");

                	if($scope.noEmpty){
                	   isEmpty = false;
                	}else{
                	   isEmpty = $scope.infoList && $scope.infoList.length==0;
                	}

                    var headerw = header.css("width"),
	                    headerh = header.css("height"),
	                    tableH = info.find("tbody").height(),headH = header.height();

                    var trlast = tableInfo.find("table tr:last");
                    if(isEmpty){
	                    if(trlast.length==0){
	                    	info.append("<tr></tr>")
	                    }
                		info.width(headerw);
                		info.height(infoh==0?headerh:infoh);
                		tableSpline.height(headerh);
                	}
                	else{
                		tableInfo.find("table").width('');
                		tableInfo.find("table").height('');

                		var tsh = headH+tableH,maxh = $(element).height();
                		tableSpline.height(tsh > maxh ? maxh : tsh);

                		if(!trlast.html()) trlast.remove();
                	}

                	tableInfo.perfectScrollbar("update");
            		tableInfo.scrollLeft(preLeft); //此行代码是为了兼容火狐浏览器
            		tableInfo.scrollTop(0);
	        	}
	        	var updateFixTds = function(){
	        		copyTable.html("");
        			if(!isEmpty){
        				tableInfo.find("tr").each(function(i){
        					copyTable.append("<tr></tr>");

        					var lastTr = copyTable.find("tr:last-child");
        					for(var c=0;c<$scope.fixedCol;c++){
        						lastTr.append($(this).children("td:eq("+c+")").clone(true));
        						//首列带有click下钻特殊处理
        						if(c==0){
        							//这里单独指compile列里面的div，是因为列上很多时候有ng-repeat
		        					var Tds = lastTr.find("td");
		        					Tds.each(function(){
		        							var hm = $(this).find("div").html();
		        							$(this).html(
		        								$compile($(this).clone(true))($scope.$parent)
		        							);
		        							$(this).find("div").html(hm);
		        						}
		        					);
        						}
        					}
        				});
        			}
	        	}
	        	$scope.$watch("initf5",function(n){
	        		if(angular.isDefined(n)){
	        			tableSpline.hide();
	        			copyTable.html("");
	        			var timer = $timeout(function() {
	        				init();
	        			},50);
	        			timer.then(function(){
	                    	$timeout.cancel(timer);
	                    });
	        		}
	        	});
	        	$scope.$watch("fixChange",function(n){
	        		if(angular.isDefined(n) && $scope.infoList){
	        			copyTable.html("");
	        			var timer = $timeout(function() {
	        				updateBar();
	        				updateFixTds();
	        			},100);
	        			timer.then(function(){
	                    	$timeout.cancel(timer);
	                    });
	        		}
	        	});

	        	$scope.$on("conentresize",function(){
                    tableInfo.perfectScrollbar("update");
            		tableInfo.scrollLeft(0);
            		tableInfo.scrollTop(0);
            		tableSpline.hide();
	        	});

                var before = 0;
	        	tableInfo.scroll(function(e){
	        		helpTip.hide();

	        	    var target = e.target,left = target.scrollLeft;
	        	    preLeft = left;
	        	    tableHeader.scrollLeft(left);

	        	    var cellCss = {
	        	    		"position":"relative",
	        	            "left":left,
	        	            "-webkit-overflow-scroll":"touch"
	        	        };

	        	    $(element).find(".tableHeader th:lt("+$scope.fixedCol+")").each(function(i){
	        	        $(this).css(cellCss);
	        	    });

	        	    if(left>0){
	        	        tableSpline.show();
	        	    }
	        	    else{
	        	       tableSpline.hide().css('-webkit-overflow-scroll','auto');
	        	    }
	                after = $(this).scrollTop();
	                copyColWrap.scrollTop(after);
	                if($scope.noAllScroll){return;}
	                if(before>after){
	                	if(after < 200 && !$scope.noScroll)
	                	$(".rightWrap").scrollTop(after);
	                }
	                else{
	                	if(!$scope.noScroll){
		                	if(after >= tableInfo.find("table").height()-tableInfo.height() && this.scrollTop>0)
		                	$(".rightWrap").scrollTop(this.scrollHeight);
	                	}else{
	                		$(".rightWrap").scrollTop($(".rightWrap").scrollTop()+this.scrollHeight);
	                	}
	                }
	                before = after;
	        	});

	        	$(".rightWrap").scroll(function() {
	        	  	helpTip.hide();
	        	});
	        	tableInfo.perfectScrollbar();
	        }
	    };
    }

    //拖拽排序
    var sourceId = 0;
    function dragOrder($parse){
    	return {
	        restrict: 'A',
	        scope:{
	        	dragId:"=",
	        	dragflag:'@'
	        },
	        link: function($scope, element, attrs) {
	        	element.attr("draggable",true);

	        	angular.element(element).on("dragstart",function(event){
	        		sourceId = $scope.dragId;
	        	});
	        	angular.element(element).on("dragover",function(event){
	        		event.preventDefault();
	        	});
	        	angular.element(element).on("drop",function(event){
	        		var replaceDom = $(this),info = JSON.parse(replaceDom.attr("drag-info"));
	        		event.preventDefault();
					if(sourceId != info.id){
						$scope.$emit("dragorder",{id:sourceId,index:info.orderindex,flag:$scope.dragflag});
					}
	        	});
	        }
	    };
    }
})();
