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: 'UserRule/select',
                    add_url: 'UserRule/insert',
                    edit_url: 'UserRule/update',
                    del_url: 'UserRule/delete',
                    multi_url: 'UserRule/multi',
                    dragsort_url: 'UserRule/weigh',
                    table: 'UserRule',
                }
            });


            /**
             * 选中父项时，同时选中子项
             * @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: 'id',
                pagination: false,
                commonSearch: false,
                search: false,
                treeShowField: 'title',
                parentIdField: 'pid',
                idField: 'id',
                uniqueId: 'id',
                clickToSelect: false, //是否启用点击选中
                dblClickToEdit: true, //是否启用双击编辑
                singleSelect: false, //是否启用单选
    
                onCheck: function(row) {
                    var datas = table.bootstrapTable('getData');
                    
                    selectChilds(datas, row, 'id', 'pid', true); // 选择子类
                    
                    selectParentChecked(datas, row, 'id', 'pid'); // 选择父类
                    
                    table.bootstrapTable('load', datas);
                },
                
                onUncheck: function(row) {
                    var datas = table.bootstrapTable('getData');
                    selectChilds(datas, row, 'id', 'pid', false);
                    table.bootstrapTable('load', datas);
                },
                onResetView: function(data) {
                    //console.log($.fn.treegrid)
                    table.treegrid({
                        initialState: 'expanded', // 所有节点都折叠
                        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",
                        },
                        // {
                        //     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",
                            hide: true,
                        },
                        {
                            title: "更新时间",
                            field: "updated_at",
                            hide: true,
                        },
                        {
                            title: "url",
                            field: "href",
                        },
                        {
                            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>';
                            }
                        },
                        {
                            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)
            this.getRole();
            IconSelector.bind($(".btn-search-icon"),$("input#icon"));
        },
        getRole:function(){
            Fast.api.ajax({
                url: "UserRole/select?format=tree",
                dataType: "json",
                success: function (res) {
                    Layer.closeAll();
                    var html = "";
                    var selected=$('#roles').data('value');
                    for (let index = 0; index < res.data.length; index++) {
                        const element = res.data[index];
                        if(selected == element.id){
                            html+='<option value="'+element.id+'" selected>'+element.name+'</option>';
                        }else{
                            html+='<option value="'+element.id+'">'+element.name+'</option>';
                        }
                    }
                    $('#roles').append(html);
                }
            });
        }
    };
    return AdminRule
});