// 页面加载完成后初始化
$(document).ready(function () {
    initCategory();
    getBookInfo();
    compactUpload();
});
function compactUpload(){
    // 初始化紧凑型上传插件
    $('#compactUpload').compactUpload({
        uploadId: 'filePaths',
        uploadApi: '/api/file/upload',
        allowedTypes: 'image/*,.pdf,.doc,.docx,.txt',
        maxSize: 100,
        blockedExtensions: ['exe', 'bat', 'cmd', 'sh', 'php', 'js', 'py'],
        onSuccess: function(response) {
            console.log('文件上传成功:', response);
            // 可以在这里处理上传成功后的逻辑，如更新页面其他部分
        },
        onError: function(error) {
            console.error('文件上传失败:', error);
        }
    });
}
layui.use(['form', 'layer'], function () {
    var form = layui.form
    layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;
    form.on("submit(save)", function (data) {
        //弹出loading
        const index = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.8});
        //实际使用时的提交信息
        $.ajax( {
            url : "/cms/book/info/save",
            type : "POST",
            dataType:"json",
            contentType:'application/json;charset=UTF-8',
            data:JSON.stringify({id:$("#bookInfoId").val(),
                isbn:$("#isbn").val(),
                title:$("#title").val(),
                subtitle: $("#subtitle").val(),
                author: $("#author").val(),
                otherAuthors: $("#otherAuthors").val(),
                publisher: $("#publisher").val(),
                publishDate: $("#publishDate").val(),
                edition: $("#edition").val(),
                categoryCode: $("#categoryCode").val(),
                language: $("#language").val(),
                coverImage: $("#coverImage").val(),
                summary: $("#summary").val(),
                toc: $("#toc").val(),
                price: $("#price").val(),
                pages: $("#pages").val(),
                dimensions: $("#dimensions").val(),
                binding: $("#binding").val(),
                series: $("#series").val(),
                source: $("#source").val(),
                filePaths: $("#filePaths").val()
            }),
            success : function(res) {
                console.log(res);
                layer.close(index);
                layer.msg(res.msg);
                layer.closeAll("iframe");
                //刷新父页面
                parent.location.reload();
            },
            error:function(e){
                layer.close(index);
                layer.msg("信息提交异常！");
                layer.closeAll("iframe");
                //刷新父页面
                parent.location.reload();
            }
        })
        return false;
    })
})
// 配置常量
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 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) {
                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('#categoryCode', staticData);
}
// 时间格式化
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 getBookInfo() {
    const bookInfoId = $("#bookInfoId").val();
    $.ajax({
        url: "/cms/book/info/info/" + bookInfoId,
        type: "GET",
        dataType: "json",
        contentType: 'application/json;charset=UTF-8',
        success: function (res) {
            if (res.code === 200) {
                const book = res.data;
                $("#isbn").val(book.isbn);
                $("#title").val(book.title);
                $("#subtitle").val(book.subtitle);
                $("#author").val(book.author);
                $("#otherAuthors").val(book.otherAuthors);
                $("#publisher").val(book.publisher);
                $("#publishDate").text(formatTime(book.publishDate));
                $("#edition").val(book.edition);
                $("#categoryCode option[value='"+book.categoryCode+"']").prop('selected', true);
                $("#language option[value='"+book.language+"']").prop('selected', true);
                $("#price").val(book.price);
                $("#dimensions").val(book.dimensions);
                $("#pages").val(book.pages);
                $("#binding").val(book.binding);
                $("#series").val(book.series);
                $("#source").val(book.source);
                $("#summary").val(book.summary);
                $("#toc").val(book.toc);

            }
        },
        error: function (xhr, status, error) {
            console.error("请求失败:", error);
        }
    });
}