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

    function funnelCtrl($scope,$rootScope,HttpService,ToolService,$state,$stateParams,UtilService,$q){
        var fid = $stateParams.pageid;
        $scope.addFirst = false;
        $scope.addFirstFunnel = function(){
            $scope.addFirst = true;
            $scope.showEventWin = true;
            $scope.currentFunnel = {};
            $scope.isEditInfo = 2;
            $scope.initFunnel();
        }
        var rmd = new Date().getTime();
        var eventPM = null;
        $scope.queryInfoByApp = function(flag,id){
            if(angular.isUndefined(flag) || flag == 5){
                //app下所有事件
                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';
                    });
                });
                //通用属性
                var profilePM = HttpService.getInfo($scope.appid+"/event/find/allAttr");
                profilePM.then(function(data){
                    data.unshift({"dimensionType":"whole",id:"-all",name:"总体",type:"string"});

                    for(var i=0; i< data.length; i++){
                        if(data[i].dimensionType == 'population' || data[i].dimensionType == 'source'){
                            data[i].dimensionType = 'eventlist';
                        }
                    }
                    $scope.dimensionList = data;
                });
            }

            var funPM = HttpService.getInfo("funnel/find/"+$scope.appid);
            funPM.then(function(data){
                $scope.funnelList = data;
                $scope.isEditInfo = 1;
                if(data.length>0){
                    if(!UtilService.isNullStr(fid)){
                        id = fid;
                    }
                    if(!UtilService.isNullStr(id)){
                        var has = false;
                        for(var i=0;i<$scope.funnelList.length;i++){
                            if($scope.funnelList[i].id == id){
                                $scope.funnelInfo = $scope.funnelList[i];
                                has = true;
                                break;
                            }
                        }
                        if(has){//修改
                            if(!UtilService.isNullStr(fid)){
                                $scope.clickFunnel($scope.funnelInfo);
                                fid = null;
                            }
                            else{
                                $scope.defineFlag = ++rmd;
                            }
                        }
                        else if(!has && $scope.funnelInfo.id == id){ //删除当前
                            $scope.clickFunnel(data[0]);
                        }

                    }
                    else{
                        $scope.clickFunnel(data[0]);
                    }
                }
                else{
                    $scope.addFirst = false;
                    $scope.funnelInfo = {};
                }
                if(flag == 5){
                    $scope.dimenRmd = ++rmd;
                }
            });
        }

        //选择按设备或者按用户
        /*$scope.deviceList = ToolService.getDeviceTypeList();
        $scope.deviceInit = $scope.deviceList[0].id;
        $scope.$on("deviceId",function(e,msg){
            $scope.seeFlag = msg.info.id;
        });*/
        $scope.deviceId = false;

        $scope.dimensionname = "维度对比";
        $scope.usergroupid = -1;
        $scope.$on("dimensionId",function(e,msg){
            $scope.dimenId = msg.info.id;
            $scope.dimenObj = msg.info;
            $scope.dimenEventType = msg.info.eventType;

            if($scope.dimenId == 'usergroup' && $scope.usergroupid == -1){
                $scope.lengedNames = ["整体"];
                $scope.dimenugkeys = UtilService.cloneJSON(msg.info.key);
                $scope.dimenugkeys.unshift("all");

                msg.info.value.filter(function(item){
                    $scope.lengedNames.push(item);
                });

                $scope.usergroupid = msg.info.key[0];
            }
            else{
                $scope.usergroupid = -1;
            }
        });

        $scope.date = ToolService.getLastDays(-7,0);
        $scope.$on("dateCustos",function(e,msg){
            $scope.date = msg;
        });
        $scope.$watch("date",function(){
            if(angular.isDefined($scope.date)){
                $scope.datestr = $scope.date.startDate + "至" + $scope.date.endDate;
            }
        });

        //已保存的事件
        $scope.definename = "请选择漏斗";
        $scope.clickFunnel = function(m){
            $scope.funnelInfo = m;
            $scope.ename = m.name;
            $scope.defineFlag = ++rmd;
            $scope.showEventWin = false;
            $scope.isEditInfo = 1;
            $rootScope.thirdtab = m.name;
        }
        $scope.deleteFunnel = function(d){
            $scope.delDefine = d;
            ToolService.showAlp();
            ToolService.showLoading();
            var validPM = HttpService.getInfo("custommenu/delete/valid/"+d.id+"?type=funnel");
            validPM.then(function(data){
                ToolService.hideLoading();
                $scope.wantDelete = true;
                $scope.custommenus = angular.isArray(data) && data.length>0?data:false;
            });
        }
        $scope.doDelete = function(){
            $scope.closeWin();
            ToolService.showLoading();
            var deletePM = HttpService.deleteInfo("mng/funnel/delete/"+$scope.delDefine.id);
            deletePM.then(function(){
                ToolService.showTips("删除成功");
                $scope.queryInfoByApp(3,$scope.delDefine.id);
                ToolService.hideLoading();
                $rootScope.operSubmitData("删除");
            });
        }
        $scope.closeAddWin = function(){
            $scope.showEventWin = false;
            $scope.isEditInfo = 1;
            $scope.addFirst = false;
        }

        $scope.eventinitname = "请选择事件";
        $scope.getEventNum = function(){
            if(!$scope.eventInfo){return 20;}

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

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

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

            if(obj){
                for(var k in obj){
                    temp[k] = obj[k];
                }
                temp.eventinit = obj.event;
            }
            (function(temp){
                $scope.$on(temp.eventid,function(e,msg){
                    temp.params = [];
                    temp.event = msg.info.eventName;
                    temp.nullevent = false;
                    var setparams = function(){
                        temp.paramsList = msg.info.profiles;
                        if(temp.oldparams){
                            temp.oldparams.filter(function(item){
                                $scope.addEventParams(temp,item);
                            });
                            delete temp.oldparams;
                        }
                    }
                    if(angular.isArray(msg.info.profiles)){
                        setparams(msg.info.profiles);
                    }
                    else{
                        var proPM = HttpService.getInfo($scope.appid+"/event/find/param?names="+temp.event);
                        proPM.then(function(data){
                            msg.info.profiles = data[0].profiles;
                            setparams();
                        });
                    }
                });
            })(temp);

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

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

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

        $scope.dayList = [
            {id:1,name:"1天"},
            {id:2,name:"2天"},
            {id:3,name:"3天"},
            {id:4,name:"4天"},
            {id:5,name:"5天"},
            {id:6,name:"6天"},
            {id:7,name:"7天"}
        ];

        $scope.windowsinit = $scope.dayList[0].id;
        $scope.$on("windows",function(e,msg){
            $scope.windows = msg.info.id;
        });
        $scope.eventInfo = [];
        $scope.initFunnel = function(flag){
            $scope.eventInfo.filter(function(item){
                item.show = false;
            });
            if(flag){
                $scope.ename = $scope.funnelInfo.name;
                $scope.windowsinit = $scope.funnelInfo.window;

                ToolService.showLoading();
                $q.all([eventPM]).then(function(data){
                    var eventInfo = JSON.parse($scope.funnelInfo.eventInfo),evts = [],evtvals = [];
                    eventInfo.filter(function(item){
                        var temp = {event:item.event,param:[]};
                        var pppm = UtilService.cloneJSON(item.params);
                        pppm.filter(function(pm){
                            temp.param.push(pm.attr);
                        });
                        evts.push(item.event);
                        evtvals.push(temp);
                    });
                    var evtprofilePM = HttpService.getInfo($scope.appid+"/event/find/param?names="+evts.join(",")+"&params="+encodeURIComponent(JSON.stringify(evtvals)));
                    evtprofilePM.then(function(pros){
                        pros.filter(function(evt){
                            for(var i=0;i<$scope.eventList.length;i++){
                                if(evt.eventName == $scope.eventList[i].eventName){
                                    $scope.eventList[i].profiles = evt.profiles;
                                    break;
                                }
                            }
                        });

                        eventInfo.filter(function(e){
                            if(JSON.stringify($scope.eventList).indexOf(e.event) > -1){
                                 e.oldparams = UtilService.cloneJSON(e.params);
                            }
                            delete e.params;
                            $scope.addEvent(e);
                        });
                        ToolService.hideLoading();
                    });
                });
            }
            else{
                $scope.addEvent();
                $scope.addEvent();
            }
        };

        $scope.isEditInfo = 1;
        $scope.addFunnel = function(flag){
            if(flag){ //修改
                if(!$scope.funnelInfo || !$scope.funnelInfo.id || $scope.isEditInfo==2){return false;}
                $scope.isEditInfo = 3;
                $scope.currentFunnel = $scope.funnelInfo;
            }else{
                $scope.isEditInfo = 2;
                $scope.currentFunnel = {};
            }
            $scope.initFunnel(flag);
            $scope.showEventWin = true;
        }
        $scope.initCondition = function(){
            if($scope.canSave()){
                $scope.initFunnel();
            }
        }

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

            $scope.eventInfo.filter(function(item){
                if(item.show!=false && JSON.stringify($scope.eventList).indexOf(item.event) < 0){
                    item.nullevent = true;
                    hasNull = true;
                }
                if(item.show!=false && JSON.stringify($scope.eventList).indexOf(item.event) > -1){
                    var temp = {event:item.event,relation:item.relation,params:[]};
                    if(UtilService.isNullStr(item.event)){
                        item.nullevent = true;
                        hasNull = true;
                    }
                    else{
                        item.nullevent = false;
                        item.params.filter(function(pm){
                            if(pm.show!=false){
                                var pms = {};
                                for(var k in pm){
                                    if(k!='id' && k!='pid'){
                                        if(k!='value'){
                                            pms[k] = pm[k];
                                        }else{
                                            pms[k] = pm[k].join(",");
                                        }
                                        if(UtilService.isNullStr(pm[k])){
                                            $scope.$broadcast(pm.id, "null");
                                            hasNull = true;
                                        }
                                    }
                                }
                                temp.params.push(pms);
                            }
                        });
                    }
                    eventInfo.push(temp);
                    myEvents.push(item.event);
                }
            });

            if(!hasNull && eventInfo.length>0){
                return {
                    eventInfo:JSON.stringify(eventInfo),
                    events : myEvents.join(",")
                }
            }
            else{
                return {};
            }
        }

        $scope.nameWin = function(flag){
            var nowEvents = $scope.getFunnelEventInfo();
            if(!nowEvents.events){
                ToolService.showTips($scope.formTipMsg);
                return false;
            }

            ToolService.showAlp();
            $scope.wantSave = true;

            $scope.ename = "";
            if(flag){
                $scope.currentFunnel = {id:0};
            }
        }
        $scope.closeWin = function(flag){
            $scope.wantSave = false;
            $scope.wantDelete = false;
            if(flag){
                if(flag == 2 && $scope.isEditInfo == 3){
                    $scope.currentFunnel = $scope.funnelInfo;
                }
                else{
                    $scope.showEventWin = false;
                }
            }
            ToolService.hideAlp();
        }
        $scope.canSave = function(){
            if(!$scope.eventInfo || $scope.eventInfo.length == 0){return false;}

            var can = false;
            for(var i=0;i<$scope.eventInfo.length;i++){
                var temp = $scope.eventInfo[i];
                if(temp.show != false && temp.event){
                    can = true;
                    break;
                }
            }
            return can;
        }
        $scope.save = function(){
            var doSave = function(){
                var par = {
                    name: $scope.ename,
                    app:$scope.appid,
                    window:$scope.windows
                };

                var nowEvents = $scope.getFunnelEventInfo();
                if(nowEvents.events){
                    par.eventInfo = nowEvents.eventInfo;
                    par.events = nowEvents.events;
                }
                else{
                    ToolService.showTips($scope.formTipMsg);
                    return false;
                }

                var savePM = null,txtTips = "添加成功";
                if($scope.currentFunnel.id){
                    par.id = $scope.currentFunnel.id;
                    savePM = HttpService.putInfo("mng/funnel/update",par);
                    txtTips = "修改成功";
                }else{
                    savePM = HttpService.postInfo("mng/funnel/create",par);
                }
                ToolService.showLoading();
                savePM.then(function(data){
                    $scope.closeWin(1);
                    ToolService.hideLoading();
                    ToolService.showTips(txtTips);
                    $scope.queryInfoByApp(1,$scope.currentFunnel.id)
                    if(!$scope.currentFunnel.id){
                        $rootScope.operSubmitData("新建");
                    }
                });
            }

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

        $scope.dimenInit = $scope.dimenId = "-all";
        $scope.$watch("appid",function(n){
            if(angular.isDefined(n)){
                $scope.dimenId = "-all";
                $scope.lengedNames = [];
                $scope.funnelInfo = {};
                $scope.queryInfoByApp(5);
            }
        });

        $scope.chartKey = [];
        $scope.chartConfig = {color:['#5fb5f1','#e6e6e6'],legend:false,ispercent:true};
        $scope.queryList = function(){
            var params = {
                startdate:$scope.date.startDate,
                enddate:$scope.date.endDate,
                appid:$scope.appid
            };
            params.datatype = "list";
            params.eventType = $scope.dimenEventType;
            if($scope.dimenId && $scope.dimenId!='-all'){
                params.dimention = $scope.dimenId;
                if(params.dimention == 'usergroup'){
                    if($scope.usergroupid==-1){return false;}
                    params.usergroupid = $scope.usergroupid;
                }
            }
            params.isdevice = $scope.seeFlag == 'device';
            $scope.chartConfig.isdevice = params.isdevice;
            //列表
            var areport = "funnel/report/"+$scope.funnelInfo.id;
            var listPM = HttpService.getInfo(areport,params);
            $scope.listInfoLoading = true;

            $scope.chartLoading = true;

            $scope.currentChartName = "";
            listPM.then(function(data){
                $scope.listInfoData = data;
                $scope.listInfoLoading = false;

                $scope.chartListInfo = data.val;
                if(params.dimention){
                    $scope.listInfoData.name[0] = $scope.dimenObj.name;

                    if(params.dimention!='usergroup'){
                        $scope.lengedNames = [];
                        var col1 = data.columnkey[0];
                        $scope.chartListInfo.filter(function(item){
                            $scope.lengedNames.push(item[col1]);
                        });
                    }
                }
                $scope.chartKey = $scope.listInfoData.key;
                $scope.chartKeyName = $scope.listInfoData.eventname;

                if(params.dimention=='usergroup'){
                    $scope.setFunnelData(1);
                }
                else{
                    $scope.setFunnelData(0);
                }

                $scope.listInfoDataCondition = ToolService.getChartConditions("漏斗转化-"+$scope.funnelInfo.name,areport,params,"funnel",$scope.funnelInfo.id);
            },function(data){
                // $scope.errorBack(data.message);
                $scope.chartData = ToolService.noDataChart();
                $scope.listInfoData = {};
                $scope.listInfoLoading = false;
                $scope.chartLoading = false;
            });
        }

        $scope.currentChartName = "";
        $scope.setFunnelData = function(idx,flag){
            if(flag && flag == 1){
                idx = $scope.lengedNames.indexOf(idx);
            }
            var fdata = $scope.chartListInfo[idx];
            //用户分群页面点击
            if($scope.dimenId == 'usergroup' && flag && flag == 1){
                if(idx > 0 && $scope.dimenugkeys.indexOf($scope.usergroupid) != idx){
                    $scope.usergroupid = $scope.dimenugkeys[idx];
                    return false;
                }
                if(idx>0){
                    fdata = $scope.chartListInfo[1];
                }
            }

            if($scope.lengedNames && $scope.lengedNames.length>0){
                if($scope.currentChartName == $scope.lengedNames[idx]){
                     return false;
                }
                else{
                    $scope.currentChartName = $scope.lengedNames[idx]
                }
            }
            else{
                $scope.currentChartName = "整体";
            }
            $scope.chartLoading = false;
            $scope.chartData = ToolService.getFunnelData(fdata,$scope.chartKey,$scope.chartKeyName);
        }
        $scope.getChartStyle = function(n){
            var idx = $scope.lengedNames.indexOf(n);
            if( ($scope.dimenId!='usergroup' && $scope.currentChartName == $scope.lengedNames[idx]) || ($scope.dimenId=='usergroup' && (($scope.currentChartName != "整体" && $scope.dimenugkeys.indexOf($scope.usergroupid) == idx) || ($scope.currentChartName == "整体" && idx == 0)))){
                return {"background-color":$scope.chartConfig.color[0],"border-color":"transparent"};
            }
            else{
                return {};
            }
        }

        $scope.$watch("date.startDate+date.endDate+defineFlag+seeFlag+dimenId+usergroupid",function(n){
            if(angular.isUndefined($scope.appid) || angular.isUndefined($scope.date) || angular.isUndefined($scope.funnelInfo) || !$scope.funnelInfo.id){return false;}

            $scope.queryList();
        });
    }
})();
