(function(){
    angular.module("app.collect")
        .controller("eventstatsCtrl",["$scope","$rootScope","HttpService","ToolService","UtilService","$filter","$timeout","$stateParams","$q",eventstatsCtrl]);

    String.prototype.visualLength = function()
    {
        var ruler = $("#ruler");
        ruler.text(this);
        return ruler.width();
    }
    function eventstatsCtrl($scope,$rootScope,HttpService,ToolService,UtilService,$filter,$timeout,$stateParams,$q){
        $scope.formatList = [
            {format:"percent",name:"百分比"},
            {format:"float",name:"两位小数"},
            {format:"int",name:"整数"}
        ];
        $scope.formatinitname = "整数";
        $scope.groupbys = [];
        $scope.dimensionname = "请选择分组";
        $scope.dimenInit = "-all";

        angular.element(document).on("click",function(){
            $scope.$apply(function(){
                $scope.showProList = false;
                $scope.nowEvent = "";
            });
        });
        $scope.getwidth = function(name){
            return ToolService.getByteLen(name)*6;
        }
        //得到最后一次出现加减乘除符号的下标
        var getLastIndex = function(str,reg){
            if(!str)return;
            var len = str.length,index = 0;
            if(len>0){
                index = str.split("").reverse().join("").search(reg?reg:regexp);
                if(index > -1){
                    index = len - index - 1;
                }
            }
            return index;
        }
        var ischrome = UtilService.getBrowser().indexOf('Chrome')>-1;
        $scope.changeExpression = function(ex,index,event){
            $scope.expressionObj = index>=0?document.getElementById("expression_"+index):$scope.expressionObj;
            var focusIndex = sectionTool.getCursortPosition($scope.expressionObj),
                value = ex.expressionName?ex.expressionName:"";
            value = value.substring(0, focusIndex);
            var s1 = value.substring(getLastIndex(value),focusIndex),filterTxt = "";
            $scope.currentIndex = index;
            //如果第一个字符是计算字符，减去，以便过滤等
            if(getLastIndex(s1) == s1.length-1){
                s1 = s1.substring(1);
            }

            var showList = function(){
                $scope.showProList = true;

                var boxXY = document.getElementById("evtBox").getBoundingClientRect(),
                    preTxt = $scope.expressionObj.value.substring(0,focusIndex),
                    mx = preTxt.visualLength() - $scope.expressionObj.scrollLeft,
                    inputXY = $scope.expressionObj.getBoundingClientRect(),
                    // top = inputXY.top + inputXY.height - boxXY.top + $(".rightWrap").scrollTop(),
                    top = inputXY.top + inputXY.height - boxXY.top,
                    len = filterTxt.visualLength();

                var left = inputXY.left - boxXY.left + mx - len+13;
                if(!ischrome){
                    left -=16;
                    if($scope.expressionObj.scrollLeft>36){
                        if(focusIndex == $scope.expressionObj.value.length){
                            left -= 36;
                        }
                        else{
                            left -= 10;
                        }
                    }
                }
                document.getElementById('optionList').style.left = left + "px";
                document.getElementById('optionList').style.top = top + "px";
            }
            $scope.eventIndex = -1;
            $(".optionList ul").scrollTop(0);
            $scope.nowEvent = "";
            if(s1.indexOf(".")==-1){
                $scope.epropertyList = $scope.eventList;
                filterTxt = s1;
                var filterIndex = filterTxt.search(regexp);
                if(filterIndex>-1){
                    filterTxt = filterTxt.slice(filterIndex+1);
                }
                $scope.typeName = eval(['自然事件','虚拟事件']);
                $scope.typeKey = eval(['nature','virtual']);
            }
            else{
                //根据截图的数据来判断当前段有几个.，以此来判断是到事件的第几级
                $scope.typeName = [];
                $scope.typeKey = [];
                var count = s1.match(/\./g).length;

                filterTxt = s1.substring(s1.lastIndexOf(".")+1);
                if(count == 1){
                    var findex = s1.split("").join("").search(regexp),start = 0;
                    if(findex == 0){
                        start = 1;
                    }
                    var tn = s1.substring(start,s1.indexOf("."));
                    $scope.getEventName(tn);
                    $scope.getAttrByEvent($scope.selectEvent,showList);
                }
                else if(count == 2){
                    var findex = s1.split("").join("").search(regexp),start = 0,fd = s1.indexOf(".");
                    if(findex == 0){
                        start = 1;
                    }
                    var en = s1.substring(start,fd),pn = s1.substring(fd+1,s1.lastIndexOf("."));
                    $scope.getEventName(en);

                    $scope.getAttrByEvent($scope.selectEvent,function(list){

                        for(var m=0;m<list.length;m++){
                            if(list[m].name == pn){
                                $scope.selectAttr = list[m];
                                break;
                            }
                        }

                        if(list.length>0 && $scope.selectAttr && !$scope.selectAttr.isleaf){
                            var kpiList = $scope.kpiList.filter(function(item){
                                return item.viewType == $scope.selectAttr.type || item.viewType == "all";
                            });
                            $scope.showProList = true;
                            $scope.epropertyList = kpiList;
                        }
                        else{
                            $scope.epropertyList = [];
                        }
                    },1);
                }
                else{
                    $scope.epropertyList = [];
                }
            }

            if($scope.epropertyList.length>0 && ((event && !event.isleaf) || !event)  ){
                showList();
            }
            else{
                $scope.showProList = false;
            }
            $scope.filterSearch = filterTxt;
            $scope.currentExpression = ex;

        }
        $scope.getEventName = function(name){
            for(var i=0;i<$scope.eventList.length;i++){
                if($scope.eventList[i].name == name){
                    $scope.selectEvent = $scope.eventList[i];
                    break;
                }
            }
        }
        $scope.$watch("filterSearch",function(n){
            if(angular.isUndefined(n) || !n){return false;}
            $scope.virtual = "";
            $scope.nature = "";
            $scope.epropertyList.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;
                }
            });
        });
        $scope.expresstionTransform = function(n){
            var par = {
                expression:n.expressionName,
                appkey:$scope.appid
            }
            var validPM = HttpService.postInfo("expression/transform",par);
            var temp = n;
            validPM.then(function(data){
                temp.error = false;
                if(data.code == 11000){
                    temp.error = true;
                }else{
                    temp.error = false;
                    temp.expression = data;
                }
            },function(){
                temp.error = true;
            });

        }
        $scope.showFlow = true;
        $scope.changeFlow = function(flag){
            if(flag == 1){
                $scope.showFlow = false;
            }
            else{
                $scope.showFlow = true;
            }
        }
        $scope.$watch("currentExpression",function(n,o){
            if(angular.isUndefined(n) || !n){return false;}
            if(!n.expressionName){
                $scope.changeExpression(n,$scope.currentIndex);
                return;
            }
            if(!o || (n == o) || (n && o && n.expressionName==o.expressionName))return;
            $scope.expresstionTransform(n);
            var name = n.expressionName;
            if(getLastIndex(name) == name.length-1 || name.slice(-1)=="."){
                $scope.changeExpression(n,$scope.currentIndex);
            }
        },true);
        var regexp =  /[\+\-\*\/\(\)]/g;
        //需要考虑怎么存储点击的事件数据，这样下次定光标的时候可以获取到前面的事件实时查询当前的属性等
        $scope.getProperty = function(event){
            var focusIndex = $scope.expressionObj.selectionStart,
                value = $scope.currentExpression.expressionName?$scope.currentExpression.expressionName:"";

            var val1 = value.substring(0,focusIndex),val2 = value.substring(focusIndex),attrType="",isleaf="";
            var reg =  /[\+\-\*\/\(\)\.]/g;
            val1 = val1.slice(0,getLastIndex(val1,reg)+1);

            for (var i = 0; i < $scope.epropertyList.length; i++) {
                var index = val2.search(regexp);
                var attr = "";
                if(val2.indexOf(".") < index){
                    attr = val2.slice(0,val2.indexOf("."));
                }else if(val2.indexOf(".") > index){
                    attr = val2.slice(0,index);
                }else{
                    attr = val2.slice(0);
                }

                if(attr == $scope.epropertyList[i].name){
                    attrType = $scope.epropertyList[i].type;
                    isleaf = $scope.epropertyList[i].isleaf;
                    break;
                }
            }
            if(val2.indexOf(".")!=0 && !event.viewType){
                var index = val2.search(regexp);
                if((index == -1 && val2.indexOf(".") > -1 ) || (val2.indexOf(".") > -1 && index > -1 && val2.indexOf(".") < index)){
                    val2 = val2.substring(val2.indexOf("."));
                }else{
                    val2 = "." + val2;
                }
            }

            //这里需要修改，要判断当前数据情况进行插入
            if(attrType && event.type != attrType && !event.isleaf || event.isleaf || isleaf){
                var index = val2.search(regexp);
                if(!event.isleaf && !isleaf){
                    val2 = "."+val2.substring(index);

                }else{
                    val2 = (event.isleaf?"":".")+(index>-1?val2.substring(index):"");
                }

            }

            $scope.currentExpression.expressionName = val1 + event.name + val2;
            $scope.expressionObj.value = $scope.currentExpression.expressionName;
            var bstr = val1 + event.name;
            var len = bstr[bstr.length-1]=="." || event.viewType || event.isleaf?bstr.length:(bstr.length+1);
            sectionTool.setCaretPosition($scope.expressionObj,len);
            $scope.selectEvent = !event.type && !event.isleaf?event:$scope.selectEvent;
            $scope.selectAttr = event.type && !event.isleaf?event:$scope.selectAttr;
            $timeout(function(){
                $scope.changeExpression($scope.currentExpression,-1,event);
            },100);
        }
        $scope.watchKey = function(n,e){

            if(e.keyCode == 37 || e.keyCode == 39){
                var timer = $timeout(function() {
                    $scope.changeExpression(n,$scope.currentIndex);
                }, 100);
                timer.then(function(){
                    $timeout.cancel(timer);
                });

            }
            if(e.keyCode == 40){
                e.preventDefault();
                $scope.eventIndex++;
                $scope.eventIndex = $scope.eventIndex<$scope.epropertyList.length?$scope.eventIndex:0;
                $(".optionList ul").scrollTop(34*($scope.eventIndex==0?1:$scope.eventIndex));
                $scope.nowEvent = $scope.epropertyList[$scope.eventIndex];
            }
            if(e.keyCode == 38){
                e.preventDefault();
                $scope.eventIndex--;
                $scope.eventIndex = $scope.eventIndex<0?$scope.epropertyList.length-1:$scope.eventIndex;
                $(".optionList ul").scrollTop(34*($scope.eventIndex==0?1:$scope.eventIndex));
                $scope.nowEvent = $scope.epropertyList[$scope.eventIndex];
            }

        }
        $(document).keydown(function(event){
            if(event.keyCode == 13 && $scope.nowEvent){
                $scope.getProperty($scope.nowEvent);
            }
        });
        var fid = $stateParams.pageid;
        var rmd = new Date().getTime();
        var commonEventPros = [];
        var eventPM = null;
        $scope.queryInfoByApp = function(flag,dID){
            if(angular.isUndefined(flag) || flag==5){
                //app下所有事件
                eventPM = HttpService.getInfo($scope.appid +"/event/find/virtual");
                eventPM.then(function(data){
                    $scope.eventList = [];
                    angular.forEach(data,function(item){
                        var event = {};
                        event.id = item.eventName;
                        event.name = item.eventNameAlias;
                        event.type = item.virtual?"virtual":"nature";
                        $scope.eventList.push(event);

                    });
                });

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

                    var bol  = false;
                    for(var i=0;i<$scope.eventList.length;i++){
                        if($scope.eventList[i].type== type){
                            bol = true;
                            break;
                        }
                    }
                    return bol;
                }
                var fixedAttrPM = HttpService.getInfo("expression/viewList");
                fixedAttrPM.then(function(data){
                    $scope.kpiList = [];
                    $scope.fixedAttrList = data.eventViewList;

                    commonEventPros = [];
                    angular.forEach($scope.fixedAttrList,function(item,index){
                        var event = {};
                        event.id = item.viewAttr;
                        event.name = item.viewAttrName;
                        event.isleaf = true;
                        if(index==$scope.fixedAttrList.length-1){
                            event.border = true;
                        }
                        commonEventPros.push(event);
                    });

                    angular.forEach(data.attrViewList,function(item){
                        var event = {};
                        event.id = item.viewAttr;
                        event.name = item.viewAttrName;
                        event.viewType = item.viewType;
                        event.isleaf = true;
                        $scope.kpiList.push(event);

                    });
                });
                //分组
                var profilePM = HttpService.getInfo($scope.appid+"/event/find/group/properties");
                profilePM.then(function(data){
                    $scope.dimensionList = data;
                });
                //通用属性
                var profilePM = HttpService.getInfo($scope.appid+"/event/find/common/properties");
                profilePM.then(function(data){
                    $scope.commonAttrList = data;
                });
            }

            var definePM = HttpService.getInfo("mng/eventstats/complicated/findAll/"+$scope.appid);
            $scope.define = {};
            definePM.then(function(data){
                $scope.defineList = data;
                if(data.length>0){
                    $scope.addFirst = false;
                    if(!UtilService.isNullStr(fid)){
                        dID = fid;
                    }
                    if(dID){ //修改自定义事件
                        for(var i=0;i<$scope.defineList.length;i++){
                            if($scope.defineList[i].id == dID){
                                $scope.define = $scope.defineList[i];
                                break;
                            }
                        }
                        if(!UtilService.isNullStr(fid)){
                            $scope.clickDefine($scope.define);
                            fid = null;
                        }
                        else{
                            $scope.defineFlag = ++rmd;
                        }
                    }
                    else{
                        $scope.clickDefine(data[0]);
                    }
                }
                else{
                    var oldPM = HttpService.getInfo("mng/eventstats/complicated/show/import");
                    ToolService.showLoading();
                    oldPM.then(function(data){
                        ToolService.hideLoading();
                        if(typeof data.content !='undefined'){
                            $scope.isold = data.content;
                        }
                        else{
                            $scope.isold = data;
                        }
                    });
                }
            });
        }
        $scope.importOld = function(){
            var importPM = HttpService.putInfo("mng/eventstats/complicated/import/old/data");
            ToolService.showLoading();
            importPM.then(function(data){
                ToolService.hideLoading();
                $scope.queryInfoByApp(1);
            });
        }
        var doDevice = ['_count_user','_count_avg'];
        $scope.$watch("define",function(obj){
            if(obj && obj.id){
                $scope.isEditInfo = true;
            }
        });
        $scope.addTitName = "新建事件统计细分";
        $scope.getTrendTitle = function(){
            if($scope.showTempLook){
                return $scope.addTitName + "的趋势";
            }
            else if($scope.define && $scope.define.id){
                return $scope.define.name + "的趋势";
            }
            else{
                return "事件趋势";
            }
        }

        //已保存的事件
        $scope.definename = "请选择事件";
        $scope.clickDefine = function(m){
            $scope.define = m;
            $scope.defineFlag = ++rmd;
            $scope.isEditInfo = true;
            $scope.isShowCache = false;

            $rootScope.thirdtab = m.name;
        }
        $scope.deleteDefine = function(d){
            $scope.delDefine = d;
            ToolService.showAlp();
            ToolService.showLoading();
            var validPM = HttpService.getInfo("custommenu/delete/valid/"+d.id+"?type=eventstats");
            validPM.then(function(data){
                ToolService.hideLoading();
                $scope.wantDelete = true;
                $scope.custommenus = angular.isArray(data) && data.length>0?data:false;
            });
        }
        $scope.doDelete = function(){
            $scope.closeWin();
            ToolService.showLoading();
            var deletePM = HttpService.deleteInfo("mng/eventstats/complicated/delete/"+$scope.delDefine.id);
            deletePM.then(function(){
                ToolService.showTips("删除成功");
                $scope.queryInfoByApp(1);
                ToolService.hideLoading();
                $rootScope.operSubmitData("删除");
            });
        }

        $scope.date = ToolService.getLastDays(-7,0);
        $scope.timeFlag='day';
        $scope.disTimeFlag = ['hour'];
        $scope.changeTimeFlag = function(flag){
            if($scope.disTimeFlag.indexOf(flag)>-1){return false;}

            $scope.timeFlag = flag;
        }
        $scope.$on("dateCustos",function(e,msg){
            if(msg.startDate == msg.endDate){
                $scope.disTimeFlag = ["week","month"];
            }
            else{
                $scope.disTimeFlag = ["hour"];

            }
            if($scope.disTimeFlag.indexOf($scope.timeFlag)>-1){
                $scope.timeFlag = 'day';
            }
            $scope.date = msg;
        });
        $scope.$watch("date",function(){
            if(angular.isDefined($scope.date)){
                $scope.datestr = $scope.date.startDate + "至" + $scope.date.endDate;
            }
        });

        var proertyCollection = {},lastid = -1;
        $scope.getAttrByEvent = function(event,callback,flag){
            // ToolService.showLoading();
            if(!event || event.isleaf){
                $scope.epropertyList = [];
                callback && callback([]);
                return false;
            };

            var myPropertys = function(profiles){
                var tempList = UtilService.cloneJSON(commonEventPros);
                angular.forEach(profiles,function(item){
                    var event = {};
                    event.id = item.attr;
                    event.name = item.attrAlias;
                    event.type = item.webType || item.dataType;
                    tempList.push(event);

                });
                if(flag){ //此种情况是直接匹配获取相应的属性指标
                    callback && callback(tempList);
                }
                else{
                    $scope.epropertyList = tempList;
                    callback && callback(tempList);
                }
            }
            $scope.epropertyList = [];

            if(proertyCollection[event.id]){
                myPropertys(proertyCollection[event.id]);
                $scope.attrShow = true;
            }
            else{
                //阻止重复发送事件
                if(lastid == event.id && flag!=2){return false;} //flag:2,编辑时需要发送

                lastid = event.id;
                var evtprofilePM = HttpService.getInfo("expression/properties/"+event.id+"/"+$scope.appid);

                evtprofilePM.then(function(pros){
                    var properties = orderBy(pros,"sortId");
                    myPropertys(properties);
                    proertyCollection[event.id] = properties;
                });
            }
        }

        $scope.changeEvent = function(event,obj){

            if(obj){ //编辑查找
                $scope.eventRel = obj.relation;
            }

            var set = function(){
                $scope.event = {
                    id:"evt_"+rmd,
                    params:[],
                    paramsList:$scope.commonAttrList
                }

                if(obj){
                    $timeout(function(){
                        $scope.propertyInit = obj.viewField;
                        $scope.prorefresh = ++rmd;
                        $scope.event.secondval = obj.fieldOperate;
                        obj.params.filter(function(pitem){
                            $scope.addEventParams($scope.event,pitem);
                        });
                    });
                }
            }
            set();
        }
        $scope.eventinitname = "请选择事件";
        $scope.eventRel = "and";
        $scope.changeRel = function(){
            $scope.eventRel = $scope.eventRel == "and" ? "or" : "and";
        }
        $scope.initCondition = function(){
            if($scope.event.id){
                $scope.initComplexEvent();
            }
        }
        $scope.changeForm = function(ex){
            $scope.nowEvent = "";
            ex.expression = !ex.expression;
            if(ex.expression){
                if(ex.operator){
                    var events = [], pros = [], target = [], proStr = "", tarStr = "";
                    if(ex.event){
                        events = $scope.eventList.filter(function(item){
                            return ex.event == item.id;
                        });
                    }
                    var pro = ex.property || ex.operator;
                    if(pro){
                        pros = ex.epropertyList.filter(function(item){
                            return pro == item.id;
                        });
                        proStr = "."+pros[0].name;
                    }
                    if(ex.operator && ex.property){
                        target = ex.targetList.filter(function(item){
                            return ex.operator == item.id;
                        });
                        tarStr = "."+target[0].name;
                    }


                    ex.expressionName = events[0].name+proStr+tarStr;
                }else{
                    ex.expressionName = $scope.eventList[0].name+".总次数/"+$scope.eventList[0].name+".用户数";
                }
                $scope.expresstionTransform(ex);
            }else{
                ex.extip = "";
            }

        };
        $scope.showEventWin = false;
        $scope.currentEvent = [];
        $scope.addComplexEvent = function(flag,n){
            var cache = UtilService.getItem($scope.appid);
            if(flag==1 || cache){ //编辑
                if(!$scope.define.id && !$scope.isShowCache){return false;}
                $scope.isShowCache = flag==0 || n;
                if(!$scope.isShowCache){
                    $scope.currentDefine = $scope.define;
                    $scope.ename = $scope.define.name;
                }else{
                    $scope.currentDefine = {};
                }
                var eventCondition = $scope.isShowCache?JSON.parse(cache):JSON.parse($scope.currentDefine.eventCondition);
                $scope.isEditInfo = true;

            }
            else{
                $scope.currentDefine = {};
                $scope.isEditInfo = false;
                $scope.isShowCache = false;
            }
            $scope.initComplexEvent(flag,eventCondition);
            $scope.showEventWin = true;
        }
        $scope.initComplexEvent = function(flag,eventCondition){
            $scope.currentEvent.filter(function(item){
                item.show = false;
            });
            $scope.groupbys.filter(function(item){
                item.show = false;
            });
            if(eventCondition){
                ToolService.showLoading();
                $q.all([eventPM]).then(function(data){
                    var eventInfo = eventCondition;
                    eventInfo.expressions.filter(function(e){
                        $scope.addEvents(e);
                    });
                    eventInfo.group.filter(function(e){
                        $scope.addGroupby(e);
                    });
                    ToolService.hideLoading();
                });
                var attrs = [];
                eventCondition.params.filter(function(e){
                    attrs.push(e.attr);
                });
                if(attrs.length>0){
                    var profilePM = HttpService.getInfo($scope.appid+"/event/find/value/attrs?attrNames="+attrs.join(","));
                    profilePM.then(function(pros){
                        var prosInfo = pros;
                        $scope.commonAttrList.filter(function(item){
                            var valueJSON = prosInfo[item.attr];
                            if(valueJSON && valueJSON.key){
                                item.key = valueJSON.key;
                            }
                            if(valueJSON && valueJSON.value){
                                item.value = valueJSON.value;
                            }

                        });
                        $scope.changeEvent(null,eventCondition);

                    });
                }

            }else{
                $scope.addEvents();
            }
            $scope.event = {
                id:"evt_"+rmd,
                params:[],
                relation:$scope.eventRel,
                paramsList:$scope.commonAttrList
            }
        }
        $scope.addFirst = false;
        $scope.addFirstEvent = function(){
            $scope.addFirst = true;
            $scope.showEventWin = true;
            $scope.currentDefine = {};
            $scope.initComplexEvent();
        }
        $scope.closeAddWin = function(){
            $scope.showEventWin = false;
            $scope.addFirst = false;
            $scope.isEditInfo = true;
        }
        $scope.maxparams = 10;
        $scope.maxevents = 10;
        $scope.maxgroupbys = 3;
        $scope.addGroupby = function(obj){
            if($scope.getGroupByNum()>=$scope.maxgroupbys)return;
            ++ rmd;
            var temp = {id:"gby_"+rmd,dimensionId:"groupby_"+rmd,show:true};
            if(obj){
                for(var k in obj){
                    temp[k] = obj[k];
                }
                temp.dimenInit = obj.name;
            }
            (function(temp){
                $scope.$on(temp.dimensionId,function(e,msg){
                    temp.dimenId = msg.info.param;
                    temp.type = msg.info.type;
                });
            })(temp);
            $scope.groupbys.push(temp);
        }
        $scope.addEvents = function(obj){
            if($scope.getEventNum()>=$scope.maxevents)return;
            ++rmd;
            var temp = {id:"evt_"+rmd,relation:"and",format_id:"for_"+rmd,show:true,
                        eventId:"event_"+rmd,propertyId:"pro_"+rmd,targetId:"tar_"+rmd};
            if(obj){
                for(var k in obj){
                    temp[k] = obj[k];
                }
                temp.formatInit = obj.format;
                temp.eventInit = obj.event;
                temp.event = obj.event;
                temp.propertyinit = obj.attr?obj.attr:obj.operator;
                temp.targetinit = obj.operator;
            }

            (function(temp){
                var event_name = "", pro_name = "", target_name ="";
                $scope.$on(temp.format_id,function(e,msg){
                    temp.formatId = msg.info.format;
                });
                $scope.$on(temp.eventId,function(e,msg){
                    if(temp.event && msg.info.id != temp.event){
                        temp.prorefresh = ++rmd;
                        temp.propertyinit = -1;
                        temp.tarrefresh = ++rmd;
                        temp.targetinit = -1;
                        temp.operator = "";
                        temp.property = "";
                        if(!obj){
                           temp.name = "";
                        }
                    }
                    temp.event = msg.info.id;
                    $scope.getAttrByEvent(msg.info,function(list){
                        temp.epropertyList = list;
                    },2);
                    temp.propertyShow = true;
                    temp.targetShow = false;
                    temp.propertyinitname = "请选择事件属性";
                    event_name = msg.info.name;

                });
                $scope.$on(temp.propertyId,function(e,msg){
                    var evObj = {id:temp.event};
                    if(!msg.info.isleaf){
                        temp.targetinitname = "请选择属性指标";
                        temp.operator = "";
                        if(temp.property && msg.info.id != temp.property){
                            temp.tarrefresh = ++rmd;
                            temp.targetinit = -1;
                            if(!obj){
                               temp.name = "";
                               target_name = "";
                            }
                        }
                        $scope.getAttrByEvent(evObj,function(list){
                            var proObj = list.filter(function(item){
                                return msg.info.id == item.id;
                            });
                            var kpiList = $scope.kpiList.filter(function(item){
                                return item.viewType == proObj[0].type || item.viewType == "all";
                            });
                            temp.targetList = kpiList;
                            temp.targetShow = true;
                        },1);
                        temp.property = msg.info.id;
                        pro_name = msg.info.name;
                        if(!obj){
                           temp.name = target_name?(event_name + pro_name + target_name):"";
                        }
                    }else{
                        temp.operator = msg.info.id;
                        temp.targetShow = false;
                        temp.targetinit = "";
                        temp.property = "";
                        if(!obj){
                            temp.name = event_name + msg.info.name;
                            target_name = "";
                        }
                    }

                });
                $scope.$on(temp.targetId,function(e,msg){
                    temp.operator = msg.info.id;
                    temp.targetShow = true;
                    target_name = msg.info.name;
                    if(!obj){
                        temp.name = event_name + pro_name + msg.info.name;
                    }
                });
            })(temp);
            $scope.currentEvent.push(temp);
        }
        $scope.getEventParamsNum = function(event){
            if(!event || !event.params){return $scope.maxparams;}

            var eps = event.params.filter(function(item){
                return item.show!=false;
            });
            return eps.length;
        }
        $scope.getEventNum = function(event){
            var eps = $scope.currentEvent.filter(function(item){
                return item.show!=false;
            });
            return eps.length;
        }
        $scope.getGroupByNum = function(event){
            var eps = $scope.groupbys.filter(function(item){
                return item.show!=false;
            });
            return eps.length;
        }
        $scope.addEventParams = function(event,obj){
            if(!event || !event.params || $scope.getEventParamsNum(event)>=$scope.maxparams){return false;};
            rmd ++;
            var tempparam = {id:"pam_"+rmd,pid:"param_"+rmd};
            if(obj){
                for(var k in obj){
                    tempparam[k] = obj[k];
                }
            }
            $scope.event.params.push(tempparam);
        }
        $scope.removeEvent = function(e){
            for(var i=0;i<$scope.currentEvent.length;i++){
                if($scope.currentEvent[i].id == e.id){
                    $scope.currentEvent[i].show = false;
                    break;
                }
            }
            $scope.eventLen = $scope.groupbys.length-1;
        }
        $scope.removeGroupby = function(g){
            for(var i=0;i<$scope.groupbys.length;i++){
                if($scope.groupbys[i].id == g.id){
                    $scope.groupbys[i].show = false;
                    break;
                }
            }
        }
        $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){
            var params = $scope.event.params;
            for(var j=0;j<params.length;j++){
                if(params[j].id == msg.id){
                    params[j] = msg;
                    break;
                }
            }
        });

        $scope.nameWin = function(flag){
            var eventInfo = $scope.getReportEventInfo();
            if(eventInfo.hasNull){
                ToolService.hideLoading();
                ToolService.showTips($scope.formTipMsg);
                return false;
            }
            ToolService.showAlp();
            $scope.wantSave = true;

            $scope.currentDefine = {};
            $scope.ename = "";
            $scope.isotherSave = false;
            if(angular.isDefined(flag)){ //编辑
                $scope.currentDefine = {id:0};
                $scope.isotherSave = true;
            }
        }
        $scope.lookReport = function(){
            var eventInfo = $scope.getReportEventInfo(),condition="";
            if(!eventInfo.hasNull){
                condition = JSON.stringify(eventInfo);
                UtilService.setItem($scope.appid,condition);
                $scope.isShowCache = true;
                $scope.query(condition);
            }
            else{
                ToolService.showTips($scope.formTipMsg);
                return false;
            }
        }
        $scope.closeWin = function(flag){
            $scope.wantSave = false;
            $scope.wantDelete = false;
            if(flag){
                if(flag == 2 && $scope.isotherSave){
                    $scope.currentDefine = $scope.define;
                }
            }
            ToolService.hideAlp();
        }
        $scope.getReportEventInfo = function(){
            var hasNull = false;
            var expressions = [] , group = [],
                eventInfo = {relation:$scope.eventRel,params:[]};
            $scope.currentEvent.filter(function(item){
                if(item.show){
                    var obj = {};
                    if(item.expression){
                        obj.expressionName = item.expressionName;
                        obj.format = item.formatId?item.formatId:"int";
                        obj.expression = item.expression;
                        var exLen = item.expressionName.match(/[\+\-\*\/]/g);
                        item.extip = exLen && exLen.length>5?"表达式最多可输入5个运算符（运算符包括+-*/）":"";
                        if(item.expressionName){
                            $scope.expresstionTransform(item);
                        }
                        item.error = !item.error && item.expressionName && !item.extip?false:true;
                    }else{
                        var e = $scope.eventList.filter(function(e){
                            return e.id == item.event;
                        });
                        obj.attr = item.property,
                        obj.event = item.event,
                        obj.operator = item.operator;
                        item.proerror = (!item.property && item.operator) || item.property ?false:true;
                        item.eventerror = e.length>0 && item.event?false:true;
                        item.tarerror = item.operator?false:true;
                    }
                    obj.name = item.name;
                    var verPar = {
                        name: {
                            key: 'spcname',
                            val: item.name
                        }
                    };
                    item.tip = formJudge(verPar);
                    item.nameerror = item.name && item.tip.succ?false:true;

                    var existName = $scope.currentEvent.filter(function(event){
                        return event.name == item.name && event.id!=item.id && event.show;
                    });
                    if (existName && existName.length>0) {item.nameerror=true;}
                    if(item.nameerror || item.error || item.proerror
                        || item.eventerror || item.tarerror){
                            hasNull = true;
                    }
                    expressions.push(obj);

                }
            });
            $scope.groupbys.filter(function(item){
                if(item.show){
                    var obj = {};
                    obj.name = item.dimenId;
                    obj.type = item.type;
                    item.groerror = item.dimenId?false:true;
                    var existGroup = $scope.groupbys.filter(function(gro){
                        return gro.dimenId == item.dimenId && gro.id != item.id && gro.show && item.type == gro.type;
                    });
                    if (existGroup && existGroup.length>0) {item.groerror=true;}
                    if(item.groerror){
                        hasNull = true;
                    }
                    group.push(obj);
                }
            });
            eventInfo.expressions = expressions;
            eventInfo.group = group;
            $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.ename && $scope.currentDefine.id)){
                eventInfo.hasNull = true;
            }
            $scope.enameerror = !$scope.ename && $scope.currentDefine.id?true:false;
            return eventInfo;

        }
        $scope.save = function(flag){
            var doSave = function(){
                var par = {
                    name: $scope.ename,
                    app:$scope.appid
                };
                var eventInfo = $scope.getReportEventInfo();
                if(!eventInfo.hasNull){
                    par.eventName = eventInfo.event;
                    par.eventCondition = JSON.stringify(eventInfo);
                }
                else{
                    ToolService.showTips($scope.formTipMsg);
                    return false;
                }
                var savePM = null,txtTips = "添加成功";
                if($scope.currentDefine.id && flag!=2){
                    par.id = $scope.currentDefine.id;
                    savePM = HttpService.putInfo("mng/eventstats/complicated/update",par);
                    txtTips = "修改成功";
                }else{
                    savePM = HttpService.postInfo("mng/eventstats/complicated/create",par);
                }

                ToolService.showLoading();
                savePM.then(function(data){
                    $scope.closeWin(1);
                    ToolService.hideLoading();
                    ToolService.showTips(txtTips);
                    if($scope.currentDefine.id && flag!=2){
                        $scope.queryInfoByApp(2,$scope.currentDefine.id);
                        $scope.currentDefine = {};
                    }
                    else{
                       $scope.queryInfoByApp(1);
                       $rootScope.operSubmitData("删除");
                       if($scope.isShowCache){
                          localStorage.removeItem($scope.appid);
                       }
                    }

                });
            }
           // if(!$scope.currentDefine.id){
                var verPar = {
                    name: {
                        key: 'spcname',
                        val: $scope.ename
                    }
                };
                $scope.tip = formJudge(verPar);
                if(UtilService.isNullStr($scope.ename) || $scope.tip.succ != true){
                    ToolService.showTips("事件分析名称请输入20个汉字以内名称，允许字符为中英文数字_-");
                    return false;
                }
                else{
                    ToolService.showLoading();
                    var existPM = HttpService.getInfo("mng/eventstats/checkName/"+$scope.appid,{eventStatsName:$scope.ename});
                    existPM.then(function(data){
                        if(data!=true && (!$scope.currentDefine.id || ($scope.define.name!=$scope.ename || flag==2))){
                            ToolService.hideLoading();
                            ToolService.showTips("事件分析名称已存在");
                        }
                        else{
                           doSave();
                        }
                    });
                }
            // }
            // else{
            //     ToolService.showLoading();
            //     var existPM = HttpService.getInfo("mng/eventstats/checkName/"+$scope.appid,{eventStatsName:$scope.ename});
            //     existPM.then(function(data){
            //         if(data!=true && ($scope.define.name!=$scope.ename || flag==2)){
            //             ToolService.hideLoading();
            //             ToolService.showTips("名称已存在");
            //         }
            //         else{
            //            doSave();
            //         }
            //     });
            // }
        }

        $scope.eventChartConfig = {
            color:ToolService.getTenColors(),
            namesub:[]
        };
        $scope.lsChange = rmd;
        $scope.$on('flipinfo',function(e,msg){
            $scope.flipPage = msg;
            $scope.lsChange++;
        });
        $scope.showTempLook = false;
        $scope.rateList = []; //所有指标
        $scope.rateListed = []; //选中指标
        $scope.group_List = []; //所有分组
        $scope.grouped_List = []; //选中分组
        $scope.istranfer = false;//是否行列转换
        $scope.ispercent = false;//是否显示占比
        $scope.isshowTotal = false;//是否显示汇总
        $scope.percentPre = "rate_"; //显示比例时的前缀，占比是'rate_'，同比?
        var queryParams = {};
        $scope.chartList = [{id:"line",name:"折线图",platform:"line"},
                            {id:"columnstack",name:"柱状图",platform:"columnstack"},
                            {id:"pie",name:"饼状图",platform:"pie"}];
        $scope.chartTypeInit = "line";

        var numIndexs = ['一','二','三','四','五','六','七','八','九','十'];
        $scope.query = function(condition){
            $scope.showEventWin = false;
            $scope.rateFlag = 1;

            var params = ToolService.getParams($scope);
            params.datatype = 'list';
            params.viewflag = $scope.timeFlag;
            var ddID = null,ddname = "事件分析";
            if(condition){ //不保存直接应用
                params.eventCondition = condition;
                $scope.showTempLook = true;
                ddname += $scope.getTrendTitle();
            }
            else{
                var cache = UtilService.getItem($scope.appid);
                params.eventCondition = $scope.isShowCache?cache:$scope.define.eventCondition;
                $scope.showTempLook = $scope.isShowCache?true:false;

                ddID = $scope.define.id;
                ddname += '-' + $scope.define.name;
            }
            params.eventCondition = encodeURIComponent(params.eventCondition);

            queryParams = params;
            $scope.totalList = [];
            $scope.eventChartLoading = true;
            $scope.chartListLoading = true;
            var areport = "eventstats/complicated/query/"+$scope.appid;

            var listPM = HttpService.getInfo(areport,params);
            listPM.then(function(data){
                var format = data.format,formatjson = {};
                format.filter(function(f){
                    formatjson[f.field] = f.format;
                });
                data.format = formatjson;

                $scope.trendList = data;
                $scope.totalList = data.totalval;

                $scope.infoList = data.val;
                $scope.eventChartLoading = false;

                $scope.rateList = data.selectfield;
                $scope.totalVal = {};
                $scope.rateList.filter(function(rate){
                    $scope.totalList.filter(function(total){
                        if(!$scope.totalVal[rate]){
                            $scope.totalVal[rate] = 0;
                        }
                        $scope.totalVal[rate] += total[rate];
                    });
                });
                $scope.group_List = $scope.getGroupNames(data.groupfield);
                $scope.grouplen = data.groupfield.length;

                if($scope.infoList.length>0){
                    $scope.limit();
                    if($scope.group_List.length == 0){ //没有分组情况，不显示占比
                        $scope.ispercent = false;
                    }
                    $scope.changeChartData($scope.chartType);
                }
                else{
                    $scope.myChartData = ToolService.noDataChart();
                }

                $scope.sortCol = "";
                $scope.sortCol1 = "";
                $scope.chartListLoading = false;

                if($scope.istranfer){
                    $scope.transformList();
                }
                else{
                    $scope.pageAllList = $scope.infoList;
                    $timeout(function(){
                        if($scope.listkey){
                            $scope.reverse1 = true;
                            $scope.order($scope.listkey[0], true,0);
                        }
                    },300);
                }

                var condjson = JSON.parse(decodeURIComponent(params.eventCondition)).expressions,newjson = [];

                ++rmd;
                condjson.filter(function(item,index){
                    item.id = item.orderindex =  rmd + index;
                    item.indexname = numIndexs[index];
                    newjson.push(item);
                });
                $scope.condList = newjson;

                $scope.myChartDataCondition = ToolService.getChartConditions(ddname,areport,params,"complicatedevents",ddID);
            },function(data){
                $scope.myChartData = ToolService.noDataChart();
                $scope.infoList = [];
                $scope.totalList = [];
                $scope.eventChartLoading = false;
                $scope.chartListLoading = false;
            });
        }
        $scope.$on("chartTypeId",function(e,msg){
            if($scope.trendList){
               $scope.chartType = msg.info.id;
               $scope.chartTypeInit = $scope.chartType;
               $scope.changeChartData();
            }
        });
        $scope.limit = function(){
            $scope.chartType = $scope.group_List.length == 0 && $scope.chartType == 'pie'?'line':$scope.chartType;
            $scope.chartTypeInit = $scope.chartType;
            if($scope.chartType == 'line'){
                $scope.rateListed = $scope.rateList.slice(0,1);
                $scope.grouped_List = $scope.group_List.slice(0, 5);
                if($scope.grouped_List.length < 2){
                    $scope.rateListed = $scope.rateList.slice(0,5);
                }
            }else if($scope.chartType == 'columnstack'){
                $scope.rateListed = $scope.rateList.slice(0,2);
                $scope.grouped_List = $scope.group_List.slice(0, 3);
            }else{
                $scope.rateListed = $scope.rateList.slice(0,2);
                $scope.grouped_List = $scope.group_List.slice(0);
            }

        }
        $scope.chartType = "line";
        //得到图的分组，同时处理成分页需要的数据格式
        $scope.getGroupNames = function(gns){
            var names = [],listArr = [];
            if(gns.length == 0){ //没有分组情况下的处理
                var hasgroup = $scope.trendList.groupfield.length>0;
                $scope.trendList.val.filter(function(item,index){
                    var listChild = {};
                    if(!hasgroup){
                        listChild = item;
                    }

                    if(item.firstDateRow){
                        listChild.ds = item.ds;
                        listChild.groupnames = item.ds;
                        if(hasgroup){
                            listChild.children = $scope.trendList.val.slice(index,index+item.rowNum);
                        }
                        else{
                            listChild.rsnum = 1;
                            listChild.isrs = true;
                        }
                        listArr.push(listChild);
                    }
                });
            }
            else{
                $scope.trendList.val.filter(function(item,index){
                    var temps = [],listChild = {};
                    gns.filter(function(k){
                        temps.push(item[k]);
                    });

                    var tn = temps.join(","),idx = names.indexOf(tn);
                    item.groupnames = tn;
                    if(idx == -1){
                        names.push(tn);
                    };

                    if(item.firstDateRow){
                        listChild.ds = item.ds;
                        listChild.groupnames = tn;
                        listChild.children = $scope.trendList.val.slice(index,index+item.rowNum);
                        listArr.push(listChild);
                    }

                });
            }
            $scope.detailAllList = listArr;
            if($scope.istranfer){
                $scope.transformList();
            }
            else{
                $scope.lsChange++;
            }
            return names;
        }
        //页数变动或者数据变动，重新获取当前页展示数据
        $scope.$watch("lsChange",function(){
            if($scope.flipPage && $scope.detailAllList){
                var start = $scope.flipPage.start+1,
                        end = $scope.flipPage.end - 1,
                        pagen = $scope.flipPage.pagen,
                        lists = [],
                        index = 0,
                        sepcObj = null,
                        dataAllArr = [];

                if($scope.istranfer){
                    dataAllArr = $scope.transfromAllList;
                    $scope.listname = $scope.transformTitle.name;
                    $scope.listkey = $scope.transformTitle.key;
                }
                else{
                    dataAllArr = $scope.detailAllList;
                    $scope.listname = $scope.trendList.name;
                    $scope.listkey = $scope.trendList.columnkey;
                }
                // $scope.colsStyle = ToolService.getTableColsWidth($scope.listname);

                if($scope.trendList.groupfield.length>0){
                    for(var i=0;i<dataAllArr.length;i++){
                        var children = dataAllArr[i].children,rs = 0;
                        for(var j=0;j<children.length;j++){
                            if(index > $scope.flipPage.start && index < $scope.flipPage.end){
                                if(rs==0){
                                    sepcObj = children[j];
                                    sepcObj.rsnum = 0;
                                    sepcObj.isrs = true;
                                }
                                else{
                                    children[j].isrs = false;
                                }
                                rs++;
                                sepcObj.rsnum++;
                                lists.push(children[j]);
                            }
                            index ++;

                            if(pagen == lists.length){
                                break;
                            }
                        }
                    }
                    $scope.currentDetailList = lists;
                }
                else{
                    $scope.currentDetailList = dataAllArr.slice(start,end);
                }
            }
            else{
                $scope.currentDetailList = [];
            }
        });
        var refreshList = function(){
            if($scope.flipPage.start > 5){
                $scope.listf5 = ++rmd;
            }
            else{
                $scope.lsChange++;
            }
        }
        //行列转换或者占比
        $scope.changeFlag = function(flag){
            if(flag == 1){
                $scope.istranfer = !$scope.istranfer;
                if($scope.group_List.length == 0){
                    $scope.ispercent = false;
                }
                if($scope.istranfer){
                    $scope.transformList();
                }
                else{
                    $scope.pageAllList = $scope.infoList;
                    refreshList();
                }
            }
            else{
                $scope.ispercent = !$scope.ispercent;
            }
        }
        //行转换成列
        $scope.transformList = function(){
            var transArr = [],
                titlename = $scope.trendList.name.slice(1,$scope.trendList.groupfield.length+1),
                titlekey = $scope.trendList.groupfield.slice(0);

            titlename.push('指标');
            titlekey.push("_myzb");

            titlename.push('合计');
            titlekey.push("_total");

            var zero = {},allList = [];
            $scope.trendList.key.filter(function(key,index){
                titlename.push(key);
                titlekey.push("_ds"+(index+1));
                zero["_ds"+(index+1)] = 0;
            });
            $scope.totalList.filter(function(item){
                var temps = [],transobj = {children:[]};
                $scope.trendList.groupfield.filter(function(k){
                    temps.push(item[k]);
                    transobj[k] = item[k];
                });
                transobj.groupnames = temps.join(",");
                transobj.rsnum = $scope.trendList.selectfield.length;

                $scope.trendList.selectfield.filter(function(s){
                    var zb = UtilService.cloneJSON(transobj);
                    zb._myzb = s;
                    zb._total = item[s];
                    // zb["rate__total"] = item["rate_"+s];

                    for(var k in zero){
                        zb[k] = zero[k];
                    }
                    if(temps.length>0){
                        var prerate = 0;
                        $scope.detailAllList.filter(function(info){
                            info.children.filter(function(child){
                                if(transobj.groupnames == child.groupnames){
                                    var dIdx = $scope.trendList.key.indexOf(info.ds);

                                    var nowrate = child[s],rateprecent = 0;
                                    zb["_ds"+(dIdx+1)] = nowrate;
                                    if(prerate!=0){
                                        rateprecent = (nowrate - prerate)/prerate*100;
                                    }
                                    prerate = nowrate;
                                    zb["rate__ds"+(dIdx+1)] = rateprecent;
                                }
                            });
                        });
                        transobj.children.push(zb);
                        allList.push(zb);
                    }
                    else{ //没有分组情况
                        var prerate = 0;
                        $scope.detailAllList.filter(function(info){
                            var dIdx = $scope.trendList.key.indexOf(info.ds);

                            var nowrate = info[s],rateprecent = 0;
                            zb["_ds"+(dIdx+1)] = nowrate;
                            if(prerate!=0){
                                rateprecent = (nowrate - prerate)/prerate*100;
                            }
                            prerate = nowrate;
                            zb["_ds"+(dIdx+1)] = info[s];
                            zb["rate__ds"+(dIdx+1)] = rateprecent;
                        });
                        transArr.push(zb);
                        allList.push(zb);
                    }

                });
                if(temps.length>0){
                    transArr.push(transobj);
                }

            });
            //重新的表头
            $scope.transformTitle = {
                key:titlekey,
                name:titlename
            }

            $scope.transfromAllList = transArr;
            $scope.pageAllList = allList;
            refreshList();
        }
        $scope.checkAll = function(){
            $scope.ischeckall = !$scope.ischeckall;
            $scope.grouped_List = $scope.ischeckall?UtilService.cloneJSON($scope.group_List):[];
            $scope.changeChartData();
         }
        //图表加显示指标
        $scope.changeRate = function(rate){
            if(!$scope.canAdd(1,rate)){return false;}

            var idx = $scope.rateListed.indexOf(rate);
            if(idx>-1){
                $scope.rateListed.splice(idx,1);
            }
            else{
                $scope.rateListed.push(rate);
            }

            $scope.changeChartData();
        }
        //图表加显示分组
        $scope.changeGroup = function(group){
            if(!$scope.canAdd(2,group)){return false;}

            var idx = $scope.grouped_List.indexOf(group);
            if(idx>-1){
                $scope.grouped_List.splice(idx,1);
            }
            else{
                $scope.grouped_List.push(group);
            }
            $scope.changeChartData();
        }
        //当前是否还能添加指标或者分组，flag:1指标，2分组
        var lengedMax = 10;
        $scope.canAdd = function(flag,cell){
            var arr = [];
            if(flag==1){
                arr = $scope.rateListed;
            }
            else{
                arr = $scope.grouped_List;
            }
            var idx = arr.indexOf(cell);
            if(idx==-1){
                var rl = $scope.rateListed.length,gl = $scope.grouped_List.length;
                if($scope.chartType == 'line'){
                    if(flag == 1){
                        return (rl+1)*gl <= lengedMax;
                    }
                    else{
                        return rl*(gl+1)<= lengedMax;
                    }
                }else{
                    if(flag == 1){
                        return rl+1 <= ($scope.chartType == 'columnstack'?3:2);
                    }
                    else{
                        return gl+1 <= ($scope.chartType == 'columnstack'?5:$scope.group_List.length);
                    }
                }

            }
            return true;
        }
        //根据已选的指标和分组，重新生成图表数据
        $scope.changeChartData = function(){
            $scope.eventChartConfig.namesub = [];
            var xKey =  $scope.trendList.key,tempData = {
                key:xKey,
                val:[],
                name:[],
                rmd : ++rmd
            };
            var zero = [];
            xKey.filter(function(d,index){
                zero.push(0);
            });
            if($scope.chartType == "pie"){
                $scope.ischeckall = $scope.group_List.length==$scope.grouped_List.length?true:false;
                $scope.eventChartConfig.flag = false;
                if($scope.rateListed.length>2){
                    $scope.rateListed = $scope.rateListed.slice(0,2);
                }
                var json = {}, grList = UtilService.cloneJSON($scope.grouped_List);
                $scope.rateListed.filter(function(rate){
                    var arr = [];
                    var totalval = 0;
                    $scope.grouped_List.filter(function(group){
                         $scope.totalList.filter(function(total){
                             var groupnames = "";
                             var val = {};
                             $scope.trendList.groupfield.filter(function(gid){
                                groupnames += total[gid]+",";
                             });
                             if(group == groupnames.slice(0,-1)){
                                 arr.push(total[rate]);
                                 totalval += total[rate];
                             }
                         });
                    });
                    if(grList.indexOf("其他")>-1){
                        grList.splice(grList.indexOf("其他"),1);
                    }
                    if($scope.totalVal[rate]-totalval>0 && $scope.group_List.length>0){
                        arr.push($scope.totalVal[rate]-totalval);
                        grList.push("其他");
                    }
                    json[rate] = arr;
                });
                $scope.myChartData.key = $scope.rateListed;
                $scope.myChartData.name = grList;
                if(!angular.equals({}, json)){
                    $scope.myChartData.val = [json];
                }else{
                    $scope.myChartData.val = [];
                }
            }else{
                if($scope.chartType == "columnstack"){
                    $scope.eventChartConfig.flag = true;
                    if($scope.grouped_List.length>5){
                        $scope.grouped_List = $scope.grouped_List.slice(0,5);
                    }
                }else{
                    $scope.eventChartConfig.flag = false;
                    var groLen  = $scope.rateListed.length==1?10:$scope.rateListed.length>2?3:5;
                    $scope.grouped_List = $scope.grouped_List.slice(0,groLen);
                }
                $scope.eventChartConfig.namesub = [];
                $scope.trendList.val.filter(function(item){
                    var date = item.ds,gname = item.groupnames;

                    if($scope.grouped_List.indexOf(gname)>-1 || $scope.grouped_List.length == 0){
                        var dateIdx = xKey.indexOf(date);

                        $scope.rateListed.filter(function(rate){
                            var format = $scope.trendList.format[rate];
                            var chartname = gname + rate;
                            if($scope.grouped_List.length == 0){
                                chartname = rate.substring(1); //因为加了下划线，要去掉
                            }
                            var dataIdx = tempData.name.indexOf(chartname),dataArr = [];

                            if(dataIdx == -1){
                                tempData.name.push(chartname);
                                $scope.eventChartConfig.namesub.push(format=='percent'?"%":"");
                                dataArr = UtilService.cloneJSON(zero);
                                tempData.val.push(dataArr);
                            }
                            else{
                                dataArr = tempData.val[dataIdx];
                            }

                            var rateNum = Number(item[rate]);
                            if(format == 'percent'){
                                rateNum =  UtilService.decimal2(rateNum*100,2);
                            }
                            else if(format == 'int'){
                                rateNum =  Math.round(rateNum);
                            }
                            else
                            {
                                rateNum =  UtilService.decimal2(rateNum,2);
                            }

                            dataArr[dateIdx] = rateNum;
                        });
                    }
                });
                $scope.myChartData = tempData;
            }
        }
        $scope.substrName = function(name){
            return name.substring(1);
        }

        var orderBy = $filter('orderBy');
        $scope.sortCol = "";
        $scope.sortCol1 = "";
        $scope.order = function(predicate, reverse,idx) {
            var outorder = false;
            if($scope.istranfer && idx < $scope.trendList.groupfield.length){
                outorder = true;
            }
            else{
                outorder = idx==0;
            }
            var dataAllArr = [];
            if($scope.istranfer){
                dataAllArr = $scope.transfromAllList;
            }
            else{
                dataAllArr = $scope.detailAllList;
            }

            if(!outorder && $scope.trendList.groupfield.length == 0){ //么有分组情况
                $scope.sortCol = predicate;
                $scope.mysort(dataAllArr, predicate, reverse);
            }
            else{
                if(!outorder){
                    $scope.sortCol = predicate;
                    $scope.mysort($scope.totalList, predicate, reverse);
                    dataAllArr.filter(function(item){
                        $scope.mysort(item.children, predicate, reverse);
                    });
                }
                else{//第一列的日期排序
                    $scope.sortCol1 = predicate;
                    $scope.mysort(dataAllArr, predicate, reverse);
                }
            }

            refreshList();
        };
        $scope.mysort = function(tempArr,key,flag){
            if (flag==true) {
                tempArr.sort(function(x, y) {
                    return x[key] == y[key] ? 0 : (x[key] > y[key] ? -1 : 1);
                });
            } else {
                tempArr.sort(function(x, y) {
                    return x[key] == y[key] ? 0 : (x[key] > y[key] ? 1 : -1);
                });
            }
        }
        $scope.$watch("appid+defineFlag+timeFlag+date.startDate+date.endDate",function(e){
            if(angular.isDefined($scope.appid) && (angular.isDefined($scope.defineFlag) || $scope.isShowCache)){
                $scope.query();
            }
        });
        $scope.$watch("appid",function(n){
            if(angular.isDefined(n)){
                $scope.lengedNames = [];
                $scope.defineFlag = undefined;
                $scope.queryInfoByApp(5);
            }
        });

        var haschangeOrder = false;
        $scope.showOrderList = function(){
            $scope.showOrderWin = true;
            haschangeOrder = false;
            ToolService.showAlp();
        }
        $scope.closeOrder = function(){
            $scope.showOrderWin = false;
            ToolService.hideAlp();
        }
        $scope.okOrderWin = function(){
            $scope.closeOrder();
            if(!haschangeOrder){return false;}

            ToolService.showLoading();
            var condition = JSON.parse(decodeURIComponent($scope.define.eventCondition));
            $scope.condList.filter(function(item){
                delete item.id;
                delete item.orderindex;
                delete item.indexname;
            });
            condition.expressions = $scope.condList;
            var par = {
                name: $scope.define.name,
                app:$scope.appid,
                id:$scope.define.id,
                eventCondition:JSON.stringify(condition)
            };
            var savePM = HttpService.putInfo("mng/eventstats/complicated/update",par);
            savePM.then(function(data){
                ToolService.hideLoading();
                $scope.queryInfoByApp(2,$scope.define.id);
            });

        }
        $scope.$on("dragorder",function(event,msg){
            var curid = msg.id,replaceId = msg.index;
            var curIdx = 0,replaceIdx = 0;

            $scope.condList.filter(function(item,index){
                if(item.id === curid){
                    curIdx = index;
                }
                if(item.id === replaceId){
                    replaceIdx = index;
                }
            });

            var newArr = UtilService.cloneJSON($scope.condList);
            if(curIdx > 0 || replaceIdx > 0){
                var curobj =  UtilService.cloneJSON(newArr[replaceIdx]);
                newArr.splice(replaceIdx,1,newArr[curIdx]);
                newArr.splice(curIdx,1,curobj);
            }
            ++rmd;
            newArr.filter(function(item,index){
                item.id = item.orderindex =  rmd + index;
                item.indexname = numIndexs[index];
            });

            $scope.$apply(function(){
                $scope.condList = newArr;
            });
            haschangeOrder = true;
        });
    }

    var sectionTool = {
        //获取光标位置
        getCursortPosition:function(textDom) {
            var cursorPos = 0;
            if (document.selection) {
              // IE Support
                textDom.focus ();
                var selectRange = document.selection.createRange();
                selectRange.moveStart ('character', -textDom.value.length);
                cursorPos = selectRange.text.length;
            }
            else if (textDom.selectionStart || textDom.selectionStart == '0') {
              // Firefox support
                cursorPos = textDom.selectionStart;
            }
            return cursorPos;
        },
        //设置光标位置
        setCaretPosition:function(textDom, pos){
             if(textDom.setSelectionRange) {
              // IE Support
                textDom.focus();
                textDom.setSelectionRange(pos, pos);
             }
             else if (textDom.createTextRange) {
              // Firefox support
                var range = textDom.createTextRange();
                range.collapse(true);
                range.moveEnd('character', pos);
                range.moveStart('character', pos);
                range.select();
             }
        },
        //光标后插入文本
        insertAfterText:function(textDom, value) {
            var selectRange;
            if (document.selection) {
              // IE Support
                textDom.focus();
                selectRange = document.selection.createRange();
                selectRange.text = value;
                textDom.focus();
            }
            else if (textDom.selectionStart || textDom.selectionStart == '0') {
              // Firefox support
                var startPos = textDom.selectionStart;
                var endPos = textDom.selectionEnd;
                var scrollTop = textDom.scrollTop;
                textDom.value = textDom.value.substring(0, startPos) + value + textDom.value.substring(endPos, textDom.value.length);
                textDom.focus();
                textDom.selectionStart = startPos + value.length;
                textDom.selectionEnd = startPos + value.length;
                textDom.scrollTop = scrollTop;
            }
            else {
                textDom.value += value;
                textDom.focus();
            }
        }
    }
})();
