var sxUtil = sxUtil || {};
var orgIdTitle;


sxUtil['tree']={
        //登陆用户所在的组织机构id
        getLoginOrgId:function(){
            return $('#loginOrgId').val();
        },
        //组织机构树选中的组织机构id
        getSelectOrgId:function(){
            return $('#navTreeSelectOrgId').val();
        },
        //组织机构树选中的组织机构级别是否网格
        isGrid:function(){
        	var org = $('#navTreeSelectOrgId').data('org');
        	if(!org || !org.orgLevel || !org.orgLevel.code){
        		return false;
        	}
            return org.orgLevel.code == 'orgLevel_107';
        },
        //组织机构树选中的组织机构完整信息
        getSelectOrgAll:function(){
            return $('#navTreeSelectOrgId').data('org');
        },
        //刷新选中的树节点
        refreshSelectedNode:function(treeId){
            var zTree = $.fn.zTree.getZTreeObj(treeId),
            nodes = zTree.getSelectedNodes(),
            treeNode = nodes[0];
            if (treeNode.isParent) {
                zTree.reAsyncChildNodes(treeNode, "refresh");
            }else{
            	 treeNode.isParent=true;
            	 zTree.reAsyncChildNodes(treeNode, "refresh");
            }
            
        },
        //初始化导航树
        navTree:function(option){
            
            if(!option || !option.id){
                return ;
            }
            
            var self = $(option.id);

            function getOrgAsyncUrl(treeId, treeNode) {
                
                return !treeNode ? "/org/findRootOrgTreeNode" : "/org/findNodeByParentId";
                
            };
            
            function zTreeOnClick(event, treeId, treeNode) {
                hideMenu();
                self.text(treeNode.name);
                $('#navTreeSelectOrgId').val(treeNode.id);
                option.selectedAfter();
            };
            
            function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
                
                var treeObj = $.fn.zTree.getZTreeObj("orgTree");
                if(!treeNode){
                    var nodes = treeObj.getNodes();
                    treeObj.selectNode(nodes[0]);
                    self.text(nodes[0].name);
                }
                
            };
            
            function orgTreeInit(e){
                var setting = {
                        callback: {
                            onClick: zTreeOnClick,
                            onAsyncSuccess: zTreeOnAsyncSuccess
                        },
                        view: {
                            dblClickExpand: false
                        },
                        async:{
                            enable:true,
                            dataType:"json",
                            url: getOrgAsyncUrl,
                            autoParam:["id=parentId"]
                        },
                        data: {
                            simpleData: {
                                enable: true
                            }
                        }
                };
                self.after('<div id="orgTree" class="ztree org-search-tree"></div>'
                        +'<div id="btnbanner" class="btnbanner"> <a id="orgTreeSelect" href="javascript:;">确定'
                        +'</a><a id="orgTreeSelectNot" href="javascript:;">取消</a></div>');
                $.fn.zTree.init($("#orgTree"), setting);
            }
                
            function showMenu() {
                $('#orgTree').slideDown("fast");
                $('#btnbanner').slideDown("fasr")
                $("body").on("mousedown", onBodyDown);
                $(".nav-option-org-icon").addClass('fa-caret-down').removeClass('fa-caret-up');
            }
            
            function hideMenu() {
                $("#orgTree").fadeOut("fast");
                $("#btnbanner").fadeOut("fast");
                $("body").off("mousedown", onBodyDown);
                $(".nav-option-org-icon").removeClass('fa-caret-down').addClass('fa-caret-up');
            }
            
            function onBodyDown(event) {
                if (!($(event.target).hasClass('ztree') || event.target.id == self.attr('id') || $(event.target).parents(".ztree").length>0)) {
                    hideMenu();
                }
            }
            
            self.click(function(e){
                showMenu();
            });

            orgTreeInit();
        },
        navTreeMap : function(option) {
            if (!option) {
                return;
            }
            option.id = '#navOptionCurrentOrg';
            var self = $(option.id);
            var orgId = $('#navTreeSelectOrgId').val();
            var btn = "#btnbanner";
            if(option.btn){
                btn = option.btn;
            }
            
            function getOrg() {
                if(orgIdTitle == null ||option.orgIdTitle)
                    orgIdTitle = orgId;
                orgId = orgIdTitle;
                $.ajax({
                    type:"GET",
                	url : "/org/get",
                    data:{"orgId":orgIdTitle},
                    async : false,
                    success : function(data) {
                        self.text(data.name);
                        name = data.name;
                        $('#navTreeSelectOrgId').data('org',data);
                        $('#navTreeSelectOrgId').val(data.id);
                    }
                })
                if( option.hasMember ){
	                $.ajax({
	                	    url : "user/do_getUserByOrg",
	                	    type:'get',
	                    data:{"department.id":orgIdTitle},
	                    async : false,
	                    success : function(data) {
		                    	if( data.success ){
		                    		var lis = '<li class="orgUserLiLeft" user-id="all"><a>全部成员</a></li>';
		                    		for( var i=0;i<data.data.length;i++ ){
		                    			lis += '<li class="orgUserLiLeft" user-id='+data.data[i].id+'><a>'+data.data[i].name+'</a></li>'
		                    		}
		                    		$("#orgUsersLeft").append(lis)
		                    	}
	                    }
	                })	
                }
            }
            
            function getLowerOrg(parentId) {
            		$(".plan-statistics .condition-query .dropdown").removeClass("open");
                $.ajax({
                    url : "/org/findNodeByParentId",
                    data : {
                        "parentId" : parentId
                    },
                    async : false,
                    beforeSend : function() {
                        $('#loadingDiv').show();
                    },
                    success : function(data) {
                        $('#loadingDiv').hide();
                        $(btn).empty();
                        orgId = parentId;
                        getOrgSelectbox(parentId);
                        var html = '';
                        html += '<div class="organizationBox">';
                        for (var i = 0; i < data.length; i++) {
                            html += '<a id=' + data[i].id + ' href="javascript:;" class="select">' + data[i].name + '</a>';
                        }
                        html += '</div>';
                        html += '<div class="bottomMap">';
                        html += '<a id="orgTreeSelect" href="javascript:;" class="btn btn-info btn-white colorbtn btn-minier" style="padding-top:0.06rem">确定</a>';
                        html += '<a id="orgTreeSelectNot" href="javascript:;" class="btn btn-white btn-info btn-minier" style="padding-top:0.06rem">取消</a>';
                        html += '</div>';
                        $(btn).append(html);
                    }
                });
            };

            function getOrgSelectbox(orgId) {
                $.ajax({
                    type:'GET',
                	url : '/org/getOrgSelectbox',
                    data : {
                        'nowId' : orgId
                    },
                    async : false,
                    beforeSend : function() {
                        $('#loadingDiv').show();
                    },
                    success : function(data) {
                        $('#loadingDiv').hide();
                        var html = "";
                        name = data[0].name;
                        orgId = orgId;
                        html +='<div id="refreshOrgTreeDiv" class="refreshOrgTreeDiv">';
                        html +='<div class="ui-widget" style="position:relative;">';
                        //html +='<i class="ace-icon fa fa-search nav-search-icon"></i><input class="nav-search-input" id="org-tree-autocomplete" type="text" value="查询辖区..." />';
                        html +='</div>';
                        html +='</div>';
                        $(btn).append(html);
                        var $html = $('<ol class="breadcrumb orgBoxResult"></ol>');
                        for (var i = data.length; i > 0; i--) {
                            var _a='';
                            if (i == 1) {
                                _a += '<li><a class="address cur" id=' + data[i - 1].id + '>'+data[i - 1].name +'</a></li>';
                            } else {
                                _a += '<li><a class="address" id=' + data[i - 1].id + '>'+data[i - 1].name +'</a></li>';
                            }
                            $html.append($(_a).data('org',data[i-1]));
                        }
                        $(btn).append($html);
                    }
                });
            };
            
            //清除查询辖区并进行自动完成
            $("body").on('focusin','#org-tree-autocomplete',function(){
                if($(this).val() == "查询辖区..."){
                    $(this).attr("value","");
                }
                $(this).autocomplete({
                   source:function(request,response){
                           $.ajax({
                               url:'/org/ajaxFindOrganizationsByOrgName',
                               data:{'orgName':function(){ return request.term;}},
                               success:function(data){
                                   response($.map(data,function(item){
                                       return {
                                           label:item.name,
                                           value:item.name,
                                           id:item.id
                                       }
                                   }))
                               }
                           });
                   },
                   select:function(event,ui){
                       getLowerOrg(ui.item.id);
                       event.stopPropagation();
                   }
                })
            });
            
            //添加查询辖区字
            $("body").on('focusout','#org-tree-autocomplete',function(){
                if(!$(this).val()){
                    $(this).attr("value","查询辖区...");
                }
            })
            
            $("body").click(function(){
                $(btn).hide();
            });
            
            $("body").on('click',btn,function(event){event.stopPropagation();});
            
            // 选中的a标签
            $(".nav-localtion").on('click', '.select', function(event) {
                orgId = $(this).attr("id");
                getLowerOrg(orgId);
                $(btn).show();
                event.stopPropagation();
            });
            
            $(".nav-localtion").on('click', '.address', function(event) {
                orgId = $(this).attr("id");
                getLowerOrg(orgId);
                $(btn).show();
                event.stopPropagation();
            });

            $(".nav-localtion").on('click', '#orgTreeSelect', function(event) {
                $('#navTreeSelectOrgId').val(orgId);
                $('#navTreeSelectOrgId').data('org',$('#'+orgId).data('org'));
                orgIdTitle = orgId;
                self.text(name);
                $(btn).hide();
                //更新成员
                if( option.hasMember ){
                		$("#orgUsersLeft").empty();
                		$(".orgUserBtnLeft").find('i').attr("checkid",'all').text("全部成员");
	                $.ajax({
		            	    url : "user/do_getUserByOrg",
		            	    type:'get',
		                data:{"department.id":orgIdTitle},
		                success : function(data) {
		                    	if( data.success ){
		                    		var lis = '<li class="orgUserLiLeft" user-id="all"><a>全部成员</a></li>';
		                    		for( var i=0;i<data.data.length;i++ ){
		                    			lis += '<li class="orgUserLiLeft" user-id='+data.data[i].id+'><a>'+data.data[i].name+'</a></li>'
		                    		}
		                    		$("#orgUsersLeft").append(lis)
		                    	}
		                }
		            })	
                };
                if( option.transferParams ){
                		option.selectedAfter(option.transferParams);
                }else{
                		option.selectedAfter();
                }
                
                event.stopPropagation();
            });
            
            $(".nav-localtion").on('click', '#orgTreeSelectNot', function() {
                $(btn).hide();
            });
            
            $("#navOptionOrg").on('click', function() {
                if (orgId == null)
                    orgId = $('#navTreeSelectOrgId').val();
                getLowerOrg(orgId);
                $(btn).show();
                event.stopPropagation();
            });

            getOrg();
        }
        
}



jQuery.fn.extend({
    treeSelect: function(option) {
         var self = $(option.id);
          var orgTreeInit = function(e){
                var setting = {
                        callback: {
                            onClick: zTreeOnClick,
                            onAsyncSuccess: zTreeOnAsyncSuccess
                        },
                        view: {
                            dblClickExpand: false,
                            selectedMulti: false
                        },
                        async:{
                            enable:true,
                            dataType:"json",
                            url: getOrgAsyncUrl,
                            autoParam:["id=parentId"]
                        },
                        data: {
                            simpleData: {
                                enable: true
                            }
                        }
                };
                $.fn.zTree.init(self, setting);
            }
            
            function getOrgAsyncUrl(treeId, treeNode) {
                return !treeNode ? "/org/findRootOrgTreeNode" : "/org/findNodeByParentId";
            }
            
            function zTreeOnClick(event, treeId, treeNode) {
                option.selectedAfter(treeNode.id);
            }
            
            function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
                var treeObj = $.fn.zTree.getZTreeObj(''+treeId);
                if(!treeNode){
                    var nodes = treeObj.getNodes();
                    treeObj.selectNode(nodes[0]);
                    option.selectedAfter(nodes[0].id);
                }
            }
            
            orgTreeInit();
    }
});