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

    function intelligentpathCtrl($scope,$rootScope,HttpService,ToolService,UtilService,$filter,$timeout,$stateParams){
        var fid = $stateParams.pageid;
        var rmd = new Date().getTime();
        //获取下拉框内容
        $scope.querySelectInfos = function() {
            //用户分组
            var groupsPM = HttpService.getInfo("mng/usergroup/find/"+$scope.appid);
            groupsPM.then(function(data){
                data.unshift({id:0,name:"请选择用户分组"})
                $scope.groupsList = data;
                $scope.groupinitname = "请选择用户分组";
                $scope.groupInit = 0;
            });

            //时间单位
            $scope.timeUnitList = [
                {id:1,name:"秒"},
                {id:60,name:"分钟"},
                {id:3600,name:"小时"}
            ];
            $scope.timeinitname = "分钟";
            $scope.timeUnitInit = 60;
            //事件类型
            $scope.eventTypeList = [
                {id:true,name:"起始事件"},
                {id:false,name:"结束事件"}
            ];
            $scope.typeinitname = "起始事件";
            $scope.eventTypeInit = true;
        }
        $scope.queryInfoByApp = function(flag,dID){
            if(angular.isUndefined(flag) || flag==5){
                //app下所有事件
                var eventPM = HttpService.getInfo($scope.appid +"/event/find");
                eventPM.then(function(data){
                    $scope.eventListAll = data;
                    $scope.eventList = $scope.eventListAll.filter(function(item){
                        return item.eventName != 'install';
                    });
                });
                //通用属性
                // $scope.dimenId = "-all";
                // var profilePM = HttpService.getInfo($scope.appid+"/event/find/value");
                // profilePM.then(function(data){
                //     data.unshift({"dimensionType":"whole",id:"-all",name:"总体",type:"string"});
                //     $scope.dimensionList = data;
                // });
            }
            //获取路径列表
            var definePM = HttpService.getInfo("mng/intelligentpath/"+$scope.appid+"/list");
            $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]);
                    }
                }
                if(flag == 5){
                    $scope.dimenRmd = ++rmd;
                }
            });
        }
        //已保存的事件
        // $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;
            $scope.wantDelete = true;
            ToolService.showAlp();
        }
        $scope.doDelete = function(){
            $scope.closeWin();
            ToolService.showLoading();
            var deletePM = HttpService.deleteInfo("mng/intelligentpath/"+$scope.delDefine.id+"/delete");
            deletePM.then(function(){
                ToolService.showTips("删除成功");
                $scope.queryInfoByApp(1);
                ToolService.hideLoading();
                $rootScope.operSubmitData("删除");
            });
        }

        $scope.date = ToolService.getLastDays(-3,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 strSort = function(str){
            str = str.split(",");
            str.sort(function(a,b) {
                return a.localeCompare(b)
            });
            return str.join(",");
        };
        $scope.$on("groupId",function(e,msg){
            $scope.groupId = msg.info.id;
        });
        $scope.$on("eventTypeId",function(e,msg){
            $scope.eventTypeId = msg.info.id;
        });
        $scope.$on("timeUnitId",function(e,msg){
            $scope.timeUnitId = msg.info.id;
        });
        $scope.$on("eventIds",function(e,msg){

            if(strSort($scope.eventIds) == strSort(msg.info)) return;
            $scope.eventIds = msg.info;
            if(!$scope.eventIds){
                $scope.eventinitname = "请先选取关注事件";
                $scope.eventId = "";
                $scope.enull = ++rmd;
                return;
            }
            if($scope.filterEvents == $scope.eventIds.split(","))return;
            // $scope.eventIds += ",";
            var ids = $scope.eventIds.split(",");
            $scope.filterEvents = $scope.eventList.filter(function(item){
                return ids.indexOf(item.eventName)>-1;
            });
            if($scope.filterEvents.length>1){
                $scope.eventTip = "";
                if($scope.params){
                    $scope.params.eventsnull = false;
                }
            }
            if($scope.eventIds.indexOf($scope.eventId)>-1){
                $scope.eventInit = $scope.eventId;
            }
            if(($scope.filterEvents && $scope.filterEvents.length>0 && !$scope.eventInit)
                || (ids.indexOf($scope.eventInit)<0)){
                $scope.eventinitname = "请选取目标事件";
                $scope.eventInit = "";
                $scope.eventId = "";
                $scope.eventRel = "and";
                $scope.event = {};
                $scope.enull = ++rmd;
            }
            // $scope.eventIds = $scope.eventIds.slice(0,-1);
        });
        $scope.$on("eventId",function(e,msg){
            if($scope.eventId == msg.info.eventName)return;
            $scope.changeEvent(msg.info);
            $scope.eventId　= msg.info.eventName;
        });
        $scope.$watch("time",function(e){
            if($scope.time){
                $("#timeId").removeClass("iptnull");
            }
        });
        $scope.changeEvent = function(event,obj){
            if(obj){ //编辑查找
                $scope.initParmas();
                var nowEvents = $scope.eventList.filter(function(item){
                    return item.eventName == obj.event;
                });
                event = nowEvents[0];
                $scope.eventinitname = event.eventNameAlias;
                $scope.eventRel = obj.relation;
            }
            $scope.eventId = event.eventName;

            var set = function(){
                $scope.event = {
                    id:"evt_"+rmd,
                    params:[],
                    paramsList:event.profiles
                }
                $scope.propertyList = event.firstLevelAttr;
                $scope.sumtypeList = event.secondLevelAttr;

                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);
                        });
                    });
                }
                else{
                    if($scope.propertyList && $scope.propertyList.length>0){
                      $scope.propertyInit = $scope.propertyList[0].attr;
                    }
                    else{
                      $scope.propertyInit = '';
                    }
                    $scope.prorefresh = ++rmd;
                }
            }
            if(event.firstLevelAttr){
                set();
            }
            else{

                var evtvals = [],temp = {event:event.eventName,param:[]};
                if(obj){
                    obj.params.filter(function(pitem){
                        temp.param.push(pitem.attr);
                    });
                    evtvals.push(temp);
                }

                ToolService.showLoading();
                var evtprofilePM = HttpService.getInfo($scope.appid+"/event/find/param?names="+event.eventName+"&params="+encodeURIComponent(JSON.stringify(evtvals)));
                evtprofilePM.then(function(pros){
                    pros.filter(function(evt){
                        for(var i=0;i<$scope.filterEvents.length;i++){
                            if(evt.eventName == $scope.filterEvents[i].eventName){
                                $scope.filterEvents[i].profiles = evt.profiles;
                                $scope.filterEvents[i].firstLevelAttr = evt.firstLevelAttr;
                                $scope.filterEvents[i].secondLevelAttr = evt.secondLevelAttr;
                                break;
                            }
                        }
                    });
                    set();
                    ToolService.hideLoading();
                });
            }
        }
        $scope.canSave = function(){
            var can = false;
            if(!$scope.eventIds && !$scope.time && !$scope.eventId
                && !$scope.groupId && $scope.eventTypeId && $scope.timeUnitId==60){
                can = true;
            }
            return can;
        }
        $scope.initParmas = function(){
            $scope.eventinitname = "请先选取关注事件";
            $scope.eventinitnames = "请选取关注事件";
            $scope.typeinitname = "起始事件";
            $scope.groupinitname = "请选择用户分组";
            $scope.timeinitname = "分钟";
            $scope.time = 20;
            $scope.eventinitIds = ++rmd;
            $scope.eventTypeInit = true;
            $scope.groupInit = ++rmd;
            $scope.eventInit = ++rmd;
            $scope.eventIds = "";
            $scope.eventTypeId = true;
            $scope.timeUnitInit = 60;
            $scope.timeUnitId = 60;
            $scope.groupId = 0;
            $scope.groupInit = 0;
            $scope.eventId = "";
            $scope.eventRel = "and";
            $scope.filterEvents = [];
            $scope.event = {};
            $scope.evtrefresh = ++rmd;
        }
        $scope.changeRel = function(){
            $scope.eventRel = $scope.eventRel == "and" ? "or" : "and";
        }
        $scope.initCondition = function(){
            $scope.initParmas();
        }
        $scope.showEventWin = false;
        $scope.addPath = function(flag,n){
            var cache = UtilService.getItem("path_"+$scope.appid);
            if(flag==1 || cache){ //编辑
                $scope.isShowCache = flag==0 || n;
                if((!$scope.define.id && !$scope.isShowCache) || (!cache && $scope.isShowCache)){return false;}
                $scope.eventTip = "";
                $scope.currentDefine = $scope.isShowCache?JSON.parse(cache):$scope.define;
                $scope.ename = $scope.isShowCache?"新增智能路径":$scope.define.name;
                var eventCondition = JSON.parse($scope.currentDefine.eventCondition);
                $scope.changeEvent(null,eventCondition);
                $scope.isEditInfo = true;
                $scope.time =  $scope.currentDefine.session;
                var eventNames = $scope.currentDefine.events.split(",");
                $scope.eventIds = $scope.currentDefine.events;
                $scope.filterEvents = $scope.eventList.filter(function(item){
                    return eventNames.indexOf(item.eventName)>-1;
                });
                $scope.groupInit = $scope.currentDefine.userGroup;
                $scope.eventId = $scope.currentDefine.targetEvent;
                $scope.eventTypeInit = $scope.currentDefine.startOrEnd;
                $scope.timeUnitInit = $scope.currentDefine.sessionUnit;
                $scope.eventInit = $scope.currentDefine.targetEvent;
                $scope.eventTypeId = $scope.currentDefine.startOrEnd;
                $scope.eventinitIds = $scope.currentDefine.events;
            }
            else{
                $scope.currentDefine = {};
                $scope.isEditInfo = false;
                $scope.initParmas();
                $scope.params = {};
                $scope.eventTip = "";
                $scope.isShowCache = false;
            }
            $scope.showEventWin = true;
        }
        $scope.addFirst = false;
        $scope.addFirstPath = function(){
            $scope.addFirst = true;
            $scope.showEventWin = true;
            $scope.currentDefine = {};
            $scope.initParmas();
        }
        $scope.closeAddWin = function(){
            $scope.showEventWin = false;
            $scope.addFirst = false;
            $scope.isEditInfo = true;
        }
        $scope.maxparams = 10;
        $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.addEventParams = function(event,obj){
            if(!event || !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){
            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){
            // if(!$scope.event.id){return false;}
            var eventInfo = $scope.getReportEventInfo();
            $scope.getPathParms(eventInfo);
            if($scope.eventIds.split(",").length<2){
                $scope.eventTip = "请至少选择2个关注事件";
                $scope.params.eventsnull = true;
            }
            if(eventInfo.hasNull || $scope.params.isnull || $scope.eventTip){
                ToolService.hideLoading();
                ToolService.showTips($scope.formTipMsg);
                return false;
            }

            // $scope.showEventWin = 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(){
            // if(!$scope.event.id){return false;}

            var eventInfo = $scope.getReportEventInfo(),condition="";
            $scope.getPathParms(eventInfo);
            if($scope.eventIds.split(",").length<2){
                $scope.eventTip = "请至少选择2个关注事件";
                $scope.params.eventsnull = true;
            }
            if(!eventInfo.hasNull && !$scope.params.isnull && !$scope.eventTip){
                condition = JSON.stringify(eventInfo);
                $scope.isShowCache = true;
                $scope.query(condition);
            }
            else{
                ToolService.showTips($scope.formTipMsg);
                return false;
            }
        }
        $scope.closeWin = function(flag){
            $scope.wantSave = false;
            $scope.wantDelete = false;
            $scope.nodeDetail = false;
            if(flag){
                if(flag == 2 && $scope.isotherSave){
                    $scope.currentDefine = $scope.define;
                }
                else{
                    $scope.showEventWin = false;
                }
                $scope.showEventWin = true;
            }
            ToolService.hideAlp();
        }
        $scope.getPathParms = function(eventInfo){
            $scope.params = {};
            if(!$scope.time){
                $scope.params.timenull = true;
                $scope.params.isnull = true;
            }
            // if(!$scope.eventIds){
            //     $scope.params.eventsnull = true;
            //     $scope.params.isnull = true;
            // }
            // if($scope.eventTypeId==undefined){
            //     $scope.params.typenull = true;
            //     $scope.params.isnull = true;
            // }
            if(!eventInfo.event){
                $scope.params.eventnull = true;
                $scope.params.isnull = true;
            }
        }
        $scope.getReportEventInfo = function(){

            if(!$scope.event.params){return false;}
            var hasNull = false;
            var eventInfo = {event:$scope.eventId,relation:$scope.eventRel,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){
                eventInfo.hasNull = true;
            }
            return eventInfo;

        }
        $scope.save = function(){
            // if(!$scope.event.id){return false;}
            var doSave = function(){
                var par = {
                    name: $scope.ename,
                    app:$scope.appid,
                    events: $scope.eventIds,
                    userGroup: $scope.groupId,
                    startOrEnd: $scope.eventTypeId,
                    session: parseInt($scope.time),
                    sessionUnit: $scope.timeUnitId?$scope.timeUnitId:60
                };
                var eventInfo = $scope.getReportEventInfo();
                $scope.getPathParms(eventInfo);
                if($scope.eventIds.split(",").length<2){
                    $scope.eventTip = "请至少选择2个关注事件";
                    $scope.params.eventsnull = true;
                }
                if(!eventInfo.hasNull && !$scope.params.isnull && !$scope.eventTip){
                    par.targetEvent = eventInfo.event;
                    par.eventCondition = JSON.stringify(eventInfo);
                }
                else{
                    ToolService.showTips($scope.formTipMsg);
                    return false;
                }
                // if(par.events.indexOf(par.targetEvent) < 0){
                //     par.events += ","+par.targetEvent;
                // }
                var savePM = null,txtTips = "添加成功";
                if($scope.currentDefine.id){
                    par.id = $scope.currentDefine.id;
                    savePM = HttpService.putInfo("mng/intelligentpath/update",par);
                    txtTips = "修改成功";
                }else{
                    savePM = HttpService.postInfo("mng/intelligentpath/create",par);
                }

                ToolService.showLoading();
                savePM.then(function(data){
                    if(data.code == -6001){
                        ToolService.showTips(data.message);
                        return;
                    }
                    $scope.closeWin(1);
                    ToolService.hideLoading();
                    ToolService.showTips(txtTips);
                    if($scope.currentDefine.id){
                        $scope.queryInfoByApp(2,$scope.currentDefine.id);
                        $scope.currentDefine = {};
                    }
                    else{
                       $scope.queryInfoByApp(1);
                       $rootScope.operSubmitData("新建");
                       if($scope.isShowCache){
                            localStorage.removeItem("path_"+$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{
                    doSave();
                }
            }
            else{
                doSave();
            }
        }

        $scope.eventChartConfig = {
            color:ToolService.getTenColors(),
            legend:false
        };
        $scope.$on('flipinfo',function(e,msg){
            $scope.flipPage = msg;
        });
        $scope.showTempLook = false;
        $scope.query = function(condition){
            $scope.showEventWin = false;
            $("#mychart div").hide();
            $("#tip_shape").hide();
            var params = ToolService.getParams($scope);
            if(condition){ //不保存直接应用
                params.eventCondition = condition;
                var tempCondition = JSON.parse(condition);
                $scope.showTempLook = true;
                if($scope.groupId){
                    params.userGroup = $scope.groupId;
                }
                params.session = $scope.time;
                params.startOrEnd = $scope.eventTypeId;
                params.targetEvent = $scope.eventId;
                params.events = $scope.eventIds;
                params.sessionUnit = $scope.timeUnitId;
                UtilService.setItem("path_"+$scope.appid,JSON.stringify(params));
            }
            else{
                var cache = UtilService.getItem("path_"+$scope.appid);
                $scope.define = $scope.isShowCache?JSON.parse(cache):$scope.define;
                params.eventCondition = $scope.define.eventCondition;
                $scope.showTempLook = $scope.isShowCache?true:false;
                if($scope.define.userGroup){
                    params.userGroup = $scope.define.userGroup;
                }
                params.session = $scope.define.session;
                params.startOrEnd = $scope.define.startOrEnd;
                params.targetEvent = $scope.define.targetEvent;
                params.events = $scope.define.events;
                params.sessionUnit = $scope.define.sessionUnit;
            }
            params.eventCondition = encodeURIComponent(params.eventCondition);
            $scope.pathIsLoading = true;
            var areport = "intelligentpath/"+$scope.appid+"/query";
            var listPM = HttpService.getInfo(areport,params);
            listPM.then(function(data){
                $scope.pathList = data;
                $scope.pathIsLoading = false;
                if($scope.pathList && $scope.pathList.value.length == 0){
                    return;
                }
                require.config({
                    paths:{
                        zrender:'./js/common/zrender',
                        'zrender/Group':'./js/common/zrender',
                        'zrender/shape/Rectangle':'./js/common/zrender',
                        'zrender/shape/Polyline':'./js/common/zrender',
                        'zrender/shape/Line':'./js/common/zrender',
                        'zrender/shape/Text':'./js/common/zrender',
                        'zrender/shape/Animal':'./js/common/zrender',
                        'zrender/shape/Image':'./js/common/zrender'
                    }
                });

                require(
                    ['zrender','zrender/Group',
                        'zrender/shape/Rectangle',
                        'zrender/shape/Polyline',
                        'zrender/shape/Line',
                        'zrender/shape/Text',
                        'zrender/shape/Image'],
                    function(zrender,Group,Rectangle,Polyline,Line,Text,Image) {
                        $scope.clickNode = false;
                        zrender.dispose();
                        var zr = zrender.init($('#mychart')[0]);
                        var width = Math.ceil(zr.getWidth());
                        var height = Math.ceil(zr.getHeight());

                        var guid = require('zrender/tool/guid');
                        var myGroup = new Group();

                        //增加节点
                        var gapx = 10,gapy = 150,itemh = 45,itemw = 130;
                        $scope._nodes = [];

                        var _textColor = '#656565',_hoverColor = '#00a9e8',_borderColor = "#ccc";
                        function createNode(pid){
                            var parent,nodes;
                            var textColor = _textColor,hoverColor = _hoverColor,borderColor = _borderColor;
                            var tip_shape = $("#tip_shape")[0];
                            if(pid == 0){
                                parent = null;
                                nodes = $scope.pathList.value.filter(function(item){
                                    return item.level == 1;
                                });
                            }
                            else{
                                parent = $scope.pathList.value.filter(function(item){
                                    return (item.id == pid && $scope.clickNode == item) ||  (!$scope.clickNode &&item.id == pid);
                                })[0];
                                nodes = $scope.pathList.value.filter(function(item){
                                    return item.parent == pid && (item.percent * 100).toFixed(2)!="0.00";
                                });
                                if(nodes.length>0){
                                    nodes = $filter("orderBy")(nodes,["percent"],"desc");
                                    for (var i = 0; i < nodes.length; i++) {
                                        if (nodes[i].name == "其他") {
                                            var otherNode = nodes[i];
                                            nodes.splice(i, 1);
                                            nodes.push(otherNode);
                                            break;
                                        }
                                    }
                                }
                            }
                            $scope._nodes = nodes;
                            if(nodes.length==0){
                                return false;
                            }

                            var xx = 10,yy = 0;
                            if(parent == null){ //首节点
                                xx = Math.ceil(width/2)-Math.ceil(itemw/2)-20;
                                yy = 20;
                                borderColor = hoverColor;
                            }
                            else{
                                yy = gapy*(nodes[0].level-1);
                            }
                            nodes.forEach(function(item,i){
                                var myx = xx*(i+1)+i*(gapx+itemw)+20,myy = parent && parent.level==1?yy+20:yy;
                                var shape = new Rectangle({
                                    id:guid(),
                                    data:item,
                                    style: {
                                        x: myx,
                                        y: myy,
                                        color:pid==0?hoverColor:'#ffffff',
                                        width: itemw,
                                        height: itemh,
                                        radius: 3,
                                        brushType:'both',
                                        strokeColor:borderColor,
                                        lineWidth:1,
                                        text:cutString(item.name,16,'...'),
                                        textFont:'normal 14px Arial',
                                        textColor:pid==0?'#ffffff':textColor,
                                        textPosition:'inside'
                                    },
                                    highlightStyle:{
                                        strokeColor:hoverColor,
                                        lineWidth:1,
                                    },
                                    clickable: true,
                                    onclick : function(params){
                                        if(item.level == 1 || item.shape.style.strokeColor==hoverColor){
                                            getDetail(item);
                                            return false;
                                        }
                                        $scope.clickNode = item;
                                        clearActiveNodes(item);
                                        item.activeNode = true;
                                        removeNode(item.level);
                                        if((item.percent * 100).toFixed(2)!="0.00"){
                                            createNode(item.id);
                                        }
                                        if($scope._nodes.length==0){
                                            getDetail(item);
                                        }

                                        var current = params.target.data;
                                        current.shape.style.strokeColor = hoverColor;
                                        current.line.style.strokeColor = hoverColor;
                                        if(item.y+290 > 550){
                                            if($(".panel").height() > 1500){
                                                $(".panel").height(1500);
                                            }else{
                                                $(".panel").height(item.y+340);
                                            }
                                        }
                                        zr.render();
                                    },
                                    onmouseover:function(e){
                                        tip_shape.innerHTML = e.target.data.name;
                                        tip_shape.style.display = "block";
                                        tip_shape.style.position = "absolute";
                                        tip_shape.style.left = e.target.style.x+'px';
                                        tip_shape.style.top = e.target.style.y-60+'px';
                                    },
                                    onmouseout:function(){
                                        tip_shape.style.display = "none";
                                    }
                                });
                                if(parent!=null){
                                    var px = parent.x,py = parent.y;
                                    var px_1 = px+Math.ceil(itemw/2),py_1 = py+itemh+1,bce = 5;
                                    var px_2 = myx+Math.ceil(itemw/2),py_2 = myy-1;
                                    var line = new Line({
                                          id:guid(),
                                          style: {
                                              xStart: px_1,
                                              yStart: parent.level==1?py_1+40:py_1,
                                              xEnd: px_2,
                                              yEnd: py_2-20,
                                              strokeColor: borderColor,
                                              lineWidth: 1
                                          }
                                      });
                                    item.line = line;
                                    myGroup.addChild(line);
                                    var text = new Text({
                                        zlevel:2,
                                        style: {
                                            text: (item.percent * 100).toFixed(2) +"%",
                                            x: px_2,
                                            y: py_2-10,
                                            textFont: '14px Arial',
                                            color:textColor,
                                            textPosition:'inside',
                                            textAlign:'center',
                                            strokeColor:"#fff"
                                        },
                                        hoverable:false
                                    });
                                    item.text = text;
                                    myGroup.addChild(text);
                                }

                                item.shape = shape;
                                item.x = myx;
                                item.y = myy;
                                item.hidx = i;
                                myGroup.addChild(shape);
                            });
                        }
                        var clearActiveNodes = function(item){
                            angular.forEach($scope.pathList.value,function(node){
                                if(node.level >= item.level){
                                    node.activeNode = false;
                                }
                            });
                        }
                        var getDetail = function(item){
                            $scope.routeList = [];
                            angular.forEach($scope.pathList.value,function(node){
                                if(node.activeNode || node.level == 1){
                                    $scope.routeList.push(node);
                                }
                            });
                            getNodeDetail(item);
                            $scope.routeList = $filter("orderBy")($scope.routeList,["level"]);
                            if($scope._nodes.length > 0){
                                $scope.routeList.push({name:"?"});
                            }
                            if(!$scope.pathList.type){
                               $scope.routeList.reverse();
                            }

                            ToolService.showAlp();
                            $scope.nodeDetail = item;
                        }
                        function removeNode(level){
                            $scope.pathList.value.filter(function(item){
                                if(item.level>level && item.shape){
                                    myGroup.removeChild(item.shape);
                                    myGroup.removeChild(item.line);
                                    myGroup.removeChild(item.text);
                                    // myGroup.removeChild(item.textbg);
                                    item.shape = undefined;
                                }
                                if(item.level == level && item.shape){
                                    item.shape.style.strokeColor = _borderColor;
                                    item.line.style.strokeColor = _borderColor;
                                    item.text.style.color = _textColor;
                                }
                            });
                        }
                        //名称过长省略显示
                        var cutString = function(str,len,suffix){
                            var templen=0;
                            for(var i=0; i < str.length; i++){
                                templen = str.charCodeAt(i) > 255?templen+=2:templen+=1;
                                if(templen == len){
                                    return str.slice(0,i+1)+suffix;
                                }else if(templen > len){
                                    return str.slice(0,i)+suffix;
                                }
                            }
                            return str;
                        }
                        var maxLevel = function(arr){
                            var levelList = [];
                            for(var i = 0; i < arr.length; i+=1){
                               levelList.push(arr[i].level);
                            }
                            return Math.max.apply(null,levelList);
                        }
                        var getClickNodePath = function(item,routeList){
                             if(routeList.length==0 && $scope._nodes.length > 0){
                                routeList.push({name:"?"});
                             }
                             var node = $scope.pathList.value.filter(function(node){
                                return item.parent == node.id;
                             })[0];

                             routeList.push(item);
                             $scope.routeList = routeList;

                             if(item.level>1){
                                getClickNodePath(node,routeList);
                             }

                        }
                        var getSecondLevelId = function(){
                            var secondLevelId = 0;
                            for(var i = 0; i < $scope.pathList.value.length; i++){
                                if($scope.pathList.value[i].level==2){
                                    secondLevelId = $scope.pathList.value[i].parent;
                                    break;
                                }
                            }
                            return secondLevelId;

                        }
                        var getNodeDetail = function(node) {
                            $scope.nodeName = node.name;
                            var tNumber = node.totalNumber==0?1:node.totalNumber;
                                tpercent = (node.totalNumber/tNumber)*100,
                                apercent = (node.number/tNumber)*100,
                                lnumber =  node.totalNumber - node.number,
                                lpercent = (lnumber/tNumber)*100;
                            $scope.lpercent = lpercent.toFixed(2)+"%"
                            ;
                            $scope.nodeDetails = [{title:"总会话数",count:node.totalNumber,percent:tpercent.toFixed(2)+"%"}
                            ,{title:"活跃会话",count:node.number,percent:apercent.toFixed(2)+"%"}
                            ,{title:"流失会话",count:lnumber,percent:lpercent.toFixed(2)+"%"}];
                        }
                        createNode(0);
                        createNode(getSecondLevelId());
                        var image = new Image({
                            style: {
                                image: $scope.pathList.type==false?'/images/top.png':'/images/bottom.png',
                                x: width/2+8-20,
                                y: 75
                            }
                        });
                        zr.addShape(image);
                        zr.addGroup(myGroup);

                });
            },function(data){
                $scope.myChartData = ToolService.noDataChart();
                $scope.infoList = [];
                $scope.eventChartLoading = false;
                $scope.chartListLoading = false;
            });
        }
        $scope.$watch("appid+defineFlag+dimenId+timeFlag+date.startDate+date.endDate+seeFlag+usergroupid",function(e){
            if(angular.isDefined($scope.appid) && (angular.isDefined($scope.defineFlag) || $scope.isShowCache)){
                $scope.query();
            }
        });
        $scope.dimenInit = $scope.dimenId = "-all";
    	$scope.$watch("appid",function(n){
    		if(angular.isDefined(n)){
                $scope.dimenId = "-all";
                $scope.lengedNames = [];
                $scope.defineFlag = undefined;
    			$scope.queryInfoByApp(5);
                $scope.querySelectInfos();
    		}
    	});

    }
})();
