layui.config({
    base: '/assets/lib/jplus/treeTable/'
}).use(['form', 'layer', 'table', 'laytpl', 'treeTable'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table,
        treeTable = layui.treeTable;

    //列表
    var tableIns = table.render({
        elem: '#list',
        url: '/silos/cms/book/info/queryPage',
        method: 'POST',
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        headers: {token: ''},
        cellMinWidth: 95,
        page: true,
        height: "full-125",
        limits: [10, 15, 20, 25],
        limit: 15,
        id: "listTable",
        request: {
            pageName: "pageNo",//重新定义当前页码参数名称
            limitName: "pageRows"//重新定义每页大小参数名称
        },
        response: {
            statusName: 'code', //数据状态的字段名称，默认：code
            statusCode: 200, //成功的状态码，默认：0
            msgName: 'msg',  //状态信息的字段名称，默认：msg
            countName: 'totalRows',  //数据总数的字段名称，默认：count
            dataName: 'data' //数据列表的字段名称，默认：data
        },
        where: {
            //请求的参数写在where
        },
        parseData: function (res) {
            return {
                "code": res.code,
                "msg": res.msg, //解析提示文本
                "totalRows": res.data.totalRows, //解析数据长度
                "data": res.data.dataList, //解析数据列表
            };
        },
        cols: [[
            {type: "checkbox", fixed: "left", width: 50},
            {field: 'isbn', title: '国际标准书号', minWidth: 100, align: "center"},
            {field: 'title', title: '图书正题名', minWidth: 100, align: "center"},
            {field: 'subtitle', title: '副题名', minWidth: 100, align: "center"},
            {
                field: 'parentId', title: '父级分类', align: 'center', templet: function (d) {
                    if (d.parentId == "0") {
                        return "顶级分类";
                    } else if (d.parentId == "1") {
                        return "一级分类";
                    } else if (d.parentId == "2") {
                        return "二级分类";
                    } else {
                        return "三级分类";
                    }
                }
            },
            {field: 'author', title: '第一作者', minWidth: 100, align: "center"},
            {field: 'otherAuthors', title: '其他责任者', minWidth: 100, align: "center"},
            {field: 'publisher', title: '出版社', align: 'center'},

            {field: 'edition', title: '版次', minWidth: 100, align: "center"},
            /*{field: 'userAvatar', title: '用户头像', minWidth:100, align:"center",templet:function(d){
                    return "<img src='"+d.userAvatar+"' style='width: 30px;height: 30px'>";
            }},*/
            {field: 'categoryCode', title: '分类代码', minWidth: 100, align: "center"},
            {field: 'language', title: '正文语种', minWidth: 100, align: "center"},
            {field: 'coverImage', title: '封面图片路径', minWidth: 100, align: "center"},
            {
                field: 'createdAt', title: '创建时间', minWidth: 100, align: "center", templet: function (d) {
                    return showTime(d.createTime);
                }
            },
            {
                field: 'updatedAt', title: '修改时间', minWidth: 100, align: "center", templet: function (d) {
                    return showTime(d.updateTime);
                }
            },
            {title: '操作', minWidth: 200, templet: '#listBar', fixed: "right", align: "center", toolBar: '#listBar'}
        ]]
    });
    $(".search_btn").click(function () {
        const infoName = $("#search_value").val();
        renderCategoriesGrid();
        table.reload("listTable", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                infoName: infoName
            }
        })
    })

    $('.book-card').click(function (e) {
        layer.open({
            type: 2,
            title: title,
            shadeClose: true,
            shade: 0.8,
            area: ['100%', '100%'],
            content: '/silos/cms/book/chapter/chapter.html' // iframe 的 url
        })
    })

    $(".add_btn").click(function () {
        edit();
    })
    // 添加/修改
    function edit(edit) {
        let title = "添加图书";
        if (edit != null) {
            title = "添加图书";
        }
        const index = layui.layer.open({
            title: title,
            type: 2,
            content: "/silos/cms/book/info/edit.html",
            scrollbar: false,
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (edit) {
                    body.find(".uid").val(BigInt(edit.id).toString());
                    body.find(".userName").val(edit.userName);  //用户名
                    body.find(".loginName").val(edit.loginName);  //登录名
                    body.find(".userMobilePhone").val(edit.userMobilePhone);
                    body.find(".userNickName").val(edit.userNickName);
                    body.find(".userAddress").val(edit.userAddress);
                    body.find(".userEmail").val(edit.userEmail);  //邮箱
                    body.find(".userSex input[value=" + edit.userSex + "]").prop("checked", "checked");  //性别
                    body.find(".allowedNetworkType").val(edit.allowedNetworkType);
                    body.find(".userType").val(edit.userType);  //会员等级
                    body.find(".userStatus").val(edit.userStatus);    //用户状态
                    body.find(".userDescription").text(edit.userDescription);    //用户简介
                    body.find(".remark").text(edit.remark);
                    form.render();
                }
                setTimeout(function () {
                    layui.layer.tips('点击此处返回分类列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            }
        });
        layui.layer.full(index);
        window.sessionStorage.setItem("index", index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }
    //时间转换函数
    function showTime(tempDate) {
        var d = new Date(tempDate);
        var year = d.getFullYear();
        var month = d.getMonth();
        month++;
        var day = d.getDate();
        var hours = d.getHours();

        var minutes = d.getMinutes();
        var seconds = d.getSeconds();
        month = month < 10 ? "0" + month : month;
        day = day < 10 ? "0" + day : day;
        hours = hours < 10 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;


        var time = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        return time;
    }
    // 生成分类卡片（网格视图）
    function renderCategoriesGrid() {
        const booksGrid = document.getElementById('booksGrid');
        $.ajax({
            url: "/silos/cms/book/info/queryPage",
            type: "POST",
            dataType: "json",
            async: false,
            contentType: 'application/json;charset=UTF-8',
            data: JSON.stringify({
                pageNo:1,
                pageRows:100,
                infoName:$("#search_value").val()
            }),
            success: function (res) {
                const data = res.data.dataList;
                if (data.length === 0) {
                    booksGrid.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-book-open"></i>
                        <h3>暂无图书</h3>
                        <p>点击"添加图书"按钮开始建立您的图书馆</p>
                    </div>
                `;
                    return;
                }

                booksGrid.innerHTML = data.map(book => `
                <div class="book-card" bookid="${book.id}" bookTitle="${book.title}">
                    <div class="book-cover" style="background-color: ${book.coverColor}">
                        <span style="color: white; font-weight: bold; font-size: 1.5rem;">${book.title.substring(0, 2)}</span>
                    </div>
                    <div class="book-info">
                        <h3 class="book-title">${book.title}</h3>
                        <p class="book-author">${book.author}</p>
                        <div class="book-meta">
                            <span>${book.publisher}</span>
                            <span>${book.pages}页</span>
                        </div>
                        <span class="book-category">${book.category}</span>
                        <div class="book-actions">
                            <button class="action-btn edit-btn">
                                <i class="fas fa-edit"></i> 编辑
                            </button>
                            <button class="action-btn delete-btn">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </div>
                    </div>
                </div>
            `).join('');
            },
            error: function (e) {
                console.log(e);
            }
        })
    }

    // 自定义绑定事件方法
    function bind_event(dom, fn, type, child,) {
        if (typeof dom == 'object' && dom != 'undefined') {
            type = type == null ? "click" : type;
            if (child != "" && child != 'object') {
                return dom.on(type, child, fn);
            } else {
                return dom.on(type, fn);
            }
        }
    };
    // 刷新页面
    bind_event($(".search_refresh"), function () {
        window.location.reload();
    });
    $(function () {
        renderCategoriesGrid();
        //切换tab页的显示
        $(document).on('click', '.view-btn', function (e) {
            // 视图切换功能
            const viewButtons = document.querySelectorAll('.view-btn');
            viewButtons.forEach(btn => {
                btn.addEventListener('click', function() {
                    const viewType = this.getAttribute('data-view');

                    viewButtons.forEach(b => b.classList.remove('active'));
                    this.classList.add('active');

                    if (viewType === 'grid') {
                        document.getElementById('booksGrid').classList.add('active');
                        document.getElementById('booksTable').classList.remove('active');
                    } else {
                        document.getElementById('booksGrid').classList.remove('active');
                        document.getElementById('booksTable').classList.add('active');
                    }
                });
            });
        })
    });
})