define(['table', 'form', 'yntree'], function (Table, Form, YnTree1) {
    var Admin = {
        //Do setup work hereAction
        index: function () {
            Table.api.init({
                extend: {
                    index_url: 'adminrole/select',
                    add_url: 'adminrole/insert',
                    edit_url: 'adminrole/update',
                    del_url: 'adminrole/delete',
                    multi_url: 'adminrole/multi',
                    dragsort_url: 'adminrole/weigh',
                    table: 'adminrole',
                }
            });

            var table = $("#table");
            var tableOptions = {
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                pagination: false,
                commonSearch: false,
                search: false,
                columns: [
                    [
                        { checkbox: true },
                        {
                            field: 'id',
                            title: 'ID',
                            filter: "number",
                            sortable: true    // 是否排序
                        },
                        {
                            field: 'name',
                            title: '角色组',
                            filter: "string",
                        },
                        // {
                        //     field: 'rules',
                        //     title: '权限',
                        //     filter: "string",
                        //     formatter: function (v,d) {
                        //         let field = "rules";
                        //         if (typeof d[field] == "undefined") return "";
                        //         let items = [];
                        //         var apiResults=[];
                        //         $.each((d[field] + "").split(","), function (k , v) {
                        //             items.push(apiResults[field][v] || v);
                        //         });
                        //         return items.join(",");
                        //     },
                        // }, 
                        {
                            title: "创建时间",
                            field: "created_at",
                        },
                        {
                            title: "更新时间",
                            field: "updated_at",
                            visible: false
                        },
                        {
                            title: "父级",
                            field: "pid",
                            formatter: function (v, d) {
                                return v;
                                // let field = "pid";
                                // var apiResults=[];
                                // if (typeof d[field] == "undefined") return "";
                                // let items = [];
                                // $.each((d[field] + "").split(","), function (k , v) {
                                //     items.push(apiResults[field][v] || v);
                                // });
                                // return items.join(",");
                            },
                            visible: false
                        },
                        { 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();
        },
        flatArrayToTree: function (items) {
            let res = []
            let getChildren = (res, pid) => {
                for (const i of items) {
                    if (i.parent === pid) {
                        const newItem = { ...i, children: [] }
                        newItem.name =newItem.text;
                        newItem.value =newItem.id;
                        newItem.checked =newItem.state.selected;
                        res.push(newItem)
                        getChildren(newItem.children, newItem.id)
                    }
                }
            }
            getChildren(res, 0)
            return res
        },
        rendertree: function (content) {
            if(Admin.ruletree){
                Admin.ruletree.destroy();
            }
            var treeData = {
                // 复选框change事件
                onchange: function (input, yntree) {
                    if ($("#treeview").length > 0) {
                        $("input[name='rules']").val(yntree.getValues().join(','));
                    }
                },
                // 是否严格的遵循父子互相关联的做法
                checkStrictly: true,
                data: []
            };
            treeData.data = Admin.flatArrayToTree(content)
            var yntree = new YnTree(document.getElementById("treeview"), treeData);
            Admin.ruletree = yntree;
        },
        ruletree: null,
        bindevent: function () {
            Form.api.bindevent($("form[role=form]"));
            //渲染权限节点树
            //变更级别后需要重建节点树
            $(document).on("change", "select[name='pid']", function () {
                var pid = $(this).data("pid");
                var id = $('[name=id]').val();
                $.ajax({
                    url: 'adminrole/tree?',
                    type: 'post',
                    dataType: 'json',
                    data: { id: id, pid: $(this).val() },
                    success: function (ret) {
                        if (ret.hasOwnProperty("code")) {
                            var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : [];
                            if (ret.code) {
                                Fast.api.error(ret.msg);
                            } else {
                                Admin.rendertree(data);
                            }
                        }
                    }, error: function (e) {
                        Fast.api.error(e.message);
                    }
                });
            });
            $("select[name='pid']").trigger("change");
        }
    };
    return Admin
});