(function(){
	angular.module("app")
	.controller("indexCtrl",["$rootScope","$scope","HttpService","ToolService","UtilService","$state","$location","DateService","$timeout",indexCtrl]);


	function indexCtrl($rootScope,$scope,HttpService,ToolService,UtilService,$state,$location,DateService,$timeout){

        $rootScope.unfoldFlag = $rootScope.unfoldFlag==undefined?false:$rootScope.unfoldFlag;
        $scope.queryLimit = function(appid){
            if(angular.isDefined(appid)){
                limitPM = HttpService.getInfo("login/limit/"+appid);
            }
            else{
                limitPM = HttpService.getInfo("login/limit");
            }

            limitPM.then(function(data){
                $rootScope.limitInfo = data;
                UtilService.setItem("limitInfo",JSON.stringify($rootScope.limitInfo));
            });
        }

        $rootScope.demoU = ToolService.isDemoUser();
        $scope.goLogin = function(){
            window.location.href = "/login.html";
        }

				//msgflag=1,新建app刷list
        $scope.queryApp = function(msgflag){
					var appPM = HttpService.getInfo("app/findall");
					appPM.then(function(data){
						$scope.appAlllistInfo = data;
						$scope.applistInfo = data.filter(function(item){
								return item.isDebug!=true;
						});

						if(msgflag==1){return false;}

						var lastId = UtilService.getCookie("ryioLastApp");
            var demoapk = UtilService.getCookie("ryioDemoapk");
            UtilService.setCookie("ryioDemoapk","");
						if($scope.applistInfo.length > 0){
							if(UtilService.isNullStr(lastId)){
								lastId = "-1";
							}
							lastId = Number(lastId);
							var apps = $scope.applistInfo.filter(function(item){
                    if(!UtilService.isNullStr(demoapk)){
                        return item.appkey == demoapk;
                    }
                    else{
                        return item.id == lastId;
                    }
									});
									if(apps.length == 0){
										lastId = $scope.applistInfo[0].id;
									}
                else{
                    lastId = apps[0].id;
                }
                if($scope.appidInit == lastId){
                    $scope.appfresh = ++rmd;
                }else{
                    $scope.appidInit = lastId;
                }
                for(i=0; i < $scope.applistInfo.length; i++){
                    if($scope.applistInfo[i].id == $scope.appidInit){
                        $scope.appkey = $scope.applistInfo[i].appkey;
                    }
                }
					}
					else{
						if($rootScope.isSuper || $rootScope.isManage || $rootScope.isAppManage){
							$state.go("collect.app");
						}
	          else{
	              $scope.goLogin();
	          }
					}
			});
		};

		$scope.$on('f5Applist',function(e,msg){
			$scope.queryApp(msg);
		});
    $scope.hasSubMenus = function(){
        $scope.showMenuFlag = {};
        var menus = $rootScope.curRoleAuth.roleAuthDetailList;
        var first = "";
        for(var i=0;i<menus.length;i++){
            if($scope.showMenuFlag.admonitor && $scope.showMenuFlag.behavior && $scope.showMenuFlag.export){
                break;
            }
            if(menus[i].parentAuth=='admonitor' || menus[i].parentAuth == 'campaignmanager'){
               $scope.showMenuFlag.admonitor = true;
            }else if(menus[i].parentAuth=='behavior' || menus[i].parentAuth == 'eventmanage'){
               $scope.showMenuFlag.behavior = true;
            }else if(menus[i].parentAuth=='export'){
               $scope.showMenuFlag.export = true;
            }
        }
        if($rootScope.mainMenu == 'export' && !$scope.showMenuFlag.export){
            $rootScope.mainMenu = "";
        }else if($rootScope.mainMenu == 'behavior' && !$scope.showMenuFlag.behavior){
            $rootScope.mainMenu = "";
        }else if($rootScope.mainMenu == 'admonitor' && !$scope.showMenuFlag.admonitor){
            $rootScope.mainMenu = "";
        }
    }

    $rootScope.webHideMenus = [];
		$scope.$on("appid",function(e,msg){
        $rootScope.appInstance = msg.info;
        $scope.platform = msg.info.platform;
        $rootScope.isandroid = $scope.platform == 'Android';
        $rootScope.isios = $scope.platform == 'iOS';
        $rootScope.isweb = $scope.platform == 'H5';

				var path = $location.$$path,idx = path.indexOf("Detail");
				if(path.indexOf('appDetail')>-1){return false;}

				if(idx>-1){
					$scope.appid = undefined;
					$location.path(path.substring(0,idx));
				}
        else if($rootScope.isweb && $rootScope.webHideMenus.indexOf($rootScope.pagePath)>-1){
            $scope.appid = undefined;
            $location.path($rootScope.firstMeau);
        }

				if($rootScope.pagePath == '' || $rootScope.pagePath == 'collect'
                    || (!$rootScope.isSuper && $rootScope.curRoleAuth && !$scope.hasTheMenu($rootScope.pagePath)))
				{
					$scope.appid = undefined;
					$location.path($rootScope.firstMeau);
				}

        $rootScope.appid = $scope.appid = msg.info.id;
				UtilService.setCookie("ryioLastApp",$scope.appid,7);
		});

    $scope.goToCustom = function(id,name){
        $location.path("/collect/custommenu/"+id);
        $rootScope.custID = id;
    }
    $scope.gotoCustonMenu = function(menuId){
        var url = $state.href('collect.custommenu');
        window.open(url+'/'+menuId,'_blank');
    }
		var rmd = new Date().getTime();
		$scope.$on("mngappTo",function(e,msg){
			if($scope.appid == msg){return false;}
			if($scope.appidInit == msg){
				$scope.appfresh = ++rmd;
			}else{
				$scope.appidInit = msg;
			}
		});

    $scope.loginuserName = UtilService.getCookie("ryioUname");
		$scope.currentAccountId = UtilService.getCookie("ryioUid");
    $scope.userPastDate = UtilService.getCookie("ryioPastDate");

			$scope.errorBack = function(msg){
				ToolService.showTips(msg);
			};

				var rmdId = UtilService.randRangeId(),auid = UtilService.getCookie("ryioUid");

				$scope.goPage = function(ui){
						$rootScope.channeluniqueName = 'normal';
			      if(ui == 'home'){
							ui = $rootScope.firstMeau;
							ui = ui.substring(1).replace("/",".");
						}

			      if(ui == 'collect.custommenu'){
			          $rootScope.custID = "";
			      }
						var mmenu = ui.substring(ui.indexOf('.')+1);
			      if(mmenu == 'channel'){
			          $rootScope.channeluniqueName = "normal";
			      }
			      if($state.current && $state.current.name == ui){
			          $state.reload(ui,{pageid:null});
			      }else{
			          $state.go(ui,{pageid:null});
			      }
				}
        $scope.resizeStyle = function(){
            var mleft = '0px';
            if($rootScope.pagePath == "userinfo" || $rootScope.pagePath == "nopower"){
                $rootScope.mainMenu = false;
            }else{
                mleft = $rootScope.unfoldFlag?'40px':'186px';
            }
            $(".conditionAlpha").css('left',mleft);
            $rootScope.panelw = $(window).width()-mleft.slice(0,-2)-84;
            return {'margin-left':mleft};
        }
        $scope.toggleMenu = function(){
            $rootScope.unfoldFlag = !$rootScope.unfoldFlag;
            UtilService.setCookie("unfoldFlag",$rootScope.unfoldFlag);

            $scope.$broadcast("conentresize",true);
        }

        //flag:1一级菜单显示权限  2:编辑权限
        $rootScope.hasTheMenu = function(name,flag,getmenus){
            var menus = $rootScope.curRoleAuth.roleAuthDetailList.filter(function(item){
                if(angular.isDefined(flag) && flag == 1){
                    if($rootScope.isweb){
                        return item.parentAuth == name && $scope.webHideMenus.indexOf(item.auth)==-1;
                    }
                    else{
                        return item.parentAuth == name;
                    }
                }
                if(angular.isDefined(flag) && flag == 2){
                    return item.auth == name && item.edit == true;
                }
                else{
                    if(name == 'export'){
                        return $rootScope.hasTheMenu(name,1);
                    }
                    else{
                        return item.auth == name && item.view == true;
                    }

                }
            });
            if(angular.isDefined(getmenus)){
                return menus;
            }
            else{
                return menus.length>0;
            }
        }
        $rootScope.showSubMenus = function(mainMenu){
            if($scope.channelAlert){
                return false;
            }
            if(mainMenu!='management' && $scope.applistInfo && $scope.applistInfo.length == 0){
                if($scope.appAlllistInfo.length > 0){
                    ToolService.showTips("请先完成"+$scope.appAlllistInfo[0].name+"的数据调试");
                }
                else{
                    ToolService.showTips("请先创建应用");
                }
                return false;
            }
            $rootScope.mainMenu = mainMenu;
            var first = "";
            if(mainMenu=='behavior'){
								first = "/collect/"+$rootScope.mainMenus.behavior[0];
						}else if(mainMenu=='export'){
								first = "/collect/"+$rootScope.mainMenus.dataexport[$rootScope.isweb?1:0];
						}else{
								first = "/manage/"+$rootScope.mainMenus.manage[0];
						}
						$location.path(first);
        }
        $rootScope.showMenu = function(name,flag){
            if(name == null){
                name = $scope.pagePath;
            }
            if($scope.isweb && $scope.webHideMenus.indexOf(name)>-1){
                return false;
            }
            if($rootScope.isSuper || $rootScope.isManage || $rootScope.isAppManage){
                $scope.campaigninfoGroup = true;
                return true;
            }else{
                if($rootScope.curRoleAuth){
                   return $scope.hasTheMenu(name,flag);
                }
                else{
                   return false;
                }
            }
        }
        $rootScope.hasEditPower = function(){
            return $rootScope.showMenu(null,2);
        }

        $scope.showDataModel = function(m){
            if($rootScope.isweb && m == 'retention'){return false;}
            if(m == 'flow'){return true;}
            if(m == 'channel'){return true;}

            var key = {'pay':'payAuth','retention':'retentionAuth','isnatureopen':'isNatureOpen','topauth':"topAuth"}[m];
        	if($rootScope.isSuper || $rootScope.isManage || $rootScope.isAppManage){
        		return true;
        	}else{
        		if($rootScope.curRoleAuth){
        			return $rootScope.curRoleAuth[key];
        		}
        		else{
        			return false;
        		}
        	}
        }
        $scope.formTipMsg = "信息没填全或数据格式有误,请检查";

        $rootScope.$watch("pagePath+isweb",function(n){
          n = $scope.pagePath;
        	if(angular.isDefined(n) && n!='' && n!= "product"){
              var tipPM = HttpService.getInfo("tip/"+n, {});
	        		tipPM.then(function(data){
	        			$rootScope.currentPageTips = data;
	        		},function(data){
	        			$rootScope.currentPageTips = {};
	        		});
        	}
        	else{
        		$rootScope.currentPageTips = {};
        	}
        });

        $scope.userLogout = function(){
        	var lgPM = HttpService.getInfo("login/logout", {});
	    		lgPM.then(function(data){
	    			HttpService.logOutCookie();
	    		});
				}

        $scope.showNoticew = false;
        $scope.queryNotice = function(){
        	var noticePM = HttpService.getInfo("notice/findDeploy", {});
        	noticePM.then(function(data){
        		$scope.noticeList = data;

        		var sortNotice = UtilService.cloneJSON(data);
						if(sortNotice && angular.isArray(sortNotice)){
							sortNotice.sort(function(a,b){
	        			return new Date(a.deployDate) > new Date(b.deployDate) ? -1 : 1;
	        		});
						}
						else{
							sortNotice = [];
						}
        		if(sortNotice.length>0){
        			$scope.newNoticeInfo = sortNotice[0];
        		}
        	});
        	$timeout($scope.queryNotice,1000*60*3);
        }
        $scope.showNoticeWin = function(){
        	$scope.showNoticew = true;
        	ToolService.showAlp();
        }
        $scope.hideNoticeWin = function(){
        	$scope.showNoticew = false;
        	ToolService.hideAlp();
        }
        $scope.clickNotice = function(news){
        	var id = news.id;
        	if($scope.curNoticeId == id){
        		$scope.curNoticeId = -1;
        	}
        	else{
        		$scope.curNoticeId = id;
        		if(!news.isRead){
        			news.isRead = true;
        			if($scope.newNoticeInfo && $scope.newNoticeInfo.id == id){
        				$scope.newNoticeInfo.isRead = true;
        			}
        			HttpService.postInfo("notice/saveReadLog/"+id, {});
        		}
        	}
        }
        $scope.initpage = function(){
            $scope.queryLimit();
            $scope.queryApp();
            $scope.queryNotice();
        }

        var lpath = $location.path();
        if(lpath!='/active/product'){
            $scope.initpage();
        }
        //判断是否需要向后台发送请求检测名称重复
        $scope.judgeNameChange = function(oldname,newname){
            if(!UtilService.isNullStr(newname)  && (oldname !='' && newname !=''  && angular.lowercase(oldname) != angular.lowercase(newname) || (oldname=='' && newname!=''))){
                return true;
            }
            else{
                return false;
            }
        }

        $scope.pwdPlacehold = "仅支持数字,大小写字母,且至少包含其中2种,长度限制为6-18位";
	}
})();