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

    function custommenuCtrl($rootScope,$scope,HttpService,ToolService,UtilService,$timeout,$stateParams,$state,$filter,$location){
        $scope.pageId = $stateParams.pageid;
        $scope.viewFlag = 1; //1看单，2收藏，3行业看单
        if($scope.pageId!=null){
            $scope.viewFlag = 0;
        }
        $scope.menuInit = $scope.pageId;
        var isinit = true;
        if($scope.pageId){
            isinit = false;
        }

        var rmd = new Date().getTime();
        $scope.$on("industryId",function(e,msg){
            if(msg.info.id == 'all'){
                $scope.industryInitName = '';
                $scope.industryInit = 'all';
            }else{
                $scope.industryInitName = msg.info.name;
                $scope.industryInit = msg.info.id;
            }
        });
        $scope.$on("menuId",function(e,msg){
            $scope.menuDetail(msg.info);
        });
        $scope.timeFlag='day';
        $scope.disTimeFlag = ['hour'];
        $scope.changeTimeFlag = function(flag){
            if($scope.disTimeFlag.indexOf(flag)>-1){return false;}

            $scope.timeFlag = flag;
        }
        $scope.changeViewFlag = function(flag){
            if($scope.viewFlag == flag){return false;}

            $rootScope.thirdtab = ['','我的看单','我的收藏','行业看单模板'][flag];

            $scope.viewFlag = flag;
            $scope.lookMyMenu();
        }
        $scope.pageFlag = 0; //1还没有看单，2看单设置完毕，3进入我的看单，4看单详情
        $scope.addReyunMenu = function(){
            var savePM = HttpService.postInfo("custommenu/addReyun/"+$scope.appid);
            ToolService.showLoading();
            savePM.then(function(data){
                ToolService.hideLoading();
                if(data.length>0){
                    $scope.pageFlag = 2;
                    $scope.reyunList = data;
                    $scope.$emit("f5CtmMenus",{});
                }
                else{
                    if(data.code == -6002){
                        ToolService.showTips("请集成sdk并上报数据");
                    }
                    else{
                        ToolService.showTips("操作失败");
                    }
                }
            });

        }

        $scope.date = ToolService.getLastDays(-7,0);
        $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 eventPM = null;
        // $scope.menuInitName = "看单名称";
        //查看我的看单
        $scope.lookMyMenu = function(flag){
            if(flag && flag == 2){ //加入看单后-查看我的看单
                 $scope.viewFlag = 1;
            }
            $scope.closeWin();
            ToolService.showLoading();
            var url = "";
            $scope.searchTxt = "";
            $scope.orderFlag = 0;
            $scope.industryList = [];
            if($scope.industryList.length==0){
                var industryPM =  HttpService.getInfo("custommenu/industry");
                industryPM.then(function(data){
                    data.filter(function(item){
                        var obj = {};
                        obj.id = item.category;
                        obj.name = item.categoryName;
                        $scope.industryList.push(obj);
                    });
                    $scope.industryList.unshift({id:"all",name:"全部行业"});
                    $scope.industryInit = $scope.appInstance.appGenre==43 || $scope.appInstance.appGenre==64?$scope.appInstance.appGenre:'all';
                    $scope.industryInitName = $scope.appInstance.appGenreName==43 || $scope.appInstance.appGenreName==64
                                              ?$scope.appInstance.appGenreName:"全部行业";
                });
            }
            switch ($scope.viewFlag) {
                case 2:
                    url = "custommenu/findFavo/"+$scope.appid;
                    break;
                case 3:
                    url = "custommenu/findShare/"+$scope.appid;
                    break;
                case 1:default:
                    url = "custommenu/findMy/"+$scope.appid;
                    break;
            }
            $scope.menuInfoList = [];
            var menuPM = HttpService.getInfo(url);
            menuPM.then(function(data){
                $scope.menuInfoList = data;
                if($scope.pageId!=null){
                    var ms = $scope.menuInfoList.filter(function(item){
                        return item.id == $scope.pageId;
                    });
                    if(ms.length>0){
                        $scope.menuDetail(ms[0]);
                    }
                    $scope.viewFlag = 1;
                }
                else{
                    //子账户进来
                    // if(!$rootScope.isSuper && data.length>0){
                    //     $scope.menuDetail(data[0]);
                    // }
                }
                if((flag && flag == 1)){
                    $scope.menuDetail(data.slice(-1)[0]);
                }
                ToolService.hideLoading();
            });
            if(eventPM == null){
                $scope.queryInfoByApp();
            }
            $scope.pageFlag = 3;
        }

        $scope.menuDetail = function(menu){
            $scope.pageFlag = 4;
            $scope.currentMenu = menu;
            $scope.changeMatchFlag(0);
            if($scope.viewFlag == 1){
                // $rootScope.custID = menu.id;
                $rootScope.thirdtab = menu.name;

            }
            if($scope.menuInit == menu.id){
                $scope.query();
            }else{
                $scope.menuInit = menu.id;
            }
        }
        $scope.orderFlag = 0;
        $scope.menuOrder = function(flag){
            $scope.orderFlag = flag;
            switch (flag) {
                case 2:
                    $scope.menuInfoList.sort(function(x,y){
                        return x.matchPercent == y.matchPercent ? 0 : (x.matchPercent > y.matchPercent ? -1 : 1);
                    });
                    break;
                case 3:
                    $scope.menuInfoList.sort(function(x,y){
                        return x.useNumber == y.useNumber ? 0 : (x.useNumber > y.useNumber ? -1 : 1);
                    });
                    break;
                case 4:
                    $scope.menuInfoList.sort(function(x,y){
                        return x.favoriteNumber == y.favoriteNumber ? 0 : (x.favoriteNumber > y.favoriteNumber ? -1 : 1);
                    });
                    break;
                case 1:default:
                    $scope.menuInfoList.sort(function(x,y){
                        return x.id == y.id ? 0 : (x.id > y.id ? -1 : 1);
                    });
                    break;
            }
        }
        $scope.backToMenu = function(){
            if($scope.viewFlag == 2 && !$scope.currentMenu.hasFavorite){
                for(var i=0;i<$scope.menuInfoList.length;i++){
                    var item = $scope.menuInfoList[i];
                    if(item.id == $scope.currentMenu.id){
                        $scope.menuInfoList.splice(i,1);
                        break;
                    }
                }
            }
            if($scope.viewFlag==1){
               $location.path("/collect/custommenu");
            }
            $scope.pageFlag = 3;
        }
        $scope.typeInitname = "请选择";
        $scope.$on("typeId",function(e,msg){
            $scope.customTypeId = msg.info.id;
        });
        $scope.customTypeFlag = 0;//1事件，2留存，3漏斗
        $scope.changeCustomFlag = function(flag){
            if($scope.customTypeFlag == flag){return false;}

            $scope.customTypeFlag = flag;
            switch (flag) {
                case 2:
                    $scope.typeList = $scope.retentionList;
                    break;
                case 3:
                    $scope.typeList = $scope.funnelList;
                    break;
                case 1:default:
                    $scope.typeList = $scope.eventstatsList;
                    break;
            }
            if($scope.typeList.length>0){
                var initid = $scope.typeList[0].id;
                if($scope.typeinit == initid){
                    $scope.typef5 = ++rmd;
                }
                else {
                    $scope.typeinit = initid;
                }
            }
            else{
                $scope.customTypeId = $scope.typeinit = -1;
            }
        }
        //查看埋点及规则
        $scope.showDetail = function(temp){
            ToolService.showAlp();
            $scope.detailInfo = JSON.parse(temp.info.descb);
            $scope.custitle = temp.info.name+(temp.info.menuType=='funnel'?"漏斗":temp.info.menuType=='retention'?"留存":"");
            $scope.isdetail = true;
            angular.element(document).on("click",function(){
                $scope.$apply(function(){
                    $scope.hideDetail();
                });
            });
        }
        $scope.hideDetail = function(){
            ToolService.hideAlp();
            $scope.isdetail = false;

        }
        $scope.maxMenu = 10;//最大看单数
        $scope.maxReport = 16;//最大报表数
        $scope.winFlag = 0; //1添加看单，2修改看单，3删除看单 ，4分享看单 5加入我的看单 6添加报表 7删除报表
        var oldename = "";
        $scope.showWin = function(flag,obj){
            if(flag == 1 && $scope.menuInfoList && $scope.menuInfoList.length>=$scope.maxMenu){
                return false;
            }
            if(flag == 6 && $scope.currentMenu && $scope.currentMenu.templates && $scope.currentMenu.templates.length>=$scope.maxReport){
                ToolService.showTips("每个看单最多支持"+$scope.maxReport+"个图表");
                return false;
            }

            var show = true;
            switch (flag) {
                case 1:
                    $scope.ename = oldename = "";
                    break;
                case 2:
                    $scope.ename = oldename = obj.name;
                    $scope.winId = obj.id;
                    break;
                case 4:
                    $scope.shareMenu = obj;
                    if(!obj.templates || obj.templates.length<1){
                        ToolService.showTips("请添加报表后再分享");
                        show = false;
                    }
                    $scope.mname = obj.name;
                    $scope.winId = obj.id;
                    break;
                case 3:case 7:
                    $scope.delname = obj.name;
                    $scope.winId = obj.id;
                    break;
                case 6:
                    // $scope.changeCustomFlag(1);
                    if(obj){
                        $scope.currentMenu = obj;
                        $scope.changeMatchFlag(0);
                    }
                    $scope.changeCustomFlag(1);
                    break;
                default:
                    break;
            }
            if(show){
                ToolService.showAlp();
                $scope.winFlag = flag;
            }
        }
        $scope.closeWin = function(flag){
            ToolService.hideAlp();
            $scope.winFlag = 0;

            if(flag == 1){ //加入看单返回到分享页
                $scope.matchFlag = 0;
            }
        }
        $scope.getMaxTips = function(){
            if($scope.chartDatas && $scope.chartDatas.length>=$scope.maxReport){
                return "每个看单最多支持"+$scope.maxReport+"个图表";
            }
            else{
                return "";
            }
        }
        $scope.doFavorite = function(){
            var favorPM = null,num=0,id = $scope.currentMenu.id;
            if(!UtilService.isNullStr($scope.currentMenu.shareId)){
                id = $scope.currentMenu.shareId;
            }
            if($scope.currentMenu.hasFavorite==false){
                favorPM = HttpService.postInfo("custommenu/addFavorite/"+$scope.appid+"/"+id);
                num = 1;
            }
            else{
                favorPM = HttpService.deleteInfo("custommenu/delFavorite/"+$scope.appid+"/"+id);
                num = -1;
            }
            ToolService.showLoading();
            favorPM.then(function(data){
                ToolService.hideLoading();
                if(data==true){
                    $scope.currentMenu.favoriteNumber += num;
                    $scope.currentMenu.hasFavorite = num > 0 ? true : false;
                    ToolService.showTips("操作成功");
                }
                else{
                    ToolService.showTips("操作失败");
                }
            });
        }
        $scope.doFavoriteByMenu = function(menu){
            var favorPM = HttpService.deleteInfo("custommenu/delFavorite/"+$scope.appid+"/"+menu.shareId);
            ToolService.showLoading();
            favorPM.then(function(data){
                ToolService.hideLoading();
                if(data==true){
                    $scope.menuInfoList.filter(function(item,index){
                        if(item.id == menu.id){
                            $scope.menuInfoList.splice(index,1);
                        }
                    });
                    ToolService.showTips("操作成功");
                }
                else{
                    ToolService.showTips("操作失败");
                }
            });
        }
        $scope.doShare = function(menu){
            if(angular.isUndefined(menu)){
                ToolService.showLoading();
                var sharePM = HttpService.postInfo("custommenu/share/"+$scope.appid+"/"+$scope.winId);
                sharePM.then(function(data){
                    $scope.closeWin();
                    ToolService.hideLoading();
                    if(data==true){
                        ToolService.showTips("分享成功");
                        $scope.shareMenu.hasShare = true;
                    }
                    else{
                        ToolService.showTips("分享失败");
                    }

                });
            }
            else{
                var sharePM = HttpService.deleteInfo("custommenu/cancelShare/"+$scope.appid+"/"+menu.id);
                ToolService.showLoading();
                sharePM.then(function(data){
                    ToolService.hideLoading();
                    if(data==true){
                        ToolService.showTips("取消成功");
                        menu.hasShare = false;
                    }
                    else{
                        ToolService.showTips("取消失败");
                    }
                });
            }

        }
        $scope.saveMenu = function(){
            var verPar = {
                name: {
                    min:1,
                    max:24,
                    key: 'spcname',
                    val: $scope.ename
                }
            };
            $scope.tip = formJudge(verPar);
            if(UtilService.isNullStr($scope.ename) || $scope.tip.succ != true){
                ToolService.showTips("请输入12个汉字以内名称，允许字符为中英文数字_-");
                return false;
            }
            else{
                var savePM = null,txtTips = "添加成功",flag = 1;
                if($scope.winFlag==2){//修改看单
                    if(angular.lowercase(oldename) == angular.lowercase($scope.ename)){
                        $scope.closeWin();
                        return false;
                    }
                    savePM = HttpService.putInfo("custommenu/updateName/"+$scope.appid+"/"+$scope.winId+"?name="+$scope.ename,{});
                    txtTips = "修改成功";
                    flag = 0;
                }else{ //添加看单
                    savePM = HttpService.postInfo("custommenu/saveMenu/"+$scope.appid+"?name="+$scope.ename,{});
                }
                ToolService.showLoading();
                savePM.then(function(data){
                    ToolService.hideLoading();
                    if(data.code == -6001){
                        ToolService.showTips("名称已存在");
                    }
                    else if(data.code == -300){
                        ToolService.showTips("最多支持"+$scope.maxMenu+"个看单");
                    }
                    else{
                        $scope.closeWin();
                        ToolService.showTips(txtTips);
                        $scope.lookMyMenu(flag);
                        $scope.$emit("f5CtmMenus",{});
                        if($scope.winFlag!=2){
                            $rootScope.operSubmitData("新建");
                        }
                    }

                },function(data){
                    ToolService.hideLoading();
                    if(data.code == -6001){
                        ToolService.showTips("名称已存在");
                    }
                    else{
                        ToolService.showTips(data.message);
                    }
                });
            }
        }
        //添加报表
        $scope.addReport = function(){
            if(!$scope.customTypeId || $scope.customTypeId<1){
                ToolService.showTips('请选择模板');
                return false;
            }
            var par = {
                menuType:['eventstats','retention','funnel'][$scope.customTypeFlag-1],
                originalReportId:$scope.customTypeId
            }
            var savePM = HttpService.postInfo("custommenu/addTemp/"+$scope.appid+"/"+$scope.currentMenu.id,par);
            ToolService.showLoading();
            savePM.then(function(data){
                ToolService.hideLoading();
                if(data.code == -6000){
                    ToolService.showTips("本看单中已存在该图表，请重新选择。");
                }
                else if(data.code == -300){
                    ToolService.showTips("每个看单最多支持"+$scope.maxReport+"个图表");
                }
                else{
                    if($scope.viewFlag == 1){
                        $scope.pageFlag = 4;
                        $scope.goToCustom($scope.currentMenu.id);
                    }
                    $scope.closeWin();
                    ToolService.showTips('添加成功');
                    $scope.query(data);
                    $scope.currentMenu.templates.push(data);
                    $rootScope.operSubmitData("看单里面创建表单");
                }

            });
        }
        $scope.getEventTypeCount = function(list){
            var evt = 0,ret = 0,fun = 0;
            list.filter(function(item){
                if(item.menuType == 'eventstats'){
                    evt ++;
                }
                else if(item.menuType == 'retention'){
                    ret ++;
                }
                else if(item.menuType == 'funnel'){
                    fun ++;
                }
            });
            return evt+"个事件细分，"+ret+"个留存，"+fun+"个漏斗";
        }
        $scope.getShareName = function(currentMenu){
            if(currentMenu.accountId == $scope.currentAccountId){
                return "来自我的分享";
            }
            else{
                return "来自“"+currentMenu.accountName+"”的分享";
            }
        }
        $scope.reportDetail = function(template){
            $state.go("collect."+template.menuType,{pageid:template.originalReportId});
        }
        $scope.getTipWidth = function(temp){
            var wid = {};
            if(temp.tooltipChart.length==1){
                wid = {'width':$scope.showCount==3?'300px':'400px'};
            }else if(temp.tooltipChart.length==2){
                wid = {'width':$scope.showCount==3?'120px':'200px'};
            }else{
                wid = {'width':$scope.showCount==3?'70px':'90px'};
            }
            return wid;
        }
        //删除
        $scope.doDelete = function(flag){
            $scope.closeWin();
            ToolService.showLoading();
            var deletePM = null;

            if(flag==3){//删除看单
                deletePM = HttpService.deleteInfo("custommenu/delMenu/"+$scope.appid+"/"+$scope.winId);
            }
            else if(flag==7){//删除报表
                deletePM = HttpService.deleteInfo("custommenu/delTemp/"+$scope.winId);
            }
            if(deletePM!=null){
                deletePM.then(function(){
                    ToolService.showTips("删除成功");
                    ToolService.hideLoading();

                    if(flag == 7){
                        $scope.currentMenu.templates.filter(function(item,index){
                            if(item.id == $scope.winId){
                                $scope.currentMenu.templates.splice(index,1);
                                $scope.chartDatas.splice(index,1);
                            }
                        });
                    }
                    else{
                        $scope.lookMyMenu();
                        $scope.$emit("f5CtmMenus",{});
                        $rootScope.operSubmitData("删除");
                    }
                });
            }
        }

        $scope.matchFlag = 0; //1匹配详情，2加入我的看单
        $scope.changeMatchFlag = function(flag){
            if($scope.showEditEvent){
                $scope.showEditEvent = false;
                return false;
            }
            if(flag == 0){
                $scope.matchFlag = 0;
                return false;
            }
            $scope.matchFlag = flag;

            $scope.currentMenu.templates.filter(function(item){
                var condition = JSON.parse(item.queryCondition),menuType = item.menuType;

                if(menuType=='eventstats'){
                    item.isMatch = condition.eventMatch;
                    item.eventname = $scope.getEventName(condition.event);
                }
                else{
                    item.isMatch = true;
                    var names = [];
                    condition.filter(function(cond){
                        if(!cond.eventMatch){
                            item.isMatch = false;
                        }
                        var n = $scope.getEventName(cond.event);
                        if(n!=''){
                            names.push(n);
                        }
                    });
                    if((names.length>2 &&  !item.isMatch) || names.length == 0){
                        item.eventname = '事件不匹配';
                    }
                    else if(names.length>2 && item.isMatch){
                        item.eventname = '事件全匹配';
                    }
                    else{
                        item.eventname = names.join(",");
                    }
                }
                item.jsonCondition = condition;
            });
        }
        $scope.editTemplateEvent = function(template,idx){
            $scope.currentTemplate = template;
            $scope.tempIndex = idx;

            $scope.showEditEvent = true;

        }
        $scope.canJoin = function(){
            if(!$scope.currentMenu){return false;}
            var can = true;
            var temps = $scope.currentMenu.templates.filter(function(item){
                return item.isMatch == false;
            });
            if(temps.length>0){
                can = false;
            }
            return can;
        }
        //根据event获取name
        $scope.getEventName = function(evt){
            if(!$scope.eventList){return "";}
            var name = evt;
            for(var i=0;i<$scope.eventList.length;i++){
                if(evt == $scope.eventList[i].eventName){
                    name = $scope.eventList[i].eventNameAlias;
                    break;
                }
            }
            return name;
        }
        //加入到我的看单
        $scope.addShareMenu = function(){
            if(!$scope.canJoin()){return false;}
            var par = {name:$scope.currentMenu.name,templates:[],id:$scope.currentMenu.id};
            if($scope.viewFlag == 2){
                par.id = $scope.currentMenu.shareId;
            }
            $scope.currentMenu.templates.filter(function(temp){
                var condition = temp.queryCondition,sevent = [];
                if(temp.menuType == 'funnel'){
                    var condJSON = JSON.parse(condition);
                    condJSON.filter(function(json){
                        sevent.push(json.event);
                    });
                }
                par.templates.push({
                    id:temp.id,
                    menuType:temp.menuType,
                    queryCondition:condition,
                    name:temp.name,
                    events:sevent.join(",")
                });
            });
            var saPM = HttpService.postInfo("custommenu/addMenu/"+$scope.appid,par);
            ToolService.showLoading();
            saPM.then(function(data){
                ToolService.hideLoading();
                if(data.length>0){
                    $scope.$emit("f5CtmMenus",{});
                    $scope.changeMatchFlag(0);
                    $scope.showWin(5);
                }
                else{
                    if(data.code && data.code == -300){
                        ToolService.showTips("您的账号仅支持创建"+$scope.maxMenu+"个看单，如需增加，请联系商务");
                    }
                    else{
                        ToolService.showTips("加入失败");
                    }

                }
            });
        }
        $scope.$on("matchok",function(e,msg){
            $scope.currentMenu.templates[$scope.tempIndex].queryCondition = JSON.stringify(msg.info);
            $scope.currentMenu.templates[$scope.tempIndex].isMatch = true;
            if(msg.names.length>2){
                $scope.currentMenu.templates[$scope.tempIndex].eventname = "事件全匹配";
            }
            else{
                $scope.currentMenu.templates[$scope.tempIndex].eventname = msg.names.join(",");
            }

            $scope.showEditEvent = false;
        });
        $scope.queryInfoByApp = function(){
            $scope.pageFlag = 3;
            //app下所有事件
            eventPM = HttpService.getInfo($scope.appid +"/event/find");
            eventPM.then(function(data){
                $scope.eventList = data;
            });

            $timeout(function(){
                //事件分析模板
                if($scope.showMenu('eventstats')){
                    var url = "mng/eventstats/complicated/findAll/";
                    var eventstatsPM = HttpService.getInfo(url+$scope.appid);
                    eventstatsPM.then(function(data){
                        $scope.eventstatsList = data;
                    });
                }
                else{
                    $scope.eventstatsList = [];
                }

                //留存模板
                if($scope.showMenu('retention')){
                    var retentionPM = HttpService.getInfo("mng/retention/find/"+$scope.appid);
                    retentionPM.then(function(data){
                        $scope.retentionList = data;
                    });
                }
                else{
                    $scope.retentionList = [];
                }

                //漏斗模板
                if($scope.showMenu('funnel')){
                    var funnelPM = HttpService.getInfo("funnel/find/"+$scope.appid);
                    funnelPM.then(function(data){
                        $scope.funnelList = data;
                    });
                }
                else{
                    $scope.funnelList = [];
                }

            },300);
        }
        //根据已选的指标和分组，重新生成图表数据
        $scope.changeChartData = function(tempData){
            tempData.tooltipChart = [];
            var xKey =  tempData.trendList.key,temp = {
                key:xKey,
                val:[],
                name:[],
                rmd : ++rmd
            };
            var zero = [];
            xKey.filter(function(d,index){
                zero.push(0);
            });
            if(tempData.charts.chartType == "pie"){
                tempData.ischeckall = tempData.group_List.length==tempData.grouped_List.length?true:false;
                tempData.charts.chartConfig.flag = false;
                if(tempData.rateListed.length>2){
                    tempData.rateListed = tempData.rateListed.slice(0,2);
                }
                var json = {}, grList = UtilService.cloneJSON(tempData.grouped_List);
                tempData.rateListed.filter(function(rate){
                    var arr = [];
                    var totalval = 0;
                    tempData.grouped_List.filter(function(group){
                         tempData.totalList.filter(function(total){
                             var groupnames = "";
                             var val = {};
                             tempData.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(tempData.totalVal[rate]-totalval>0 && tempData.group_List.length>0){
                        arr.push(tempData.totalVal[rate]-totalval);
                        grList.push("其他");
                    }
                    json[rate] = arr;
                });
                tempData.charts.chartData.key = tempData.rateListed;
                tempData.charts.chartData.name = grList;
                if(!angular.equals({}, json)){
                    tempData.charts.chartData.val = [json];
                }else{
                    tempData.charts.chartData.val = [];
                }
            }else if(tempData.charts.chartType == "table"){
                if(tempData.grouplen>0){
                    tempData.trendList.name = tempData.trendList.name.slice(tempData.grouplen+1);
                    tempData.trendList.columnkey = tempData.trendList.columnkey.slice(tempData.grouplen+1);
                    tempData.trendList.columnkey.unshift("groupnames");
                    tempData.trendList.name.unshift("分组");
                    $scope.mysort(tempData.infoList,tempData.trendList.columnkey[1],true);
                }
                var names = [],keys=[];
                tempData.rateListed.filter(function(rate){
                    names.push($scope.substrName(rate));
                });
                if(names.length>0){
                    names.unshift(tempData.trendList.name[0]);
                    keys = UtilService.cloneJSON(tempData.rateListed);
                    keys.unshift(tempData.trendList.columnkey[0]);
                    tempData.trendList.name = names;
                    tempData.trendList.columnkey = keys;
                }
                tempData.colsStyle = ToolService.getTableColsWidth(tempData.trendList.name,$scope.timeFlag,$scope.showCount);
                tempData.fixrefresh = ++rmd;
            }else{
                if(tempData.charts.chartType == "columnstack"){
                    tempData.charts.chartConfig.flag = tempData.group_List.length>0?'hasGro':'nohasGro';
                    if(tempData.grouped_List.length>5){
                        tempData.grouped_List = tempData.grouped_List.slice(0,5);
                    }
                    if(tempData.rateListed.length>2){
                        tempData.rateListed = tempData.rateListed.slice(0,2);
                    }
                }else{
                    tempData.charts.chartConfig.flag = false;
                    if(tempData.rateListed.length>4){
                        tempData.rateListed = tempData.rateListed.slice(0,4);
                    }
                    var groLen  = tempData.rateListed.length==1?4:2;
                    tempData.grouped_List = tempData.grouped_List.slice(0,groLen);
                }
                tempData.charts.chartConfig.namesub = [];
                tempData.trendList.val.filter(function(item){
                    var date = item.ds,gname = item.groupnames;

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

                            if(dataIdx == -1){
                                temp.name.push(chartname);
                                tempData.charts.chartConfig.namesub.push(format=='percent'?"%":"");
                                dataArr = UtilService.cloneJSON(zero);
                                temp.val.push(dataArr);
                            }
                            else{
                                dataArr = temp.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;
                        });
                    }
                });
                tempData.charts.chartData = temp;
                var klen = tempData.charts.chartData.key.length-1;
                if(tempData.group_List.length>0 && tempData.charts.chartType=='columnstack'){
                    var total = 0;
                    tempData.charts.chartData.val.filter(function(item){
                        total += item[item.length-1];
                    });
                    var obj = {seriesName:$scope.substrName(tempData.rateListed[0]),
                               value:total,
                               name:tempData.charts.chartData.key[klen]};
                    tempData.tooltipChart.push(obj);
                }else{
                    tempData.charts.chartData.name.filter(function(item,index){
                        var vlen = tempData.charts.chartData.val[index].length-1,
                        obj = {seriesName:item,
                                   value:tempData.charts.chartData.val[index][vlen],
                                   name:tempData.charts.chartData.key[klen],
                                   color:tempData.charts.chartConfig.color[index]};
                        tempData.tooltipChart.push(obj);
                    });
                }
            }
            if(tempData.group_List.length>0 && tempData.charts.chartType!='table'){
                tempData.selectName = tempData.grouped_List.length+"个分组";
            }
            if(tempData.group_List.length==0 || tempData.charts.chartType=='table'){
                tempData.selectName = tempData.rateListed.length+"个指标";
            }
        }

        $scope.$on("conentresize",function(){
            if($scope.chartDatas && $scope.chartDatas.length>0){
                $scope.chartDatas.filter(function(tempData){
                    if(tempData.trendList){
                        tempData.colsStyle = ToolService.getTableColsWidth(tempData.trendList.name,$scope.timeFlag,$scope.showCount);
                        tempData.fixrefresh = ++rmd;
                    }
                });
            }
        });
        $scope.orderCol = function(tempData,predicate, reverse) {
            tempData.sortCol = predicate;
            $scope.mysort(tempData.infoList, predicate, reverse);
            tempData.fixrefresh = ++rmd;
        };
        $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.changeRate = function(tempData,rate){
            if(!$scope.canAdd(tempData,1,rate)){return false;}

            var idx = tempData.rateListed.indexOf(rate);
            if(idx>-1){
                tempData.rateListed.splice(idx,1);
            }
            else{
                tempData.rateListed.push(rate);
            }
            $scope.changeChartData(tempData);
        }
        //图表加显示分组
        $scope.changeGroup = function(tempData,group){
            if(!$scope.canAdd(tempData,2,group)){return false;}

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

            }
            return true;
        }
        $scope.substrName = function(name){
            return name.substring(1);
        }
        var changeChart = function(tempData){
            $scope.changeChartData(tempData);
            (function(tempData){
                $scope.$on(tempData.charts.chartTypeId,function(e,msg){
                   if(msg.info.id != tempData.charts.chartType && $scope.viewFlag==1){
                       var changePM = HttpService.putInfo("custommenu/updateType/"+tempData.info.id+"?type="+msg.info.id,{});
                       ToolService.showLoading();
                       changePM.then(function(data){
                           ToolService.hideLoading();
                       },function(data){
                           ToolService.hideLoading();
                           ToolService.showTips(data.message);
                       });
                   }
                   tempData.charts.chartType = msg.info.id;
                   $scope.changeChartData(tempData);
                });
            })(tempData);
        }
        $scope.gotoDetail = function(temp){
            if($scope.viewFlag!=1)return;
            $state.go("collect."+temp.menuType,{pageid:temp.originalReportId});
        }

         $scope.percentPre = "rate_";//显示比例时的前缀
        //onetemp 是为了添加成功后动态查询当前报表
        $scope.query = function(onetemp){
            if(!isinit){
                isinit = !isinit;
                return false
            }
            var templates = [];
            if(onetemp){
                if(angular.isUndefined($scope.chartDatas)){
                    $scope.chartDatas = [];
                }
                templates = [onetemp];
            }
            else{
                $scope.chartDatas = [];
                templates = $scope.currentMenu.templates;
            }
            var myChartDatas = [];
            var setLineData = function(data,tempData,type){
                if(data.val && data.val.length>0){
                    var lineData = data.val[0];
                    if(type == 'funnel')
                    {
                        tempData.charts.chartData = ToolService.getFunnelData(lineData,data.key,data.eventname);
                    }
                    else if(type == 'retention')
                    {
                        tempData.charts.chartData.key = data.key.slice(1);
                        var columns = data.columnkey,line = [];
                        tempData.charts.chartData.name.push(lineData[columns[0]]);

                        for(var i=2;i<columns.length;i++){
                            line.push(lineData['rate_'+columns[i]]);
                        }
                        tempData.charts.chartData.val.push(line);
                    }
                    // else if(type == 'eventstats')
                    // {
                    //     lineData = data.val;
                    //     tempData.charts.chartData.key = data.key;
                    //     tempData.charts.chartData.name = data.name.slice(1);
                    //     var columns = data.columnkey,line = [];

                    //     lineData.filter(function(item){
                    //         line.unshift(item[columns[1]]);
                    //     });

                    //     tempData.charts.chartData.val = [line];
                    // }
                    else if(type == 'eventstats')
                    {

                        var format = data.format,formatjson = {};
                        if(format){
                            format.filter(function(f){
                                formatjson[f.field] = f.format;
                            });
                        }

                        data.format = formatjson;
                        tempData.trendList = data;
                        tempData.totalList = data.totalval;
                        tempData.infoList = data.val;
                        tempData.eventChartLoading = false;

                        tempData.rateList = data.selectfield;
                        tempData.totalVal = {};
                        tempData.rateList.filter(function(rate){
                            tempData.totalList.filter(function(total){
                                if(!tempData.totalVal[rate]){
                                    tempData.totalVal[rate] = 0;
                                }
                                tempData.totalVal[rate] += total[rate];
                            });
                        });
                        tempData.group_List = $scope.getGroupNames(tempData,data.groupfield);
                        tempData.grouplen = data.groupfield.length;
                        $scope.getChartTypeList(tempData);
                        if(tempData.infoList.length>0){
                            $scope.limit(tempData);
                            if(tempData.group_List.length == 0){ //没有分组情况，不显示占比
                                tempData.ispercent = false;
                            }
                            changeChart(tempData);
                            if(tempData.group_List.length>0){
                                tempData.dsList = [];
                                tempData.trendList.key.filter(function(ds,index){
                                    var dsObj = {id:index,name:ds,dsflag:'ds'};
                                    tempData.dsList.unshift(dsObj);
                                });
                                tempData.dsInit = tempData.dsList[0].id;
                                (function(tempData){
                                    $scope.$on(tempData.dsId,function(e,msg){
                                        tempData.ds = msg.info.name;
                                        tempData.fixrefresh = ++rmd;
                                    });
                                })(tempData);
                            }
                            tempData.fixrefresh = ++rmd;
                            tempData.initrefresh = ++rmd;
                        }
                    }
                }
                tempData.charts.chartLoading = false;
            }

            templates.filter(function(item,idx){
                if(item.toShow!=false){
                    var tempData = {info:item};
                    tempData.charts = {
                        chartConfig:{color:ToolService.getTenColors(),legend:false,issmart:true,namesub:[],id:item.menuType=='eventstats'?++rmd:""},
                        chartLoading:true,
                        chartData: ToolService.noDataChart(),
                        rmd : ++rmd,
                        chartTypeId: $scope.timeFlag+'_'+(++rmd),
                        dsId : 'ds_'+(++rmd)
                    };
                    if(onetemp){
                        $scope.chartDatas.push(tempData);
                    }
                    else{
                        myChartDatas.push(tempData);
                    }

                    (function(item,idx,tempData){
                        $timeout(function(){
                            var type = item.menuType;
                            tempData.charts.chartType = (type=='funnel' ? 'funnel' : 'line');
                            //收藏和行业模板
                            if(angular.isDefined(item.queryData)){
                                setLineData(JSON.parse(item.queryData),tempData,type);
                            }
                            else{
                                var chartPM = HttpService.getInfo("custommenu/report/"+$scope.appid+"/"+item.originalReportId,{startDate:$scope.date.startDate,endDate:$scope.date.endDate,menuType:type,viewFlag:$scope.timeFlag});
                                chartPM.then(function(data){
                                    setLineData(data,tempData,type);
                                },function(data){
                                    tempData.charts.chartLoading = false;
                                });
                            }
                        },idx*200*(Math.ceil(idx+1)/4));
                    })(item,idx,tempData);
                }
            });
            if(!onetemp){
                $scope.chartDatas = myChartDatas;
            }
        }
        $rootScope.$on("tooltipObj",function(e,msg){
            $timeout(function() {
               if($scope.chartDatas && $scope.chartDatas.length>0){
                     $scope.chartDatas.filter(function(temp){
                          if(msg.id == temp.charts.chartConfig.id && temp.info.menuType=='eventstats'){
                              temp.tooltipChart = [];
                              if(temp.group_List.length>0 && temp.charts.chartType=='columnstack'){
                                   var total = 0;
                                   msg.objs.filter(function(item){
                                       total += item.value;
                                   });
                                   var obj = {seriesName:$scope.substrName(temp.rateListed[0]),value:total,name:msg.objs[0].name}
                                   temp.tooltipChart.push(obj);
                              }else{
                                   temp.tooltipChart = msg.objs;
                              }
                          }
                     });
               }
           }, 100);
        })
        $scope.getFormatNumber = function(num){
            if(num >= 100000000){
                return UtilService.decimal2(num/100000000) + '亿';
            }
            else if(num >= 10000000){
                return UtilService.decimal2(num/10000000) + '千万';
            }
            else if(num >= 1000000){
                return UtilService.decimal2(num/1000000) + '百万';
            }
            else if(num >= 10000){
                return UtilService.decimal2(num/10000) + '万';
            }
            else{
                return num;
            }
        }
        $scope.changeCount = function(){
            if(!$scope.showCount || $scope.showCount==2){
                $scope.showCount = 3;
                $scope.chartDatas.filter(function(temp){
                    if(temp.info.menuType=='eventstats' && temp.rateListed){
                        var rateLen = temp.rateListed.length==0?1:temp.rateListed.length,
                            groLen = temp.grouped_List.length==0?1:temp.grouped_List.length
                        if(temp.charts.chartType == 'line' && rateLen*groLen>3){
                            temp.rateListed = temp.rateList.slice(0,1);
                            temp.grouped_List = temp.group_List.slice(0, 3);
                            if(temp.grouped_List.length < 2){
                                temp.rateListed = temp.rateList.slice(0,3);
                            }
                            $scope.changeChartData(temp);
                        }
                    }
                });
            }else{
                $scope.showCount = 2;
            }
            $scope.$broadcast("conentresize",true);
            $scope.chartDatas.filter(function(temp){
                temp.fixrefresh = ++rmd;
            });
        }
        $scope.checkAll = function(temp){
            temp.ischeckall = !temp.ischeckall;
            temp.grouped_List = temp.ischeckall?UtilService.cloneJSON(temp.group_List):[];
            $scope.changeChartData(temp);
        }
        $scope.chartAllList = [{id:"line",name:"折线图",platform:"line"},
                              {id:"columnstack",name:"柱状图",platform:"columnstack"},
                              {id:"table",name:"表格",platform:"table"},
                              {id:"pie",name:"饼状图",platform:"pie"}];
        $scope.getChartTypeList = function(tempData){
            if(tempData.rateList.length >= 1 && tempData.grouplen == 0){
                tempData.chartList = $scope.chartAllList.slice(0,3);;
                tempData.charts.chartType  =  "line";
                tempData.charts.chartTypeInit = "line";
            }
            else if(tempData.rateList.length == 1 && tempData.grouplen > 0){
                tempData.chartList = $scope.chartAllList.slice(0);
            }
            else if(tempData.rateList.length >1 && tempData.grouplen > 0){
                tempData.chartList = $scope.chartAllList.slice(2,-1);
                tempData.charts.chartType  =  "table";
                tempData.charts.chartTypeInit = "table";
            }
            tempData.charts.chartType = tempData.info.type?tempData.info.type:tempData.charts.chartType;
            tempData.charts.chartTypeInit = tempData.charts.chartType;
        }
        $scope.limit = function(tempData){
            if(tempData.charts.chartType == 'line'){
                tempData.rateListed = tempData.rateList.slice(0,1);
                tempData.grouped_List = tempData.group_List.slice(0, 3);
                if(tempData.grouped_List.length < 2){
                    tempData.rateListed = tempData.rateList.slice(0,3);
                }
            }else if(tempData.charts.chartType == 'columnstack'){
                tempData.rateListed = tempData.rateList.slice(0,2);
                tempData.grouped_List = tempData.group_List.slice(0, 3);
            }else if(tempData.charts.chartType == 'pie'){
                tempData.rateListed = tempData.rateList.slice(0,1);
                tempData.grouped_List = tempData.group_List.slice(0);
            }else{
                tempData.rateListed = tempData.rateList.slice(0);
                tempData.grouped_List = tempData.group_List.slice(0);
            }
        }
        //得到图的分组，同时处理成分页需要的数据格式
        $scope.getGroupNames = function(tempData,gns){
            var names = [],listArr = [];
            if(gns.length == 0){ //没有分组情况下的处理
                var hasgroup = tempData.trendList.groupfield.length>0;
                tempData.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{
                tempData.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 = tempData.trendList.val.slice(index,index+item.rowNum);
                        listArr.push(listChild);
                    }

                });
            }
            $scope.detailAllList = listArr;
            if($scope.istranfer){
                $scope.transformList();
            }
            else{
                $scope.lsChange++;
            }
            return names;
        }
        $scope.$on("dragorder",function(event,msg){
            ToolService.showLoading();
            var url = "";
            if(msg.flag == 'menu'){
                url = "custommenu/updateIndex/"+$scope.appid+"/"+msg.id+"?index="+msg.index;
            }
            else{
                url = "custommenu/updateIndex/"+msg.id+"?index="+msg.index;
            }

            var updatePM = HttpService.putInfo(url,{});
            updatePM.then(function(){
                if(msg.flag == 'menu'){
                    $scope.lookMyMenu();
                }
                else{
                    $scope.query();
                }
            },function(){
                ToolService.hideLoading();
            });

        });

        $scope.$watch("appid",function(n){
            if(angular.isDefined($scope.appid)){
                eventPM = null;
                // 查询该用户是否有看单（我的看单和收藏）
                var hasPM = HttpService.getInfo("custommenu/find/"+$scope.appid);
                ToolService.showLoading();
                hasPM.then(function(data){
                    ToolService.hideLoading();
                    if(data==true){
                        $scope.lookMyMenu();
                    }
                    else{
                        $scope.pageFlag = 1;
                    }
                });
            }
        });

        $scope.$watch("date.startDate+date.endDate+timeFlag",function(){
            if(angular.isDefined($scope.date) && $scope.pageFlag == 4){
                $scope.query();
            }
        });
    }
})();
