layui.config({
    base: '/assets/lib/jplus/treeTable/'
}).use(['form', 'layer', 'table', 'laytpl', 'treeTable'], function () {
    'use strict';

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table,
        treeTable = layui.treeTable;

    // 常量定义
    var CONSTANTS = {
        TABLE_ID: 'listTable',
        SEARCH_INPUT_ID: '#searchInput',
        PAGE_SIZE: 15,
        PAGE_SIZES: [10, 15, 20, 25],
        SUCCESS_CODE: 200
    };

    // 缓存DOM元素
    var $searchInput = $(CONSTANTS.SEARCH_INPUT_ID);

    // 工具函数：时间格式化
    function formatTime(timestamp) {
        if (!timestamp) return '';

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

        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}`;
    }

    // 工具函数：防抖搜索
    var debounceSearch = (function() {
        var timer;
        return function(callback, delay) {
            clearTimeout(timer);
            timer = setTimeout(callback, delay || 300);
        };
    })();

    // 表格配置
    var tableConfig = {
        elem: '#list',
        url: '/cms/book/contents/queryPage',
        method: 'POST',
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        headers: { token: '' },
        cellMinWidth: 90,
        page: true,
        height: "full-125",
        limits: CONSTANTS.PAGE_SIZES,
        limit: CONSTANTS.PAGE_SIZE,
        id: CONSTANTS.TABLE_ID,
        request: {
            pageName: "pageNo",
            limitName: "pageRows"
        },
        response: {
            statusName: 'code',
            statusCode: CONSTANTS.SUCCESS_CODE,
            msgName: 'msg',
            countName: 'totalRows',
            dataName: 'data'
        },
        parseData: function (res) {
            // 统一错误处理
            if (res.code !== CONSTANTS.SUCCESS_CODE) {
                layer.msg(res.msg || '请求失败');
                return {
                    code: res.code,
                    msg: res.msg,
                    totalRows: 0,
                    data: []
                };
            }

            return {
                code: res.code,
                msg: res.msg,
                totalRows: res.data.totalRows || 0,
                data: res.data.dataList || []
            };
        },
        cols: [[
            {type: "checkbox", fixed: "left", width: 50},
            {field: 'bookInfoId', title: '关联图书', minWidth: 100, align: "center"},
            {field: 'chapterLevel', title: '章节层级', minWidth: 100, align: "center"},
            {field: 'chapterNumber', title: '章节编号', minWidth: 100, align: "center"},
            {field: 'chapterTitle', title: '章节标题', minWidth: 100, align: "center"},
            {field: 'contentType', title: '内容类型', minWidth: 100, align: "center"},
            {field: 'wordCount', title: '字数统计', align: 'center'},
            {field: 'isPublic', title: '是否公开', minWidth: 100, align: "center"},
            {field: 'version', title: '内容版本', minWidth: 100, align: "center"},
            {field: 'parentId', title: '父级章节', minWidth: 100, align: "center"},
            {field: 'coverImage', title: '封面图片路径', minWidth: 100, align: "center"},
            {
                field: 'createTime',
                title: '创建时间',
                minWidth: 100,
                align: "center",
                templet: function (d) {
                    return formatTime(d.createTime);
                }
            },
            {
                field: 'updateTime',
                title: '修改时间',
                minWidth: 100,
                align: "center",
                templet: function (d) {
                    return formatTime(d.updateTime);
                }
            },
            {
                title: '操作',
                minWidth: 200,
                templet: '#listBar',
                fixed: "right",
                align: "center",
                toolBar: '#listBar'
            }
        ]],
        done: function(res, curr, count) {
            // 表格渲染完成后的回调，可以用于后续操作
            console.log('表格渲染完成', count);
        },
        error: function(res, msg) {
            // 错误处理
            layer.msg(msg || '数据加载失败');
        }
    };

    // 初始化表格
    var tableIns = table.render(tableConfig);

    // 搜索功能
    function performSearch() {
        var searchParams = {
            contentsName: $searchInput.val().trim(),
            contentType: $("#contentType").val(),
            isPublic: $("#isPublic").val(),
            version: $("#version").val(),
            createBeginTime: $("#createTime").val(),
            bookInfoId: $('#bookInfoId').val()
        };

        // 清空空值参数
        Object.keys(searchParams).forEach(function(key) {
            if (!searchParams[key]) {
                delete searchParams[key];
            }
        });

        table.reload(CONSTANTS.TABLE_ID, {
            page: { curr: 1 },
            where: searchParams
        });
    }

    // 事件绑定
    function bindEvents() {
        // 搜索按钮点击
        $(".search_btn").on('click', performSearch);

        // 输入框回车搜索
        $searchInput.on('keypress', function(e) {
            if (e.which === 13) {
                performSearch();
            }
        });

        // 添加按钮点击
        $(".add_btn").on('click', function() {
            editContent();
        });

        // 可选：输入框实时搜索（防抖）
        $searchInput.on('input', function() {
            debounceSearch(performSearch, 500);
        });
    }

    // 编辑/添加内容
    function editContent(editData) {
        var title = editData ? "修改章节" : "添加章节";
        var index = layui.layer.open({
            title: title,
            type: 2,
            content: "/cms/book/contents/edit.html",
            scrollbar: false,
            area: ['100%', '100%'],
            success: function(layero, index) {
                if (editData) {
                    setEditFormData(index, editData);
                }
            },
            end: function() {
                // 弹窗关闭后的清理操作
                window.sessionStorage.removeItem("index");
            }
        });

        // 存储弹窗索引
        window.sessionStorage.setItem("index", index);

        // 窗口resize事件处理（使用事件委托）
        $(window).off('resize.layer-resize').on('resize.layer-resize', function() {
            var savedIndex = window.sessionStorage.getItem("index");
            if (savedIndex) {
                layer.full(parseInt(savedIndex));
            }
        });
    }

    // 设置编辑表单数据
    function setEditFormData(index, data) {
        try {
            var body = layui.layer.getChildFrame('body', index);
            /*body.find('#id').val(data.id);
            body.find('#chapterNumber').val(data.chapterNumber);
            body.find('#chapterLevel input[value="${data.chapterLevel}"]').prop('checked', true);
            body.find('#chapterTitle').val(data.chapterTitle);
            body.find('#contentType input[value="${data.contentType}"]').prop('checked', true);
            body.find('#wordCount').val(data.wordCount);
            body.find('#version').val(data.version);
            body.find('#contentText').val(data.contentText);
            body.find('#isPublic input[value="${data.isPublic}"]').prop('checked', true);*/

            var formFields = {
                '#id': data.id ? BigInt(data.id).toString() : '',
                '#chapterLevel': data.chapterLevel || '',
                '#chapterNumber': data.chapterNumber || '',
                '#chapterTitle': data.chapterTitle || '',
                '#contentType': data.contentType || '',
                '#wordCount': data.wordCount || '',
                '#version': data.version || '',
                '#contentText': data.contentText || '',
                '#isPublic': data.isPublic || ''
            };

            // 设置表单字段
            Object.keys(formFields).forEach(function(selector) {
                var element = body.find(selector);
                if (element.length) {
                    element.val(formFields[selector]);
                }
            });

            // 设置单选按钮
            if (data.isPublic) {
                body.find('#isPublic input[value="' + data.isPublic + '"]').prop('checked', true);
            }

            // 渲染表单
            form.render();

        } catch (error) {
            console.error('设置表单数据失败:', error);
            layer.msg('表单数据加载失败');
        }
    }

    // 初始化
    function init() {
        bindEvents();

        // 初始化表单
        form.render();

        // 可选：监听表格事件
        table.on('tool(list)', function(obj) {
            var event = obj.event;
            var data = obj.data;

            switch(event) {
                case 'edit':
                    editContent(data);
                    break;
                case 'del':
                    deleteContent(data);
                    break;
            }
        });
    }

    // 删除内容（示例）
    function deleteContent(data) {
        layer.confirm('确定要删除此章节吗？', {
            icon: 3,
            title: '提示'
        }, function(index) {
            layer.close(index);
            // 这里添加删除API调用
            // ...
            layer.msg('删除成功');
            table.reload(CONSTANTS.TABLE_ID);
        });
    }

    // 初始化POST方式下拉框
    function initPostDropdown() {
        // POST 请求示例
        $('.smart-dropdown').smartDropdown({
            url: '/cms/book/info/queryPage',
            method: 'POST',
            hiddenId: 'bookInfoId',
            valueField: 'isbn',
            textField: 'title',
            pageSize: 5,
            params: {
                pageNo: 1,
                pageRows: 5,
                status: 1,
                category: 'user'
            },
            onSelect: function (item) {
                console.log('选中:', item);
            }
        });
    }

    // 页面加载完成后初始化
    $(document).ready(function() {
        init();
        initPostDropdown();
    });
});