<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));
$statusOptions = article_generation_task_editable_status_options();
$domains = array();
$models = array();
$menuOptions = array();
$error = '';
$success = '';
$taskId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$isEdit = $taskId > 0;
$form = array(
    'task_name' => '',
    'template_id' => 0,
    'model_id' => 0,
    'custom_prompt' => '',
    'article_length' => '1200-1800字',
    'path_prefix' => 'article',
    'interval_seconds' => 0,
    'generate_image' => 1,
    'cover_watermark' => 1,
    'cover_watermark_text' => '',
    'publish_now' => 0,
    'static_output' => 0,
    'use_folder_cover' => 0,
    'target_menu_ids' => array(),
    'status' => 'enabled',
    'remark' => '',
    'domain_ids' => array(),
    'keywords_text' => ''
);

try {
    $domains = list_enabled_domain_options();
    $models = list_enabled_ai_model_options();
    if ($isEdit) {
        $existing = find_article_generation_task_form_data($taskId);
        if (!$existing) {
            $error = '未找到对应的文章任务。';
            $isEdit = false;
        } else {
            $form = array_merge($form, $existing);
        }
    }
    $menuOptions = array();
    foreach ($domains as $d) {
        $dMenus = list_enabled_menu_options((int)$d['id']);
        foreach ($dMenus as $dm) {
            if (!empty($dm['is_home'])) continue;
            if (isset($dm['custom_url']) && trim((string)$dm['custom_url']) !== '') continue;
            $dm['_domain'] = isset($d['domain']) ? (string)$d['domain'] : '';
            $dm['_domain_id'] = (int)$d['id'];
            $menuOptions[] = $dm;
        }
    }
} catch (Exception $e) {
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_csrf();
    $form = normalize_article_task_form_data($_POST);
    try {
        if ($isEdit) {
            update_article_generation_task($taskId, $form);
            $success = '文章任务已更新成功。';
            $loaded = find_article_generation_task_form_data($taskId);
            if ($loaded) {
                $form = array_merge($form, $loaded);
            }
        } else {
            $newId = create_article_generation_task($form);
            redirect('/admin/article-task/edit.php?id=' . (int)$newId . '&saved=1');
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

if (isset($_GET['saved']) && $_GET['saved'] === '1' && $success === '') {
    $success = '文章任务已创建成功。';
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(APP_NAME); ?> - <?php echo $isEdit ? '编辑文章任务' : '新建文章任务'; ?></title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
    <style>
    .site-build-grid { display:grid; grid-template-columns:minmax(0, 1.65fr) 340px; gap:20px; align-items:start; }
    .site-build-grid.grid-full { grid-template-columns:1fr; }
    .right-panel { position:sticky; top:24px; }
    .right-panel .progress-shell { padding:22px; border-radius:24px; background:linear-gradient(180deg, #ffffff 0%, #f8fafc 100%); border:1px solid rgba(148,163,184,0.18); box-shadow:0 22px 54px rgba(15,23,42,0.08); }
    .right-panel .progress-shell .input-group { margin-bottom:14px; }
    .right-panel .progress-shell .input-group:last-child { margin-bottom:0; }
    .right-panel .progress-shell .input-group span:first-child { display:block; font-size:13px; font-weight:600; color:#334155; margin-bottom:6px; }
    .domain-multi-grid { display:grid; grid-template-columns:repeat(2, minmax(0, 1fr)); gap:10px; padding:14px; border:1px solid rgba(148,163,184,0.16); border-radius:16px; background:#f8fafc; max-height:240px; overflow:auto; }
    .domain-multi-item { display:flex; align-items:flex-start; gap:8px; font-size:13px; color:#334155; }
    .domain-multi-item input { margin-top:2px; }
    .prompt-preset-btn { padding:5px 12px; font-size:12px; font-weight:600; border-radius:8px; border:1px solid rgba(148,163,184,.22); background:#f8fafc; color:#64748b; cursor:pointer; transition:all .15s; }
    .prompt-preset-btn:hover { border-color:rgba(99,102,241,.3); color:#4f46e5; background:rgba(99,102,241,.04); }
    .prompt-preset-btn.is-active { background:linear-gradient(135deg,#4f46e5,#6366f1); color:#fff; border-color:transparent; box-shadow:0 2px 8px rgba(79,70,229,.22); }
    @media (max-width: 1080px) { .site-build-grid { grid-template-columns:1fr; } .right-panel { position:static; } }
    @media (max-width: 720px) { .domain-multi-grid { grid-template-columns:1fr; } }
    </style>
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('site_build', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1><?php echo $isEdit ? '编辑定时任务' : '新建定时任务'; ?></h1><p>配置域名、文章模板、关键词池与后台执行策略，后续由调度器静默执行。</p></div>
                <div class="topbar-actions"><a class="btn-ghost" href="/admin/site-build/index.php?mode=tasklist">查看任务列表</a></div>
            </header>
            <div class="site-build-grid">
                <div>
                    <section class="page-card site-build-form">
                <?php if ($error !== ''): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">保存失败</strong>
                        <p style="margin:0; color:#b91c1c;"><?php echo e($error); ?></p>
                    </div>
                <?php endif; ?>
                <?php if ($success !== ''): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);">
                        <strong style="color:#15803d;">保存成功</strong>
                        <p style="margin:0; color:#166534;"><?php echo e($success); ?></p>
                    </div>
                <?php endif; ?>
                <form id="edit-task-form" method="post" action="/admin/article-task/edit.php<?php echo $isEdit ? '?id=' . (int)$taskId : ''; ?>">
                    <?php echo csrf_field(); ?>
                    <div class="form-grid" style="grid-template-columns:1fr 1fr;">
                        <div class="input-group">
                            <span>* 任务名称</span>
                            <input class="input" type="text" name="task_name" value="<?php echo e($form['task_name']); ?>" placeholder="例如：装修类文章日更任务">
                        </div>
                        <div class="input-group">
                            <span>* 任务状态</span>
                            <select class="select" name="status">
                                <?php foreach ($statusOptions as $key => $label): ?>
                                    <option value="<?php echo e($key); ?>"<?php echo $form['status'] === $key ? ' selected' : ''; ?>><?php echo e($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="input-group" style="grid-column:1/-1;">
                            <span>* 执行域名（可多选）</span>
                            <div class="domain-multi-grid">
                                <?php foreach ($domains as $item): ?>
                                    <label class="domain-multi-item"><input type="checkbox" name="domain_ids[]" value="<?php echo (int)$item['id']; ?>"<?php echo in_array((int)$item['id'], $form['domain_ids'], true) ? ' checked' : ''; ?>><span><?php echo e($item['domain']); ?><br><small style="color:#94a3b8;"><?php echo e($item['site_name']); ?></small></span></label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="input-group">
                            <span>模板套件</span>
                            <input type="hidden" name="template_id" value="0">
                            <div class="input" style="background:#f8fafc; color:#64748b; cursor:default;">自动使用域名绑定的模板套件</div>
                        </div>
                        <div class="input-group">
                            <span>路径前缀（备用）</span>
                            <input class="input" type="text" name="path_prefix" value="<?php echo e($form['path_prefix']); ?>" placeholder="如 article / news">
                            <div style="font-size:12px; color:#94a3b8; margin-top:4px;">已选目标菜单时自动使用菜单 slug 作为路径前缀。</div>
                        </div>
                        <div class="input-group" style="grid-column:1/-1;">
                            <span>目标菜单（可多选，按已选域名筛选）</span>
                            <div class="domain-multi-grid" id="edit-menu-grid">
                                <?php if (empty($menuOptions)): ?>
                                    <div style="color:#94a3b8; padding:8px 0;">请先勾选执行域名</div>
                                <?php endif; ?>
                                <?php $selectedMenuIds = isset($form['target_menu_ids']) ? $form['target_menu_ids'] : array(); ?>
                                <?php foreach ($menuOptions as $item): ?>
                                    <label class="domain-multi-item edit-menu-item" data-domain-id="<?php echo (int)$item['_domain_id']; ?>" style="display:none;"><input type="checkbox" name="target_menu_ids[]" value="<?php echo (int)$item['id']; ?>"<?php echo in_array((int)$item['id'], $selectedMenuIds) ? ' checked' : ''; ?>><span><?php echo e($item['menu_name']); ?><br><small style="color:#94a3b8;">/<?php echo e($item['menu_slug']); ?>/ · <?php echo e($item['_domain']); ?></small></span></label>
                                <?php endforeach; ?>
                            </div>
                            <div style="font-size:12px; color:#94a3b8; margin-top:6px;">勾选后，任务生成的文章会自动归入对应菜单栏目。</div>
                        </div>
                        <div class="input-group">
                            <span>生成标题图</span>
                            <label style="display:flex; align-items:center; gap:10px; min-height:44px; padding:0 2px; color:#334155;"><input type="checkbox" name="generate_image" value="1"<?php echo !empty($form['generate_image']) ? ' checked' : ''; ?>> 自动生成文章标题图（同时作为封面图）</label>
                            <div id="watermark_panel" style="margin-top:6px;<?php echo empty($form['generate_image']) ? ' display:none;' : ''; ?>">
                                <label style="display:flex; align-items:center; gap:8px; font-size:13px; color:#475569;"><input type="checkbox" name="cover_watermark" value="1" id="chk_watermark"<?php echo !empty($form['cover_watermark']) ? ' checked' : ''; ?>> 添加水印</label>
                                <div id="watermark_text_panel" style="margin-top:6px;<?php echo empty($form['cover_watermark']) ? ' display:none;' : ''; ?>">
                                    <input class="input" type="text" name="cover_watermark_text" value="<?php echo e(isset($form['cover_watermark_text']) ? $form['cover_watermark_text'] : ''); ?>" placeholder="自定义水印内容，留空默认使用域名对应的站点名" style="font-size:13px;">
                                </div>
                            </div>
                        </div>
                        <div class="input-group">
                            <span>生成后发布</span>
                            <label style="display:flex; align-items:center; gap:10px; min-height:44px; padding:0 2px; color:#334155;"><input type="checkbox" name="publish_now" value="1" id="chk_publish_now"<?php echo !empty($form['publish_now']) ? ' checked' : ''; ?>> 自动发布（生成后直接设为已发布状态）</label>
                            <div id="static_output_panel" style="margin-top:6px;<?php echo empty($form['publish_now']) ? ' display:none;' : ''; ?>">
                                <label style="display:flex; align-items:center; gap:8px; font-size:13px; color:#475569;"><input type="checkbox" name="static_output" value="1" id="chk_static_output"<?php echo !empty($form['static_output']) ? ' checked' : ''; ?>> 同时生成静态HTML文件</label>
                                <div style="font-size:12px; color:#94a3b8; margin-top:4px;">使用伪静态（rewrite）方式访问的站点无需勾选此项。</div>
                            </div>
                        </div>
                        <div class="input-group" style="grid-column:1/-1; border-top:1px solid rgba(148,163,184,0.12); padding-top:18px; margin-top:8px;">
                            <span>插入本地图片</span>
                            <label style="display:flex; align-items:center; gap:10px; min-height:44px; padding:0 2px; color:#334155;"><input type="checkbox" name="insert_images" value="1" id="chk_insert_images"<?php echo !empty($form['insert_images']) ? ' checked' : ''; ?>> 从指定文件夹随机选取图片插入文章正文</label>
                        </div>
                        <div class="input-group" id="image_config_panel" style="grid-column:1/-1;<?php echo empty($form['insert_images']) ? ' display:none;' : ''; ?>">
                            <div class="form-grid" style="gap:14px;">
                                <div class="input-group full-row">
                                    <span>图片文件夹路径</span>
                                    <input class="input" type="text" name="image_folder" value="<?php echo e(isset($form['image_folder']) ? $form['image_folder'] : ''); ?>" placeholder="相对路径如 uploads/images 或绝对路径如 d:/wwwroot/images">
                                    <div style="font-size:12px; color:#94a3b8; margin-top:4px;">支持 jpg/jpeg/png/gif/webp/svg/bmp，系统将随机抽取图片插入文章。</div>
                                </div>
                                <div class="input-group">
                                    <span>插入数量</span>
                                    <input class="input" type="number" name="image_count" min="1" max="10" value="<?php echo (int)(isset($form['image_count']) && $form['image_count'] > 0 ? $form['image_count'] : 1); ?>">
                                    <div style="font-size:12px; color:#94a3b8; margin-top:4px;">1 张插入文章中间，多张自动平均分布在段落之间。</div>
                                </div>
                                <div class="input-group full-row">
                                    <label style="display:flex; align-items:center; gap:10px; min-height:36px; padding:0 2px; color:#334155;"><input type="checkbox" name="use_folder_cover" value="1"<?php echo !empty($form['use_folder_cover']) ? ' checked' : ''; ?>> 将文件夹图片设为封面图（优先级高于标题图）</label>
                                    <div style="font-size:12px; color:#94a3b8; margin-top:4px;">勾选后，封面图从指定文件夹随机选取；未勾选则使用自动生成的标题图作为封面。</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="filter-row" style="margin-top:18px;">
                        <button class="btn-primary" type="submit"><?php echo $isEdit ? '保存任务' : '创建任务'; ?></button>
                        <a class="btn-ghost" href="/admin/site-build/index.php?mode=tasklist">返回文章任务管理</a>
                    </div>
                </form>
                    </section>
                </div>

                <aside class="right-panel">
                    <div class="progress-shell">
                        <strong style="display:block; font-size:18px; color:#0f172a; margin-bottom:16px;">AI 与内容配置</strong>
                        <div class="input-group">
                            <span>* AI 模型</span>
                            <select class="select" name="model_id" form="edit-task-form">
                                <option value="0">请选择 AI 模型</option>
                                <?php foreach ($models as $item): ?>
                                    <option value="<?php echo (int)$item['id']; ?>"<?php echo (int)$form['model_id'] === (int)$item['id'] ? ' selected' : ''; ?>><?php echo e($item['name']); ?>（<?php echo e($item['provider']); ?> / <?php echo e($item['model_name']); ?>）</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="input-group">
                            <span>文章字数</span>
                            <input class="input" type="text" name="article_length" form="edit-task-form" value="<?php echo e($form['article_length']); ?>" placeholder="如：1200-1800字">
                        </div>
                        <div class="input-group">
                            <span>执行间隔（秒）</span>
                            <input class="input" type="number" min="0" max="86400" name="interval_seconds" form="edit-task-form" value="<?php echo (int)$form['interval_seconds']; ?>">
                        </div>
                        <div class="input-group">
                            <span>* 关键词池</span>
                            <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:8px;">
                                <input type="number" id="kwAiQty" class="input" min="1" max="500" value="50" style="width:80px;height:34px;margin:0;padding:4px 8px;font-size:13px;" placeholder="数量">
                                <span style="font-size:13px;color:#64748b;">条</span>
                                <button type="button" class="btn-soft" id="btnAiKeywords" style="white-space:nowrap;height:34px;font-size:13px;">AI 生成关键词</button>
                                <span id="kwAiStatus" style="font-size:13px;color:#6b7280;"></span>
                            </div>
                            <textarea class="input" name="keywords_text" form="edit-task-form" id="editKeywordsText" placeholder="一行一个关键词，也支持逗号分隔。&#10;任务执行成功后，关键词将从待处理池中消费。" style="min-height:180px;"><?php echo e($form['keywords_text']); ?></textarea>
                            <label style="display:inline-flex; align-items:center; gap:6px; margin-top:6px; cursor:pointer; font-size:13px; color:#64748b;">
                                <input type="checkbox" name="reuse_keywords" form="edit-task-form" value="1"<?php echo !empty($form['reuse_keywords']) ? ' checked' : ''; ?>>
                                重复使用关键词（执行完最后一个后从头循环，不消费关键词）
                            </label>
                        </div>
                        <div class="input-group">
                            <span>自定义 AI 指令</span>
                            <textarea class="input" name="custom_prompt" form="edit-task-form" placeholder="例如：采用问答式结构、避免营销语气、小标题贴近真实搜索表达。" style="min-height:100px;"><?php echo e($form['custom_prompt']); ?></textarea>
                            <div class="prompt-presets" style="display:flex;flex-wrap:wrap;gap:6px;margin-top:8px;">
                                <button type="button" class="prompt-preset-btn is-active" data-prompt-key="0">拟人化风格</button>
                                <button type="button" class="prompt-preset-btn" data-prompt-key="1">专业化写作</button>
                                <button type="button" class="prompt-preset-btn" data-prompt-key="2">幽默化写作</button>
                                <button type="button" class="prompt-preset-btn" data-prompt-key="3">Google SEO</button>
                            </div>
                        </div>
                        <div class="input-group">
                            <span>备注</span>
                            <input class="input" type="text" name="remark" form="edit-task-form" value="<?php echo e($form['remark']); ?>" placeholder="记录任务用途、分组、项目说明等">
                        </div>
                    </div>
                </aside>
            </div>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
<script>
(function () {
    // 域名-菜单联动
    var domainChecks = document.querySelectorAll('input[name="domain_ids[]"]');
    var menuItems = document.querySelectorAll('.edit-menu-item');
    function syncMenuVisibility() {
        var selected = {};
        domainChecks.forEach(function (cb) { if (cb.checked) selected[cb.value] = true; });
        menuItems.forEach(function (label) {
            var show = !!selected[label.getAttribute('data-domain-id')];
            label.style.display = show ? '' : 'none';
            if (!show) { var cb = label.querySelector('input[type="checkbox"]'); if (cb) cb.checked = false; }
        });
    }
    domainChecks.forEach(function (cb) { cb.addEventListener('change', syncMenuVisibility); });
    syncMenuVisibility();

    // 插入图片面板展开/收起
    var chkImg = document.getElementById('chk_insert_images');
    var imgPanel = document.getElementById('image_config_panel');
    if (chkImg && imgPanel) {
        chkImg.addEventListener('change', function () { imgPanel.style.display = chkImg.checked ? '' : 'none'; });
    }

    // 生成标题图 → 水印面板联动
    var chkGenImg = document.querySelector('input[name="generate_image"]');
    var wmPanel = document.getElementById('watermark_panel');
    var chkWm = document.getElementById('chk_watermark');
    var wmTextPanel = document.getElementById('watermark_text_panel');
    if (chkGenImg && wmPanel) {
        chkGenImg.addEventListener('change', function () { wmPanel.style.display = chkGenImg.checked ? '' : 'none'; });
    }
    if (chkWm && wmTextPanel) {
        chkWm.addEventListener('change', function () { wmTextPanel.style.display = chkWm.checked ? '' : 'none'; });
    }

    // 发布 → 静态输出面板联动
    var chkPublish = document.getElementById('chk_publish_now');
    var staticPanel = document.getElementById('static_output_panel');
    if (chkPublish && staticPanel) {
        chkPublish.addEventListener('change', function () { staticPanel.style.display = chkPublish.checked ? '' : 'none'; });
    }

    // AI 风格预设按钮
    var promptPresets = {
        0: '你是一位经验丰富的内容创作者，配备根据不同的主题灵活运营与写高质量文章。以下是关于你所有的写作指南，请将这些要求视为创作原则：\n\n1. 首先最重要的原则是自然、真实，看起来像一位有经验有个性的人在跟你分享他知道的东西。\n2. 避免AI痕迹，不要使用"首先、其次、总之、综上所述"这类模板化过渡词。\n3. 保持对话感和轻松语气，像在跟朋友聊天一样。\n4. 适度使用口语化表达，增加可信度。\n5. 加入合理的个人观点和实际经验。\n6. 不要生成文章的元信息（如"SEO关键词"、"meta描述"等），只专注于正文内容。',
        1: '你是一位专业领域写作者，擅长撰写结构清晰、逻辑严密的深度文章。\n\n1. 内容需要有明确的论点和充分的论据支撑。\n2. 使用专业但不晦涩的语言。\n3. 适当引用数据或行业案例增加可信度。\n4. 每个小标题下的内容要有深度，不要泛泛而谈。\n5. 适合用于行业分析、技术解读、知识科普类文章。\n6. 不要生成文章的元信息（如"SEO关键词"、"meta描述"等），只专注于正文内容。',
        2: '你是一位风趣幽默的自媒体写手，擅长用轻松诙谐的方式讲清楚复杂的事情。\n\n1. 语言风格活泼有趣，像在聊天。\n2. 适度使用比喻、夸张等修辞手法。\n3. 加入一些生活化的例子和类比。\n4. 在保持趣味性的同时确保内容准确有用。\n5. 适合用于科普、评测、生活建议类文章。\n6. 不要生成文章的元信息（如"SEO关键词"、"meta描述"等），只专注于正文内容。',
        3: 'You are an experienced SEO content writer who creates high-quality, search-optimized articles.\n\n1. Write in clear, natural language that reads well for both users and search engines.\n2. Use relevant long-tail keywords naturally throughout the content.\n3. Structure content with clear H2/H3 headings that include target keywords.\n4. Include practical, actionable information that satisfies search intent.\n5. Write comprehensive content that covers the topic thoroughly.\n6. Do not include meta information (like "SEO keywords", "meta description", etc.), focus only on the article body.'
    };
    var presetBtns = document.querySelectorAll('.prompt-preset-btn');
    var promptTA = document.querySelector('textarea[name="custom_prompt"]');
    presetBtns.forEach(function (btn) {
        btn.addEventListener('click', function () {
            var key = btn.getAttribute('data-prompt-key');
            presetBtns.forEach(function (b) { b.classList.remove('is-active'); });
            btn.classList.add('is-active');
            if (promptTA && promptPresets[key] !== undefined) {
                promptTA.value = promptPresets[key];
            }
        });
    });

    // AI 生成关键词
    var btnKw = document.getElementById('btnAiKeywords');
    var kwStatus = document.getElementById('kwAiStatus');
    var kwTA = document.getElementById('editKeywordsText');
    var kwQtyInput = document.getElementById('kwAiQty');
    if (btnKw && kwTA) {
        btnKw.addEventListener('click', function () {
            var modelSelect = document.querySelector('select[name="model_id"]');
            var modelId = modelSelect ? modelSelect.value : '0';
            if (!modelId || modelId === '0') { kwStatus.textContent = '请先选择 AI 模型'; return; }
            var qty = kwQtyInput ? parseInt(kwQtyInput.value, 10) : 50;
            if (isNaN(qty) || qty < 1) qty = 50;
            var menuNames = [];
            var selectedDomainId = 0;
            document.querySelectorAll('.edit-menu-item input[type="checkbox"]:checked').forEach(function (cb) {
                var txt = cb.parentElement.querySelector('span');
                if (txt) { var name = txt.textContent.split('\n')[0].trim(); if (name) menuNames.push(name); }
                // 获取第一个选中菜单所属的域名ID
                if (selectedDomainId === 0) {
                    var label = cb.closest('.edit-menu-item');
                    if (label) { selectedDomainId = parseInt(label.getAttribute('data-domain-id'), 10); }
                }
            });
            if (menuNames.length === 0) { kwStatus.textContent = '请先勾选目标菜单'; return; }
            btnKw.disabled = true;
            btnKw.textContent = '生成中...';
            kwStatus.textContent = '';
            kwTA.value = '';
            fetch('/admin/api/ai-generate-keywords.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ menu_names: menuNames.join(','), quantity: qty, model_id: modelId, domain_id: selectedDomainId })
            })
            .then(function (response) {
                var reader = response.body.getReader();
                var decoder = new TextDecoder();
                var buffer = '';
                function read() {
                    return reader.read().then(function (result) {
                        if (result.done) {
                            var raw = kwTA.value;
                            raw = raw.replace(/[、，,；;｜\|]/g, '\n');
                            raw = raw.replace(/(?<=[\u4e00-\u9fff\u3400-\u4dbf])\s+(?=[\u4e00-\u9fff\u3400-\u4dbf])/g, '\n');
                            raw = raw.replace(/^[#＃]\s*\d+[\.、\)\s]*/gm, '');
                            raw = raw.replace(/^\d+[\.\)、）]\s*/gm, '');
                            raw = raw.replace(/^[-–—·•●○◆▪]\s*/gm, '');
                            raw = raw.replace(/\n{2,}/g, '\n');
                            var lines = raw.trim().split('\n');
                            var seen = {};
                            var unique = [];
                            for (var li = 0; li < lines.length; li++) {
                                var kw = lines[li].trim();
                                if (kw === '') continue;
                                var key = kw.toLowerCase();
                                if (seen[key]) continue;
                                seen[key] = true;
                                unique.push(kw);
                            }
                            if (qty > 0 && unique.length > qty) unique = unique.slice(0, qty);
                            kwTA.value = unique.join('\n');
                            btnKw.disabled = false;
                            btnKw.textContent = 'AI 生成关键词';
                            var msg = '✓ 生成完成（' + unique.length + ' 条）';
                            if (lines.length !== unique.length) msg += '，已去重' + (lines.length - unique.length) + '条';
                            kwStatus.textContent = msg;
                            return;
                        }
                        buffer += decoder.decode(result.value, { stream: true });
                        var parts = buffer.split('\n\n');
                        buffer = parts.pop();
                        parts.forEach(function (part) {
                            if (part.indexOf('data: ') === 0) {
                                try {
                                    var json = JSON.parse(part.substring(6));
                                    if (json.text) { kwTA.value += json.text; }
                                    if (json.error) { kwStatus.textContent = '错误：' + json.error; }
                                } catch (e) {}
                            }
                        });
                        return read();
                    });
                }
                return read();
            })
            .catch(function (err) {
                btnKw.disabled = false;
                btnKw.textContent = 'AI 生成关键词';
                kwStatus.textContent = '请求失败：' + err.message;
            });
        });
    }
})();
</script>
</body>
</html>
