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;
    // 缓存DOM元素
    const domCache = {
        booksGrid: $('#booksGrid'),
        searchInput: $('#search_value'),
        searchBtn: $('.search_btn'),
        addBtn: $('.add_btn'),
        refreshBtn: $('.search_refresh'),
        categoryCode: $('#book_category')
    };

    // 配置常量
    const CONFIG = {
        table: {
            elem: '#list',
            url: '/cms/book/info/queryPage',
            method: 'POST',
            contentType: 'application/json;charset=utf-8',
            page: true,
            limits: [10, 15, 20, 25],
            limit: 15,
            id: "listTable",
            request: {
                pageName: "pageNo",
                limitName: "pageRows"
            },
            response: {
                statusName: 'code',
                statusCode: 200,
                msgName: 'msg',
                countName: 'totalRows',
                dataName: 'data'
            }
        },
        grid: {
            pageNo: 1,
            pageRows: 100
        }
    };

    // 修改图书
    function updateBook(bookData) {
        var title = bookData ? "编辑图书" : "添加图书";
        var index = layui.layer.open({
            title: title,
            type: 2,
            content: "/cms/book/info/update.html/"+bookData.id,
            area: ['100%', '100%'],
            maxmin: true,
            success: function (layero, index) {

            }
        });
    }

    // 添加/编辑图书
    function editBook(bookData) {
        var title = bookData ? "编辑图书" : "添加图书";
        var index = layui.layer.open({
            title: title,
            type: 2,
            content: "/cms/book/info/edit.html",
            area: ['100%', '100%'],
            maxmin: true,
            success: function (layero, index) {
                if (bookData) {
                    var body = layer.getChildFrame('body', index);
                    // 填充图书数据
                    Object.keys(bookData).forEach(function (key) {
                        var input = body.find('.' + key);
                        if (input.length) {
                            if (input.is(':radio')) {
                                input.filter('[value="' + bookData[key] + '"]').prop('checked', true);
                            } else {
                                input.val(bookData[key]);
                            }
                        }
                    });
                    form.render();
                }
            }
        });
    }

    // 渲染图书网格视图
    function renderBooksGrid(infoName, categoryCode) {
        var requestData = $.extend({}, CONFIG.grid, {
            infoName: infoName,
            categoryCode: categoryCode
        });

        $.ajax({
            url: "/cms/book/info/queryPage",
            type: "POST",
            dataType: "json",
            contentType: 'application/json;charset=UTF-8',
            data: JSON.stringify(requestData),
            success: function (res) {
                if (res.code === 200) {
                    $(".books-count").html("找到 " + res.data.totalRows + " 本图书")
                    renderGridItems(res.data.dataList);
                } else {
                    showError("加载失败", res.msg);
                }
            },
            error: function (xhr, status, error) {
                console.error("请求失败:", error);
                showError("请求失败", "网络错误或服务器异常");
            }
        });
    }

    // 渲染网格项目
    function renderGridItems(books) {
        if (!books || books.length === 0) {
            domCache.booksGrid.html(`
                <div class="empty-state">
                    <i class="fas fa-book-open"></i>
                    <h3>暂无图书</h3>
                    <p>点击"添加图书"按钮开始建立您的图书馆</p>
                </div>
            `);
            return;
        }

        var html = books.map(function (book) {
            var coverColor = book.coverColor || getRandomHexColor();
            var initials = book.title ? book.title.substring(0, 2) : '??';

            return `
                <div class="book-card" data-id="${book.id}" data-isbn="${book.isbn}" data-title="${book.title || ''}">
                    <div class="book-cover" style="background-color: ${coverColor}">
                        <span style="color: white; font-weight: bold; font-size: 1.5rem;">${initials}</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 || 0}页</span>
                        </div>
                        <span class="book-category">${getCategory(book.categoryCode) || '未分类'}</span>
                        <div class="book-actions">
                            <button class="action-btn edit-btn" data-action="edit">
                                <i class="fas fa-edit"></i> 编辑
                            </button>
                            <button class="action-btn delete-btn" data-action="delete">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </div>
                    </div>
                </div>
            `;
        }).join('');

        domCache.booksGrid.html(html);
    }
    //分类缓存
    let category = [];
    function getCategory(code) {
        let categoryName = "";
        category.forEach(obj => {
            if (obj.categoryCode === code) {
                categoryName = obj.categoryName;
            }
        });
        return categoryName;
    }

    //初始化分类
    function initCategory() {
        var requestData = $.extend({}, CONFIG.grid);
        $.ajax({
            url: "/cms/book/categories/queryPage",
            type: "POST",
            dataType: "json",
            contentType: 'application/json;charset=UTF-8',
            data: JSON.stringify(requestData),
            success: function (res) {
                if (res.code === 200) {
                    category = res.data.dataList;
                    setCategory(res.data.dataList);
                } else {
                    showError("加载失败", res.msg);
                }
            },
            error: function (xhr, status, error) {
                console.error("请求失败:", error);
                showError("请求失败", "网络错误或服务器异常");
            }
        });
    }

    function setCategory(categories) {
        if (!categories || categories.length === 0) {
            return;
        }
        const staticData = [];
        categories.forEach(category => {
            staticData.push({value: category.categoryCode, text: category.categoryName}); // 使用id作为键，整个对象作为值
        });
        // 创建渲染器实例
        var selectRenderer = new SelectRenderer({
            placeholderText: '请选择',
            valueField: 'id',
            textField: 'name'
        });
        // 渲染单个select
        selectRenderer.render('#book_category', staticData);
    }

    // 初始化表格
    function initTable() {
        table.render($.extend(true, {}, CONFIG.table, {
            elem: '#list',
            dataType: 'json',
            headers: {token: ''},
            id: "listTable",
            cellMinWidth: 95,
            height: "full-125",
            parseData: parseTableData,
            cols: getTableColumns()
        }));
    }

    // 解析表格数据
    function parseTableData(res) {
        return {
            "code": res.code,
            "msg": res.msg,
            "totalRows": res.data.totalRows,
            "data": res.data.dataList
        };
    }

    // 获取表格列配置
    function getTableColumns() {
        return [[
            {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) {
                    return getParentCategoryName(d.parentId);
                }
            },
            {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: '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 formatTime(d.createTime);
                }
            },
            {
                field: 'updatedAt', title: '修改时间', minWidth: 100, align: "center", templet: function (d) {
                    return formatTime(d.updateTime);
                }
            },
            {title: '操作', minWidth: 200, templet: '#listBar', fixed: "right", align: "center"}
        ]];
    }

    // 获取父级分类名称
    function getParentCategoryName(parentId) {
        var categoryMap = {
            "0": "顶级分类",
            "1": "一级分类",
            "2": "二级分类"
        };
        return categoryMap[parentId] || "三级分类";
    }

    // 搜索功能
    function searchBooks() {
        const infoName = domCache.searchInput.val().trim();
        const categoryCode = domCache.categoryCode.val().trim();
        // 同时更新表格和网格视图
        reloadTable(infoName, categoryCode);
        renderBooksGrid(infoName, categoryCode);
    }

    // 重新加载表格
    function reloadTable(infoName, categoryCode) {
        table.reload("listTable", {
            page: {curr: 1},
            where: {
                infoName: infoName,
                categoryCode: categoryCode
            }
        });
    }

    // 打开章节页面
    function openChapterPage(bookId, bookTitle) {
        //如果写成layer.open，将会在所有页面最上层 而不是当前iframe展开
        layui.layer.open({
            type: 2,
            title: bookTitle ? bookTitle + ' - 章节管理' : '章节管理',
            shadeClose: true,
            shade: 0.8,
            area: ['100%', '100%'],
            content: '/cms/book/chapter/chapter.html/' + bookId
        });
    }

    function getRandomHexColor() {
        // 生成 #000000 到 #ffffff 之间的随机颜色
        return '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
    }

    // 获取随机颜色
    function getRandomColor() {
        var colors = ['#3498db', '#2ecc71', '#e74c3c', '#f39c12', '#9b59b6'];
        return colors[Math.floor(Math.random() * colors.length)];
    }

    // 显示错误信息
    function showError(title, msg) {
        layer.msg(msg || '操作失败', {icon: 2});
    }

    // 时间格式化
    function formatTime(timestamp) {
        if (!timestamp) return '';

        var date = new Date(timestamp);
        if (isNaN(date.getTime())) return timestamp;

        var year = date.getFullYear();
        var month = (date.getMonth() + 1).toString().padStart(2, '0');
        var day = date.getDate().toString().padStart(2, '0');
        var hours = date.getHours().toString().padStart(2, '0');
        var minutes = date.getMinutes().toString().padStart(2, '0');
        var seconds = date.getSeconds().toString().padStart(2, '0');

        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    }

    // 视图切换功能
    function initViewToggle() {
        $(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');
                    }
                });
            });
        });
    }

    // 网格视图事件委托
    function initGridEvents() {
        domCache.booksGrid.on('click', function (e) {
            var target = $(e.target);
            var bookCard = target.closest('.book-card');

            if (!bookCard.length) return;

            var bookId = bookCard.data('id');
            var bookTitle = bookCard.data('title');
            var bookIsbn = bookCard.data('isbn');

            // 卡片点击（非按钮区域）
            if (!target.closest('.book-actions').length) {
                openChapterPage(bookIsbn, bookTitle);
                return;
            }

            // 按钮点击
            var actionBtn = target.closest('.action-btn');
            if (!actionBtn.length) return;

            var action = actionBtn.data('action');

            switch (action) {
                case 'edit':
                    updateBook({id: bookId, title: bookTitle});
                    break;
                case 'delete':
                    layer.confirm('确定删除这本图书吗？', {
                        title: '删除确认',
                        btn: ['确定', '取消']
                    }, function (index) {
                        // 这里添加删除逻辑
                        layer.close(index);
                    });
                    break;
            }
        });
    }

    // 表格操作事件监听
    function initTableEvents() {
        table.on('tool(listTable)', function (obj) {
            var data = obj.data;
            var event = obj.event;

            switch (event) {
                case 'edit':
                    editBook(data);
                    break;
                case 'delete':
                    layer.confirm('确定删除这本图书吗？', {
                        title: '删除确认',
                        btn: ['确定', '取消']
                    }, function (index) {
                        // 这里添加删除逻辑
                        layer.close(index);
                    });
                    break;
            }
        });
    }


    // 初始化事件绑定
    function initEvents() {
        // 搜索按钮
        domCache.searchBtn.on('click', searchBooks);

        // 回车搜索
        domCache.searchInput.on('keypress', function (e) {
            if (e.keyCode === 13) {
                searchBooks();
            }
        });

        // 添加按钮
        domCache.addBtn.on('click', function () {
            editBook();
        });

        // 刷新按钮
        domCache.refreshBtn.on('click', function () {
            location.reload();
        });
    }

    // 初始化
    function init() {
        initCategory();
        initEvents();
        initViewToggle();
        initGridEvents();
        initTableEvents();
        // 初始加载数据
        renderBooksGrid('', '');
        initTable();
    }

    // 启动初始化
    init();
});