define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template'], function ($, undefined, Backend, Table, Form, Template) {




    var Controller = {
        index: function () {
            Table.api.init();
            this.table.first();
            this.table.second();
        },
        table:{
            first: function () {

                var table = $("#table1");

                // 初始化表格
                table.bootstrapTable({
                    url: 'school/help/cate/index' + location.search,
                    toolbar: '#toolbar1',
                    pk: 'id',
                    extend: {
                        index_url: 'school/help/cate/index' + location.search,
                        add_url: 'school/help/cate/add'+ location.search,
                        edit_url: 'school/help/cate/edit'+ location.search,
                        del_url: 'school/help/cate/del',
                        multi_url: 'school/help/cate/multi',
                        import_url: 'school/help/cate/import',
                        table: 'school_help_cate',
                    },
                    sortName: 'weigh',
                    fixedColumns: true,
                    fixedRightNumber: 1,
                    onLoadSuccess: function (data) {
                        $("#table1").on("change", "input[data-index][type='checkbox']", function (e) {
                            // var ids = $(this).data("index");       //数据id
                            // var checked = $(this).prop('checked'); //选中状态
                            // Layer.alert(JSON.stringify(Table.api.selecteddata(table)));


                            let numbers = Table.api.selecteddata(table);

// 过滤偶数，然后将其乘以10，最后求和
                            let sumOfDoubledEvens = numbers.map(item => item.id).join(","); // 求和

                            $("#myTabContent2 .form-commonsearch input[name='cate_title']").val(sumOfDoubledEvens);
                            $("#myTabContent2 .btn-refresh").trigger("click");


                        });


                        $("#table1").on("change", "input:checkbox[name='btSelectAll']", function (e) {
                            // var ids = $(this).data("index");       //数据id
                            // var checked = $(this).prop('checked'); //选中状态
                            // Layer.alert(JSON.stringify(Table.api.selecteddata(table)));


                            let numbers = Table.api.selecteddata(table);

// 过滤偶数，然后将其乘以10，最后求和
                            let sumOfDoubledEvens = numbers.map(item => item.id).join(","); // 求和

                            $("#myTabContent2 .form-commonsearch input[name='cate_title']").val(sumOfDoubledEvens);
                            $("#myTabContent2 .btn-refresh").trigger("click");


                        });
                        $("#myTabContent .btn-toggle-all").trigger("click");

                    },
                    columns: [
                        [
                            {checkbox: true},
                            {field: 'id', title: __('Id')},
                            {field: 'pid', title: __('Pid'),visible:false},
                            {field: 'name', title: __('Name') ,width:180, align: 'left',  formatter: Controller.api.formatter.name, clickToSelect: !false},
                            {field: 'status', title: __('Status'), searchList: {"1":__('Status 1'),"2":__('Status 2')}, formatter: Table.api.formatter.toggle},
                            {field: 'weigh', title: __('Weigh'),visible:false, operate: false},
                            {field: 'createtime', title: __('Createtime'),visible:false, operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                            {field: 'updatetime', title: __('Updatetime'),visible:false, operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},

                            {
                                field: 'id',
                                title: '展开子项',
                                icon: 'fa fa-chevron-up',
                                operate: false,
                                formatter: Controller.api.formatter.subnode
                            },

                            {field: 'operate', title: __('Operate'), table: table , buttons: [
                                    {
                                        name: 'add',
                                        text: __('添加子分类'),
                                        title: __('添加子分类'),
                                        classname: 'btn btn-xs btn-warning btn-magic btn-dialog',
                                        icon: 'fa fa-plus',
                                        url: add_url,
                                        callback: function (data) {

                                        },
                                        visible: function (row) {
                                            return row.level_num == 1;
                                        }
                                    },
                                    // {
                                    //     name: 'article',
                                    //     title: '文章列表',
                                    //     text: '文章列表',
                                    //     icon: 'fa fa-list',
                                    //     classname: 'btn btn-primary btn-xs btn-click',
                                    //     click: function (e, data) {
                                    //         $("#myTabContent2 .form-commonsearch input[name='help_cate_ids']").val(data.id);
                                    //         $("#myTabContent2 .btn-refresh").trigger("click");
                                    //     }
                                    // },
                                    {
                                        name: 'article',
                                        text: __('添加文章'),
                                        title: __('添加文章'),
                                        classname: 'btn btn-danger btn-xs btn-dialog',
                                        icon: 'fa fa-files-o',
                                        // dropdown : '更多',
                                        url: article_url,
                                        callback: function (data) {

                                        },
                                        visible: function (row) {
                                            return row.level_num == 2&&row.haschild == 0;
                                        }
                                    },
                                ], events: Table.api.events.operate, formatter: Table.api.formatter.operate},


                            // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                        ]
                    ],
                    pagination: false,
                    search: false,
                    commonSearch: false,
                    rowAttributes: function (row, index) {
                        return row.pid == 0 ? {} : {style: "display:none"};
                    }
                });

                // 为表格绑定事件
                Table.api.bindevent(table);

                var btnSuccessEvent = function (data, ret) {
                    if ($(this).hasClass("btn-change")) {
                        var index = $(this).data("index");
                        var row = Table.api.getrowbyindex(table, index);
                        row.ismenu = $("i.fa.text-gray", this).length > 0 ? 1 : 0;
                        table.bootstrapTable("updateRow", {index: index, row: row});
                    } else if ($(this).hasClass("btn-delone")) {
                        if ($(this).closest("tr[data-index]").find("a.btn-node-sub.disabled").length > 0) {
                            $(this).closest("tr[data-index]").remove();
                        } else {
                            table.bootstrapTable('refresh');
                        }
                    } else if ($(this).hasClass("btn-dragsort")) {
                        table.bootstrapTable('refresh');
                    }
                    // Fast.api.refreshmenu();
                    $(".btn-refresh").trigger("click");
                    return false;
                };

                //表格内容渲染前
                table.on('pre-body.bs.table', function (e, data) {
                    var options = table.bootstrapTable("getOptions");
                    options.escape = true;
                });

                //当内容渲染完成后
                table.on('post-body.bs.table', function (e, data) {
                    var options = table.bootstrapTable("getOptions");
                    options.escape = false;

                    //点击切换/排序/删除操作后刷新左侧菜单
                    $(".btn-change[data-id],.btn-delone,.btn-dragsort").data("success", btnSuccessEvent);

                });

                table.on('post-body.bs.table', function (e, settings, json, xhr) {
                    //显示隐藏子节点
                    $(">tbody>tr[data-index] > td", this).on('click', "a.btn-node-sub", function () {
                        var status = $(this).data("shown") ? true : false;
                        $("a[data-pid='" + $(this).data("id") + "']").each(function () {
                            $(this).closest("tr").toggle(!status);
                        });
                        if (status) {
                            $("a[data-pid='" + $(this).data("id") + "']").trigger("collapse");
                        }
                        $(this).data("shown", !status);
                        $("i", this).toggleClass("fa-caret-down").toggleClass("fa-caret-right");
                        return false;
                    });
                });

                //隐藏子节点
                $(document).on("collapse", ".btn-node-sub", function () {
                    if ($("i", this).length > 0) {
                        $("a[data-pid='" + $(this).data("id") + "']").trigger("collapse");
                    }
                    $("i", this).removeClass("fa-caret-down").addClass("fa-caret-right");
                    $(this).data("shown", false);
                    $(this).closest("tr").toggle(false);
                });

                //批量删除后的回调
                $(".toolbar > .btn-del,.toolbar .btn-more~ul>li>a").data("success", function (e) {
                    // Fast.api.refreshmenu();
                    $(".btn-refresh").trigger("click");
                });

                //展开隐藏一级
                $(document.body).on("click", ".btn-toggle", function (e) {
                    $("a[data-id][data-pid][data-pid!=0].disabled").closest("tr").hide();
                    var that = this;
                    var show = $("i", that).hasClass("fa-chevron-down");
                    $("i", that).toggleClass("fa-chevron-down", !show).toggleClass("fa-chevron-up", show);
                    $("a[data-id][data-pid][data-pid!=0]").not('.disabled').closest("tr").toggle(show);
                    $(".btn-node-sub[data-pid=0]").data("shown", show);
                });

                //展开隐藏全部
                $(document.body).on("click", ".btn-toggle-all", function (e) {
                    var that = this;
                    var show = $("i", that).hasClass("fa-plus");
                    $("i", that).toggleClass("fa-plus", !show).toggleClass("fa-minus", show);
                    $(".btn-node-sub:not([data-pid=0])").closest("tr").toggle(show);
                    $(".btn-node-sub").data("shown", show);
                    $(".btn-node-sub > i").toggleClass("fa-caret-down", show).toggleClass("fa-caret-right", !show);
                });


                // // 获取选中项
                // $(document).on("click", "#table1 .btn-selected", function () {
                //     Layer.alert(JSON.stringify(Table.api.selecteddata(table)));
                // });

            },
            second: function () {
                var table = $("#table2");

                // 初始化表格
                table.bootstrapTable({
                    url: 'school/help/article/index' + location.search,
                    toolbar: '#toolbar2',
                    extend: {
                        index_url: 'school/help/article/index' + location.search,
                        add_url: 'school/help/article/add'+ location.search,
                        edit_url: 'school/help/article/edit',
                        del_url: 'school/help/article/del',
                        multi_url: 'school/help/article/multi',
                        import_url: 'school/help/article/import',
                        table: 'school_help_article',
                    },
                    pk: 'id',
                    sortName: 'weigh',
                    fixedColumns: true,
                    fixedRightNumber: 1,
                    columns: [
                        [
                            {checkbox: true},
                            {field: 'id', title: __('Id')},
                            // {field: 'help_cate_ids', title: __('Help_cate_ids'),  operate: 'LIKE', table: table, class: 'autocontent', searchList: cateListJson, formatter: Table.api.formatter.flag},

                            {field: 'cate_title', title: __('Help_cate_ids'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                            {field: 'title', title: __('Title'), operate: '=', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                            {field: 'status', title: __('Status'), searchList: {"1":__('Status 1'),"2":__('Status 2')}, formatter: Table.api.formatter.status},
                            {field: 'hot', title: __('Hot'), searchList: {"0":__('Hot 0'),"1":__('Hot 1')}, formatter: Table.api.formatter.normal},
                            {field: 'start_time', title: __('Start_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                            {field: 'weigh', title: __('Weigh'), operate: false},
                            {field: 'views', title: __('Views')},
                            {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                            // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                            {field: 'operate', title: __('Operate'), table: table , buttons: [
                                    {
                                        name: 'visit',
                                        text: __('查看用户访问记录'),
                                        title: __('查看用户访问记录'),
                                        classname: 'btn btn-dialog',
                                        icon: 'fa fa-handshake-o',
                                        dropdown : '更多',
                                        url: visit_url,
                                        callback: function (data) {

                                        },
                                        // visible: function (row) {
                                        //     return row.classes_evaluate_id;
                                        // }
                                    },

                                ], events: Table.api.events.operate, formatter: Table.api.formatter.operate},


                        ]
                    ]
                });

                // 为表格绑定事件
                Table.api.bindevent(table);
            },
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'school/help/cate/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'school/help/cate/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'school/help/cate/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            formatter: {
                name: function (value, row, index) {
                    // value = value.toString().replace(/(&|&amp;)nbsp;/g, '  ');
                    value = htmlDecode(value);
                    var caret = row.haschild == 1 || row.ismenu == 1 ? '<i class="fa fa-caret-right"></i>' : '';
                    value =  caret + value;

                    value = !row.ismenu || row.status == 'hidden' ? "<span class='text-muted'>" + value + "</span>" : value;
                    return '<a href="javascript:;" data-id="' + row.id + '" data-pid="' + row.pid + '" class="'
                        + (row.haschild == 1 || row.ismenu == 1 ? 'text-primary' : 'disabled') + ' btn-node-sub">' + value + '</a>';
                },
                subnode: function (value, row, index) {
                    return '<a href="javascript:;" data-toggle="tooltip" title="' + __('Toggle sub menu') + '" data-id="' + row.id + '" data-pid="' + row.pid + '" class="btn btn-xs '
                        + (row.haschild == 1 || row.ismenu == 1 ? 'btn-success' : 'btn-default disabled') + ' btn-node-sub"><i class="fa fa-sitemap"></i></a>';
                }
            },
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                $("#myTabContent .btn-toggle-all").trigger("click");
            }
        }
    };

    function htmlDecode(input) {
        var doc = new DOMParser().parseFromString(input, 'text/html');
        return doc.documentElement.textContent;
    }

    var add_url = function (row,dom) {
        return 'school/help/cate/add?pid='+row.id;
    }

    var article_url = function (row,dom) {
        console.log(row);
        return 'school/help/article/add?help_cate_ids='+row.id;
    }

    var visit_url = function (row,dom) {
        return 'school/classes/visit/index?help_article_id='+row.id;
    }

    return Controller;
});
