define(['table', 'form','../libs/iconselect','treegrid','bootstrap-table-treegrid'], function (Table,Form,IconSelector) {
    var AdminRule = {
        //Do setup work hereAction
        index: function () {
            this.initTalbe();
        },
        initTalbe:function(){

            var apiResults_type = ["目录","菜单","权限"];
            Table.api.init({
                extend: {
                    index_url: 'AdminRule/select',
                    add_url: 'AdminRule/insert',
                    edit_url: 'AdminRule/update',
                    del_url: 'AdminRule/delete',
                    multi_url: 'AdminRule/multi',
                    dragsort_url: 'AdminRule/weigh',
                    table: 'AdminRule',
                }
            });


            /**
             * 选中父项时，同时选中子项
             * @param datas 所有的数据
             * @param row 当前数据
             * @param id id 字段名
             * @param pid 父id字段名
             */
            function selectChilds(datas,row,id,pid,checked) {
                for(var i in datas){
                    if(datas[i][pid] == row[id]){
                        datas[i][0]=true;
                        datas[i].check=checked;
                        selectChilds(datas,datas[i],id,pid,checked);
                    };
                }
            }

            function selectParentChecked(datas,row,id,pid){
                for(var i in datas){
                    if(datas[i][id] == row[pid]){
                        datas[i].check=true;
                        datas[i][0]=true;
                        selectParentChecked(datas,datas[i],id,pid);
                    };
                }
            }
            var table = $("#table");
            var tableOptions = {
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weight',
                sortOrder: 'desc',
                pagination: false,
                commonSearch: false,
                search: false,
                treeShowField: 'title',
                parentIdField: 'pid',
                idField: 'id',
                uniqueId: 'id',
                clickToSelect: false, //是否启用点击选中
                dblClickToEdit: true, //是否启用双击编辑
                singleSelect: false, //是否启用单选
    
                onCheck1: function(row) {
                    var datas = table.bootstrapTable('getData');
                    table.treegrid('saveState')
                    selectChilds(datas, row, 'id', 'pid', true); // 选择子类
                    
                    selectParentChecked(datas, row, 'id', 'pid'); // 选择父类
                    
                    table.bootstrapTable('load', datas);
                    table.treegrid('restoreState')
                },
                
                onUncheck1: function(row) {
                    table.treegrid('saveState')
                    var datas = table.bootstrapTable('getData');
                    selectChilds(datas, row, 'id', 'pid', false);
                    table.bootstrapTable('load', datas);
                    table.treegrid('restoreState')
                },
                onResetView: function(data) {
                    //console.log($.fn.treegrid)
                    table.treegrid({
                        initialState: 'expanded1', // 所有节点都折叠
                        treeColumn: 2,
                        expanderExpandedClass: 'mdi mdi-folder-open',  // 可自定义图标样式
                        expanderCollapsedClass: 'mdi mdi-folder',
                        onChange: function() {
                            table.bootstrapTable('resetWidth');
                        }
                    });
                    
                    // 只展开树形的第一集节点
                    //table.treegrid('getRootNodes').treegrid('expand');
                },
                columns: [
                    [
                        {checkbox: true},
                        {
                            field: 'id',
                            title: 'ID',
                            filter: "number",
                            sortable: true    // 是否排序
                        },
                        {
                            field: 'title',
                            title: '标题',
                            filter: "string",
                            align:"left"
                        },
                        {
                            title: "图标",
                            field: "icon",
                            formatter: function (v,d) {
                                return '<i class="layui-icon ' + d["icon"] + '"></i>';
                            }
                        },
                        {
                            title: "key",
                            field: "key",
                            filter: "string",
                            sortable: true,    // 是否排序
                        },
                        // {
                        //     title: "上级菜单",
                        //     field: "pid",
                        //     hide: true,
                        //     formatter: function (v,d) {
                        //         let field = "pid";
                        //         if (typeof d[field] == "undefined") return "";
                        //         let items = [];
                        //         $.each((d[field] + "").split(","), function (k , v) {
                        //             items.push( v);
                        //         });
                        //         return items.join(",");
                        //     }
                        // },
                        {
                            title: "创建时间",
                            field: "created_at",
                            visible: false,
                        },
                        {
                            title: "更新时间",
                            field: "updated_at",
                            visible: false,
                        },
                        {
                            title: "url",
                            field: "href",
                            visible: false,
                        },
                        {
                            title: "类型",
                            field: "type",
                            width: 80,
                            formatter: function (v,d) {
                                let field = "type";
                                let value =  apiResults_type[d["type"]] || d["type"];
                                let css = {"目录":"layui-bg-blue", "菜单": "layui-bg-green", "权限": "layui-bg-orange"}[value];
                                return '<span class="layui-badge '+css+'">'+value+'</span>';
                            },
                            visible: false
                        },
                        {
                            title: "状态",
                            field: "status",
                            formatter:Table.api.formatter.switch
                        },
                        {
                            title: "排序",
                            field: "weight",
                            width: 80,
                        },  
                        {field: 'operate', title: '操作', table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            };
            // 初始化表格
            table.bootstrapTable(tableOptions);
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        update:function(){
            this.bindevent();
        },
        insert:function(){
            this.bindevent();
        },
        bindevent:function(){
            Config['upload_url'] = '/files/avatar';
            var form = $('form');
            Form.api.bindevent(form)
            IconSelector.bind($(".btn-search-icon"),$("input#icon"));
        }
    };
    return AdminRule
});