layui.use(['form', 'layer'], function () {
    var form = layui.form
    layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;

    // 初始化TinyMCE
    tinymce.init({
        selector: '#contentText',
        license_key: 'gpl',
        height: 400,
        menubar: 'file edit view insert format tools table help',
        plugins: [
            'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
            'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
            'insertdatetime', 'media', 'table', 'code', 'help', 'wordcount'
        ],
        toolbar: 'undo redo | blocks | bold italic underline | ' +
            'alignleft aligncenter alignright alignjustify | ' +
            'bullist numlist outdent indent | link image | ' +
            'removeformat | code | help',
        content_style: 'body { font-family: "Microsoft YaHei", sans-serif; font-size: 14px }',
        language: 'zh_CN',
        // 字数统计回调
        setup: function (editor) {
            editor.on('keyup', function () {
                updateWordCount();
            });
            editor.on('change', function () {
                updateWordCount();
            });
        }
    });

    /**
     * 读取章节信息
     */
    function getContentInfo() {
        let id = $("#id").val();
        if (id !== "") {
            $.ajax({
                url: "/cms/book/contents/info/" + id,
                type: "GET",
                dataType: "json",
                contentType: 'application/json;charset=UTF-8',
                success: function (res) {
                    if (res.code === 200) {
                        const book = res.data;
                        let text = book.contentHtml;
                        if (book.contentHtml == null || book.contentHtml === "") {
                            text = book.contentText;
                        }
                        /*tinyMCE.activeEditor.setContent(text);*/

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

    $(document).ready(function () {
        getContentInfo();
    });

    // 更新字数统计
    function updateWordCount() {
        const content = tinymce.activeEditor.getContent({format: 'text'});
        const wordCount = content.length;
        document.getElementById('wordCount').value = wordCount;
        document.getElementById('wordCountDisplay').textContent = `${wordCount} 字`;
    }

    form.on("submit(save)", function (data) {
        //弹出loading
        const index = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.8});
        const contentHtml = tinymce.get('contentText').getContent();
        const contentText = tinymce.activeEditor.getContent({format: 'text'});
        //实际使用时的提交信息
        $.ajax({
            url: "/cms/book/contents/save",
            type: "POST",
            dataType: "json",
            contentType: 'application/json;charset=UTF-8',
            data: JSON.stringify({
                id: $("#id").val(),
                bookInfoId: $("#bookInfoId").val(),
                chapterLevel: $("#chapterLevel").val(),
                chapterNumber: $("#chapterNumber").val(),
                chapterTitle: $("#chapterTitle").val(),
                contentType: $("#contentType").val(),
                wordCount: $("#wordCount").val(),
                isPublic: $("#isPublic").val(),
                version: $("#version").val(),
                parentId: $("#parentId").val(),
                contentText: contentText,
                contentHtml: contentHtml,
            }),
            success: function (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;
    })


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