routerAdd('GET', '/manage/document-manage', function (e) {
    const html = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>文档管理</title>
    <script>
        (function () {
            var token = localStorage.getItem('pb_manage_token') || ''
            var isLoggedIn = localStorage.getItem('pb_manage_logged_in') === '1'
            if (!token || !isLoggedIn) {
                window.location.replace('/pb/manage/login')
            }
        })()
    </script>
    <style>
        * { box-sizing: border-box; }
        body { margin: 0; font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; background: linear-gradient(180deg, #eef6ff 0%, #f8fafc 100%); color: #1f2937; }
        .container { max-width: 1280px; margin: 0 auto; padding: 32px 20px 64px; }
        .panel { background: rgba(255,255,255,0.96); border: 1px solid #e5e7eb; box-shadow: 0 18px 50px rgba(15, 23, 42, 0.08); border-radius: 24px; padding: 24px; }
        .panel + .panel { margin-top: 24px; }
        h1, h2 { margin-top: 0; }
        p { color: #4b5563; line-height: 1.7; }
        .actions, .form-actions { display: flex; flex-wrap: wrap; gap: 12px; }
        .btn { border: none; border-radius: 12px; padding: 10px 16px; font-weight: 600; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; }
        .btn-primary { background: #2563eb; color: #fff; }
        .btn-light { background: #f8fafc; color: #334155; border: 1px solid #dbe3f0; }
        .btn-danger { background: #dc2626; color: #fff; }
        .status { margin-top: 14px; min-height: 24px; font-size: 14px; }
        .status.success { color: #15803d; }
        .status.error { color: #b91c1c; }
        .grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
        .full { grid-column: 1 / -1; }
        label { display: block; margin-bottom: 8px; color: #334155; font-weight: 600; }
        input, textarea { width: 100%; border: 1px solid #cbd5e1; border-radius: 12px; padding: 10px 12px; font-size: 14px; background: #fff; }
        textarea { min-height: 96px; resize: vertical; }
        .hint { color: #64748b; font-size: 12px; margin-top: 6px; }
        table { width: 100%; border-collapse: collapse; }
        thead { background: #eff6ff; }
        th, td { padding: 14px 12px; border-bottom: 1px solid #e5e7eb; text-align: left; vertical-align: top; }
        th { font-size: 13px; color: #475569; }
        tr:hover td { background: #f8fafc; }
        .empty { text-align: center; padding: 24px 16px; color: #64748b; }
        .muted { color: #64748b; font-size: 12px; }
        .doc-links a { display: inline-block; margin-right: 10px; color: #2563eb; text-decoration: none; font-weight: 600; }
        @media (max-width: 960px) {
            .grid { grid-template-columns: 1fr; }
            table, thead, tbody, th, td, tr { display: block; }
            thead { display: none; }
            tr { margin-bottom: 14px; border: 1px solid #e5e7eb; border-radius: 16px; overflow: hidden; }
            td { display: flex; justify-content: space-between; gap: 12px; }
            td::before { content: attr(data-label); font-weight: 700; color: #475569; }
        }
    </style>
</head>
<body>
    <div class="container">
        <section class="panel">
            <h1>文档管理</h1>
            <p>页面会先把文件上传到 <code>tbl_attachments</code>，然后把返回的 <code>attachments_id</code> 写入 <code>tbl_document.document_image</code> 或 <code>document_video</code>。文档列表会直接显示 PocketBase 文件流链接。</p>
            <div class="actions">
                <a class="btn btn-light" href="/pb/manage">返回主页</a>
                <a class="btn btn-light" href="/pb/manage/login">登录页</a>
                <button class="btn btn-light" id="reloadBtn" type="button">刷新列表</button>
                <button class="btn btn-danger" id="logoutBtn" type="button">退出登录</button>
            </div>
            <div class="status" id="status"></div>
        </section>

        <section class="panel">
            <h2>新增文档</h2>
            <div class="grid">
                <div>
                    <label for="documentTitle">文档标题</label>
                    <input id="documentTitle" placeholder="请输入文档标题" />
                </div>
                <div>
                    <label for="documentType">文档类型</label>
                    <input id="documentType" placeholder="例如：说明书、新闻、常见故障" />
                </div>
                <div>
                    <label for="documentStatus">文档状态</label>
                    <input id="documentStatus" placeholder="默认 active" value="active" />
                </div>
                <div>
                    <label for="embeddingStatus">嵌入状态</label>
                    <input id="embeddingStatus" placeholder="默认 pending" value="pending" />
                </div>
                <div>
                    <label for="effectDate">生效日期</label>
                    <input id="effectDate" type="date" />
                </div>
                <div>
                    <label for="expiryDate">到期日期</label>
                    <input id="expiryDate" type="date" />
                </div>
                <div class="full">
                    <label for="documentSubtitle">副标题</label>
                    <input id="documentSubtitle" placeholder="可选" />
                </div>
                <div class="full">
                    <label for="documentSummary">摘要</label>
                    <textarea id="documentSummary" placeholder="请输入文档摘要"></textarea>
                </div>
                <div class="full">
                    <label for="documentContent">正文内容</label>
                    <textarea id="documentContent" placeholder="支持 Markdown 原文"></textarea>
                </div>
                <div>
                    <label for="relationModel">关联机型</label>
                    <input id="relationModel" placeholder="可选" />
                </div>
                <div>
                    <label for="vectorVersion">向量版本</label>
                    <input id="vectorVersion" placeholder="可选" />
                </div>
                <div>
                    <label for="documentKeywords">关键词</label>
                    <input id="documentKeywords" placeholder="多个值用 | 分隔" />
                    <div class="hint">例如：安装|配置|排障</div>
                </div>
                <div>
                    <label for="productCategories">适用产品类别</label>
                    <input id="productCategories" placeholder="多个值用 | 分隔" />
                </div>
                <div>
                    <label for="applicationScenarios">适用场景</label>
                    <input id="applicationScenarios" placeholder="多个值用 | 分隔" />
                </div>
                <div>
                    <label for="hotelType">适用酒店类型</label>
                    <input id="hotelType" placeholder="多个值用 | 分隔" />
                </div>
                <div class="full">
                    <label for="documentRemark">备注</label>
                    <textarea id="documentRemark" placeholder="可选"></textarea>
                </div>
                <div>
                    <label for="imageFile">图片附件</label>
                    <input id="imageFile" type="file" />
                </div>
                <div>
                    <label for="videoFile">视频附件</label>
                    <input id="videoFile" type="file" />
                </div>
            </div>
            <div class="form-actions" style="margin-top:16px;">
                <button class="btn btn-primary" id="submitBtn" type="button">上传附件并创建文档</button>
                <button class="btn btn-light" id="resetBtn" type="button">重置表单</button>
            </div>
        </section>

        <section class="panel">
            <h2>文档列表</h2>
            <div style="overflow:auto;">
                <table>
                    <thead>
                        <tr>
                            <th>document_id</th>
                            <th>标题</th>
                            <th>类型/状态</th>
                            <th>附件链接</th>
                            <th>更新时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <tr><td colspan="6" class="empty">暂无数据，请先刷新列表。</td></tr>
                    </tbody>
                </table>
            </div>
        </section>
    </div>

    <script>
        const tokenKey = 'pb_manage_token'
        const statusEl = document.getElementById('status')
        const tableBody = document.getElementById('tableBody')
        const fields = {
            documentTitle: document.getElementById('documentTitle'),
            documentType: document.getElementById('documentType'),
            documentStatus: document.getElementById('documentStatus'),
            embeddingStatus: document.getElementById('embeddingStatus'),
            effectDate: document.getElementById('effectDate'),
            expiryDate: document.getElementById('expiryDate'),
            documentSubtitle: document.getElementById('documentSubtitle'),
            documentSummary: document.getElementById('documentSummary'),
            documentContent: document.getElementById('documentContent'),
            relationModel: document.getElementById('relationModel'),
            vectorVersion: document.getElementById('vectorVersion'),
            documentKeywords: document.getElementById('documentKeywords'),
            productCategories: document.getElementById('productCategories'),
            applicationScenarios: document.getElementById('applicationScenarios'),
            hotelType: document.getElementById('hotelType'),
            documentRemark: document.getElementById('documentRemark'),
            imageFile: document.getElementById('imageFile'),
            videoFile: document.getElementById('videoFile'),
        }
        const state = { list: [] }

        function setStatus(message, type) {
            statusEl.textContent = message || ''
            statusEl.className = 'status' + (type ? ' ' + type : '')
        }

        function getToken() {
            return localStorage.getItem(tokenKey) || ''
        }

        async function requestJson(url, payload) {
            const token = getToken()
            if (!token) {
                window.location.replace('/pb/manage/login')
                throw new Error('登录状态已失效，请重新登录')
            }

            const res = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: 'Bearer ' + token,
                },
                body: JSON.stringify(payload || {}),
            })

            const data = await res.json()
            if (!res.ok || !data || data.code >= 400) {
                if (res.status === 401 || res.status === 403 || data.code === 401 || data.code === 403) {
                    localStorage.removeItem('pb_manage_token')
                    localStorage.removeItem('pb_manage_logged_in')
                    window.location.replace('/pb/manage/login')
                }
                throw new Error((data && data.msg) || '请求失败')
            }

            return data.data
        }

        async function uploadAttachment(file, label) {
            const token = getToken()
            const form = new FormData()
            form.append('attachments_link', file)
            form.append('attachments_filename', file.name || '')
            form.append('attachments_filetype', file.type || '')
            form.append('attachments_size', String(file.size || 0))
            form.append('attachments_status', 'active')
            form.append('attachments_remark', 'document-manage:' + label)

            const res = await fetch('/api/attachment/upload', {
                method: 'POST',
                headers: {
                    Authorization: 'Bearer ' + token,
                },
                body: form,
            })

            const data = await res.json()
            if (!res.ok || !data || data.code >= 400) {
                throw new Error((data && data.msg) || ('上传' + label + '失败'))
            }

            return data.data
        }

        function escapeHtml(value) {
            return String(value || '')
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;')
        }

        function renderLinks(item) {
            const links = []
            if (item.document_image_url) {
                links.push('<a href="' + escapeHtml(item.document_image_url) + '" target="_blank" rel="noreferrer">图片流</a>')
            }
            if (item.document_video_url) {
                links.push('<a href="' + escapeHtml(item.document_video_url) + '" target="_blank" rel="noreferrer">视频流</a>')
            }
            if (!links.length) {
                return '<span class="muted">无</span>'
            }
            return '<div class="doc-links">' + links.join('') + '</div>'
        }

        function renderTable() {
            if (!state.list.length) {
                tableBody.innerHTML = '<tr><td colspan="6" class="empty">暂无文档数据。</td></tr>'
                return
            }

            tableBody.innerHTML = state.list.map(function (item) {
                return '<tr>'
                    + '<td data-label="document_id"><div>' + escapeHtml(item.document_id) + '</div><div class="muted">owner: ' + escapeHtml(item.document_owner) + '</div></td>'
                    + '<td data-label="标题"><div><strong>' + escapeHtml(item.document_title) + '</strong></div><div class="muted">' + escapeHtml(item.document_subtitle) + '</div></td>'
                    + '<td data-label="类型/状态"><div>' + escapeHtml(item.document_type) + '</div><div class="muted">' + escapeHtml(item.document_status) + ' / ' + escapeHtml(item.document_embedding_status) + '</div></td>'
                    + '<td data-label="附件链接">' + renderLinks(item) + '</td>'
                    + '<td data-label="更新时间"><span class="muted">' + escapeHtml(item.updated) + '</span></td>'
                    + '<td data-label="操作"><button class="btn btn-danger" type="button" onclick="window.__deleteDocument(\\'' + encodeURIComponent(item.document_id) + '\\')">删除</button></td>'
                    + '</tr>'
            }).join('')
        }

        async function loadDocuments() {
            setStatus('正在加载文档列表...', '')
            try {
                const data = await requestJson('/api/document/list', {})
                state.list = data.items || []
                renderTable()
                setStatus('文档列表已刷新，共 ' + state.list.length + ' 条。', 'success')
            } catch (err) {
                setStatus(err.message || '加载列表失败', 'error')
            }
        }

        function resetForm() {
            fields.documentTitle.value = ''
            fields.documentType.value = ''
            fields.documentStatus.value = 'active'
            fields.embeddingStatus.value = 'pending'
            fields.effectDate.value = ''
            fields.expiryDate.value = ''
            fields.documentSubtitle.value = ''
            fields.documentSummary.value = ''
            fields.documentContent.value = ''
            fields.relationModel.value = ''
            fields.vectorVersion.value = ''
            fields.documentKeywords.value = ''
            fields.productCategories.value = ''
            fields.applicationScenarios.value = ''
            fields.hotelType.value = ''
            fields.documentRemark.value = ''
            fields.imageFile.value = ''
            fields.videoFile.value = ''
        }

        async function submitDocument() {
            if (!fields.documentTitle.value.trim()) {
                setStatus('请先填写文档标题。', 'error')
                return
            }

            setStatus('正在上传附件并创建文档...', '')

            try {
                let imageAttachment = null
                let videoAttachment = null
                const imageFile = fields.imageFile.files && fields.imageFile.files[0]
                const videoFile = fields.videoFile.files && fields.videoFile.files[0]

                if (imageFile) {
                    imageAttachment = await uploadAttachment(imageFile, 'image')
                }

                if (videoFile) {
                    videoAttachment = await uploadAttachment(videoFile, 'video')
                }

                await requestJson('/api/document/create', {
                    document_title: fields.documentTitle.value.trim(),
                    document_type: fields.documentType.value.trim(),
                    document_status: fields.documentStatus.value.trim(),
                    document_embedding_status: fields.embeddingStatus.value.trim(),
                    document_effect_date: fields.effectDate.value,
                    document_expiry_date: fields.expiryDate.value,
                    document_subtitle: fields.documentSubtitle.value.trim(),
                    document_summary: fields.documentSummary.value.trim(),
                    document_content: fields.documentContent.value.trim(),
                    document_image: imageAttachment ? imageAttachment.attachments_id : '',
                    document_video: videoAttachment ? videoAttachment.attachments_id : '',
                    document_relation_model: fields.relationModel.value.trim(),
                    document_keywords: fields.documentKeywords.value.trim(),
                    document_vector_version: fields.vectorVersion.value.trim(),
                    document_product_categories: fields.productCategories.value.trim(),
                    document_application_scenarios: fields.applicationScenarios.value.trim(),
                    document_hotel_type: fields.hotelType.value.trim(),
                    document_remark: fields.documentRemark.value.trim(),
                })

                resetForm()
                await loadDocuments()
                setStatus('文档创建成功。', 'success')
            } catch (err) {
                setStatus(err.message || '创建文档失败', 'error')
            }
        }

        async function deleteDocument(documentId) {
            const target = decodeURIComponent(documentId)
            if (!window.confirm('确认删除文档「' + target + '」吗？')) {
                return
            }

            setStatus('正在删除文档...', '')
            try {
                await requestJson('/api/document/delete', { document_id: target })
                await loadDocuments()
                setStatus('文档删除成功。', 'success')
            } catch (err) {
                setStatus(err.message || '删除文档失败', 'error')
            }
        }

        window.__deleteDocument = deleteDocument

        document.getElementById('reloadBtn').addEventListener('click', loadDocuments)
        document.getElementById('submitBtn').addEventListener('click', submitDocument)
        document.getElementById('resetBtn').addEventListener('click', function () {
            resetForm()
            setStatus('表单已重置。', 'success')
        })
        document.getElementById('logoutBtn').addEventListener('click', function () {
            localStorage.removeItem('pb_manage_token')
            localStorage.removeItem('pb_manage_logged_in')
            localStorage.removeItem('pb_manage_login_account')
            localStorage.removeItem('pb_manage_login_time')
            window.location.replace('/pb/manage/login')
        })

        loadDocuments()
    </script>
</body>
</html>`

    return e.html(200, html)
})
