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

    function usergroupCtrl($scope,$rootScope,HttpService,ToolService,UtilService,$state){

        $scope.query = function(){
            var usergroupPM = HttpService.getInfo("mng/usergroup/find/"+$scope.appid);
            ToolService.showLoading();
            usergroupPM.then(function(data){
                ToolService.hideLoading();
                $scope.usergroupList = data;
            });
        }
        $scope.$watch("appid",function(n){
            if(angular.isDefined(n)){
                $scope.query();
            }
        });

        $scope.$on('flipinfo',function(e,msg){
            $scope.flipPage = msg;
        });

        $scope.doRemove = function(id){
            $scope.delstatus = true;
            $scope.delId = id;
        }
        $scope.removeInfo = function(){
            var removePM = HttpService.deleteInfo("mng/usergroup/delete/"+$scope.delId);
            ToolService.showLoading();
            removePM.then(function(data){
                ToolService.hideLoading();
                $scope.delstatus = false;
                ToolService.showTips("删除成功");
                $scope.query();
                $rootScope.operSubmitData("删除");
            });
        }

        $scope.gopage = function(info){
            if(angular.isDefined(info)){
                $state.go("collect.usergroupDetail",{aid:info});
            }else{
                $state.go("collect.usergroupDetail");
            }
        }

        $scope.refreshExport = function(info){
            var upDate = info.dataUpdateTime;
            if(angular.isDefined(upDate)){
                if(Date.isSameDay(new Date(),new Date(upDate))){
                    ToolService.showTips("已经是最新数据");
                    return false;
                }
            }
            var putPM = HttpService.putInfo("mng/usergroup/refresh/"+info.id);
            ToolService.showLoading();
            putPM.then(function(data){
                ToolService.hideLoading();
                $scope.query();
            });
        }
    }

    function usergroupDetailCtrl($scope,$rootScope,HttpService,ToolService,UtilService,$q,$state,$stateParams){
        var editInfo = $stateParams.aid,infoId = null;
        if(editInfo!=null){
            infoId = $scope.id = editInfo.id;
        }

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

        var profilePM = null,eventPM = null;
        $scope.queryEventProfile = function(){
            profilePM = HttpService.getInfo($scope.appid+"/profile/find");
            profilePM.then(function(data){
                $scope.profileList = data;
            });
            eventPM = HttpService.getInfo($scope.appid+"/event/find");
            eventPM.then(function(data){
                $scope.eventList = data;
            });
            if(infoId!=null){
                ToolService.showLoading();
                $q.all([profilePM,eventPM]).then(function(data){
                    var info = editInfo;
                    var profileInfoStr = info.profileInfo,eventInfoStr = info.eventInfo;
                    if(!UtilService.isNullStr(profileInfoStr)){
                        var profileInfo = JSON.parse(profileInfoStr);

                        $scope.profileRel = profileInfo.relation,profiles = profileInfo.profiles;
                        profileInfo.profiles.filter(function(p){
                            $scope.addProfile(p);
                        });
                    }
                    if(!UtilService.isNullStr(eventInfoStr)){
                        var eventInfo = JSON.parse(eventInfoStr),evts = [],evtvals = [];
                        $scope.eventRel = eventInfo.relation;

                        eventInfo.events.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="+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.events.filter(function(e){
                                e.oldparams = UtilService.cloneJSON(e.params);
                                delete e.params;
                                $scope.addEvent(e);
                            });
                        });
                    }
                    ToolService.hideLoading();
                });
            }
        }

        $scope.$watch("appid",function(n){
            if(angular.isDefined(n)){
                if(profilePM!=null){
                    $scope.cancel();
                }
                else{
                    $scope.queryEventProfile();
                }
            }
        });

        $scope.changeRel = function(flag,obj){

            switch (flag) {
                case 1:
                    $scope.profileRel = $scope.profileRel == 'and' ? "or" : 'and';
                    break;
                case 2:
                    $scope.eventRel = $scope.eventRel == 'and' ? "or" : 'and';
                    break;
                case 3:
                    obj.relation = obj.relation == 'and' ? "or" : 'and';
                    break;
                default:
                    break;
            }
        }
        var rmd = new Date().getTime();
        $scope.getProfileNum = function(){
            if(!$scope.profileInfo){return  0;}
            var ps = $scope.profileInfo.filter(function(item){
                return item.show!=false;
            });
            return ps.length;
        }
        $scope.addProfile = function(obj){
            if($scope.getProfileNum()>=5){
                return false;
            }
            rmd ++;
            var temp = {id:"pro_"+rmd};
            if(obj){
                for(var k in obj){
                    temp[k] = obj[k];
                }
            }
            $scope.profileInfo.push(temp);
        }

        $scope.removeProfile = function(pro){
            for(var i=0;i<$scope.profileInfo.length;i++){
                if($scope.profileInfo[i].id == pro.id){
                    $scope.profileInfo[i].show = false;
                    break;
                }
            }
        }
        $scope.$on("profile",function(e,msg){
            for(var i=0;i<$scope.profileInfo.length;i++){
                if($scope.profileInfo[i].id == msg.id){
                    $scope.profileInfo[i] = msg;
                    break;
                }
            }
        });

        $scope.eventinitname = "请选择事件";
        $scope.getEventNum = function(){
            var es = $scope.eventInfo.filter(function(item){
                return item.show!=false;
            });
            return es.length;
        }
        $scope.setEventStyle = function(){
            var idx = -1;
            var len = $scope.eventInfo.length;
            $scope.eventInfo.filter(function(item,i){
                if(item.show!=false){
                    idx ++;
                    item.style = {'z-index':len-i};
                }
            });
        }
        $scope.addEvent = function(obj){
            if($scope.getEventNum()>=5){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.setEventStyle();
        }
        $scope.removeEvent = function(event){
            for(var i=0;i<$scope.eventInfo.length;i++){
                if($scope.eventInfo[i].id == event.id){
                    $scope.eventInfo[i].show = false;
                    break;
                }
            }
            $scope.setEventStyle();
        }

        $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;
                        }
                    }
                }
            }
        });

        var oldname = "";
        $scope.init = function(){
            $scope.profileInfo = [];
            $scope.eventInfo = [];
            $scope.profileRel = "and";
            $scope.eventRel = "and";

            if(infoId!=null){
                $scope.name = oldname = editInfo.name;
                $scope.mark = editInfo.mark;
                $scope.userType = editInfo.userType;
                $scope.mydate = {
                    startDate:editInfo.startDate,
                    endDate:editInfo.endDate
                };

            }
        };

        $scope.init();

        //判断账号是否存在
        $scope.exixtName = function(flag){
            if(angular.isDefined(flag) && flag ==1){
                ToolService.showLoading();
            }
            if($scope.judgeNameChange(oldname,$scope.name)){
                var namePM = HttpService.getInfo("mng/usergroup/valid/"+$scope.appid,{name:$scope.name});
                namePM.then(function(data){
                    $scope.tip = {};
                    if(data==true){//存在
                        $scope.tip = {
                            name:{
                                status:true,
                                txt:"名称已存在"
                            }
                        }
                        ToolService.hideLoading();
                    }else{
                        if(angular.isDefined(flag) && flag ==1){
                            $scope.save();
                        }
                    }
                });
            }
            else{
                if(angular.isDefined(flag) && flag ==1){
                    $scope.save();
                }
            }
        }
        $scope.save = function(){
            var par = {
                name: $scope.name,
                mark: $scope.mark,
                userType: $scope.userType,
                startDate:$scope.mydate.startDate,
                endDate:$scope.mydate.endDate,
                app:$scope.appid
            };

            var pevtInfo = "";
            var profileInfo = {'relation':$scope.profileRel,profiles:[]};

            var hasNull = false;
            $scope.profileInfo.filter(function(item){
                if(item.show!=false){
                    if(UtilService.isNullStr(item.attr)){
                        $scope.$broadcast(item.id, "error");
                        hasNull = true;
                    }
                    var temp = {};
                    for(var k in item){
                        if(k!='id'){
                            if(k!='value'){
                                temp[k] = item[k];
                            }else{
                                temp[k] = item[k].join(",");
                            }
                            if(UtilService.isNullStr(temp[k]) && k!='pid'){
                                $scope.$broadcast(item.id, "error");
                                hasNull = true;
                            }
                        }
                    }
                    profileInfo.profiles.push(temp);
                }
            });
            if(profileInfo.profiles.length>0){
                par.profileInfo = JSON.stringify(profileInfo);
                pevtInfo = "profile";
            }

            var eventInfo = {relation:$scope.eventRel,events:[]};
            $scope.eventInfo.filter(function(item){
                if(item.show!=false){
                    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){
                                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;
                                        }
                                    }
                                }
                                temp.params.push(pms);
                            }
                        });
                    }
                    eventInfo.events.push(temp);
                }
            });
            if(eventInfo.events.length>0){
                par.eventInfo = JSON.stringify(eventInfo);
                pevtInfo = "event";
            }

            var verPar = {
                name: {
                    key: 'spcname',
                    val: par.name
                }
            }

            $scope.tip = formJudge(verPar);
            if(pevtInfo==''){
                $scope.tip.params = {
                    status : true,
                    txt:"至少选择用户属性或者触发事件其中一项"
                }
                $scope.tip.succ = false;
            }
            if(hasNull){
                // ToolService.showTips('选择框、输入框必填');
            }
            if ($scope.tip.succ != true || hasNull) {
                ToolService.hideLoading();
                ToolService.showTips($scope.formTipMsg);
                return false;
            }

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

        $scope.cancel = function(){
            $state.go("collect.usergroup");
        }
    }
})();
