"use strict";
layui.extend({
   common   :   'js/common'
}).use(['jquery','common','table','tree'],function(){
    var $ = layui.jquery;
    var common = layui.common;

    //  加载表格
    var layuiTable = common.layuiTable.render(layui.table,{
        elem: '#data_entity_table'
        ,url: '/permissions/region/authorize/pagingQuery?isAuthorized=1&orgId='+ pageData.orgId
        ,toolbar: '#table_head'
        , cols: [[
            { field: 'xqName', title: '小区名称',align:'center' }
            , { field: 'region', title: '区域',align:'center' }
            , { field: 'address', title: '详细地址' }
        ]]
    });


    //  类型转换
    var castDataForma = function(entityList){
        var list = [];
        entityList.forEach(function(entity){
            //  递归
            var subList = castDataForma(entity.subList);
            var item = {
                id      :   entity.id,
                name    :   entity.name,
                spread  :   true,
                children:   subList
            };
            //  添加元素
            list.push(item);
        });
        return list;
    };

    //  获取省市区树形菜单
    $.ajax({
        url     :   '/permissions/region/authorize/getAuthorizeRegionList/'  + pageData.orgId,
        success :   function(result){
            layui.tree({
                elem: '#per-tree'
                //  点击事件
                , click: function(item){
                    if (item.id === 100000){
                        item.id = null;
                    }
                    layuiTable.reload({
                        //  设定异步数据接口的额外参数
                        where: {
                            areaId    :   item.id
                        }
                        //  重新从第1页开始
                        ,page: {
                            curr: 1
                        }
                    });
                }
                , nodes: castDataForma(result.list)
            });
        }
    });

    //  操作栏事件绑定
    layui.table.on('toolbar(data_table_event)',function(obj){
        switch (obj.event) {
            //  修改
            case 'edit':
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
                parent.layui.common.openDefaultIframe({
                    title   :   '区域权限',
                    content :   '/permissions/org/region/permissions/edit/' + pageData.orgId
                });
                break;
        }
    });
});