<?php
$title='在线客服管理';
include __DIR__ . '/head.php';
?>
<style>
#feedback_original_content img {
    max-width: 100%;
    max-height: 200px;
    border-radius: 6px;
    margin: 6px 0;
    display: block;
}
.tab-scroll {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}
.tab-scroll::-webkit-scrollbar {
    height: 4px;
}
.tab-scroll::-webkit-scrollbar-thumb {
    background: #d1d5db;
    border-radius: 4px;
}
.tab-btn {
    white-space: nowrap;
    flex: 0 0 auto;
}
@media (max-width: 640px) {
    .table-responsive table {
        min-width: 760px;
    }
}
</style>

<div class="p-4 md:p-6">
    <!-- Tab 切换 -->
    <div class="tab-scroll flex border-b border-gray-200 mb-4 gap-1">
        <button onclick="switchTab('settings')" id="tab_settings" class="tab-btn px-3 sm:px-4 py-2 text-sm font-medium border-b-2 border-blue-600 text-blue-600">基础设置</button>
        <button onclick="switchTab('qa')" id="tab_qa" class="tab-btn px-3 sm:px-4 py-2 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700">问答管理</button>
        <button onclick="switchTab('chain')" id="tab_chain" class="tab-btn px-3 sm:px-4 py-2 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700">连续问答</button>
        <button onclick="switchTab('feedback')" id="tab_feedback" class="tab-btn px-3 sm:px-4 py-2 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700">留言管理</button>
    </div>

    <!-- Tab 1: 基础设置 -->
    <div id="panel_settings" class="tab-panel">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="p-4 md:p-6 border-b border-gray-200">
                <h2 class="text-base md:text-lg font-semibold text-gray-800">客服系统设置</h2>
            </div>
            <div class="p-4 md:p-6">
                <form onsubmit="saveConfig(this);return false;" class="space-y-6">
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                        <label class="text-sm font-medium text-gray-700">客服系统开关</label>
                        <div class="md:col-span-3">
                            <select name="cs_enabled" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" default="<?php echo $conf['cs_enabled'] ?? '1'?>">
                                <option value="1">开启</option>
                                <option value="0">关闭</option>
                            </select>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                        <label class="text-sm font-medium text-gray-700">悬浮球图标</label>
                        <div class="md:col-span-3">
                            <div class="flex items-center gap-2 mb-2 flex-nowrap">
                                <input type="text" name="cs_bubble_icon" id="cs_bubble_icon" class="flex-1 min-w-0 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm" value="<?php echo htmlspecialchars($conf['cs_bubble_icon'] ?? '')?>" placeholder="图标URL地址，留空使用默认图标">
                                <label class="shrink-0 whitespace-nowrap px-3 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-medium rounded-lg cursor-pointer transition text-center">
                                    <i class="fas fa-upload mr-1"></i>上传
                                    <input type="file" accept="image/*" onchange="uploadIcon(this)" class="hidden">
                                </label>
                            </div>
                            <div id="icon_preview" class="mt-2" style="<?php echo ($conf['cs_bubble_icon'] ?? '') == '' ? 'display:none' : ''?>">
                                <img src="<?php echo htmlspecialchars($conf['cs_bubble_icon'] ?? '')?>" class="w-12 h-12 rounded-full object-cover border">
                            </div>
                            <p class="mt-1 text-xs text-gray-500">建议使用 64x64 像素的正方形图片，支持 PNG/JPG/GIF/SVG</p>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                        <label class="text-sm font-medium text-gray-700">欢迎语</label>
                        <div class="md:col-span-3">
                            <textarea name="cs_welcome_msg" rows="2" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"><?php echo htmlspecialchars($conf['cs_welcome_msg'] ?? '您好，欢迎咨询！请选择下方问题或直接输入。</br>隐藏窗口：会保留历史对话。</br>关闭窗口：清除历史对话')?></textarea>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                        <label class="text-sm font-medium text-gray-700">悬浮球位置</label>
                        <div class="md:col-span-3">
                            <select name="cs_bubble_position" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" default="<?php echo $conf['cs_bubble_position'] ?? 'right'?>">
                                <option value="right">右下角</option>
                                <option value="left">左下角</option>
                            </select>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-start">
                        <label class="text-sm font-medium text-gray-700 pt-2">无匹配默认回复</label>
                        <div class="md:col-span-3">
                            <textarea name="cs_no_match_msg" rows="2" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm" placeholder="留空则显示默认文案"><?php echo htmlspecialchars($conf['cs_no_match_msg'] ?? '')?></textarea>
                            <p class="mt-1 text-xs text-gray-500">用户输入无法匹配时显示的回复，留空则显示内置默认文案</p>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-start">
                        <label class="text-sm font-medium text-gray-700 pt-2">会话窗口顶部信息</label>
                        <div class="md:col-span-3">
                            <textarea name="cs_top_info" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm font-mono" placeholder="支持HTML和PHP代码，留空则不显示"><?php echo htmlspecialchars($conf['cs_top_info'] ?? '')?></textarea>
                            <p class="mt-1 text-xs text-gray-500">显示在会话窗口顶部，支持HTML和PHP代码。可用变量：<code class="bg-gray-100 px-1 rounded">$conf</code>网站配置(如$conf['qq'])、<code class="bg-gray-100 px-1 rounded">$date</code>当前时间、<code class="bg-gray-100 px-1 rounded">$userrow</code>当前用户信息(如$userrow['qq'])</p>
                        </div>
                    </div>
                    <div class="border-t border-gray-200 pt-4 mt-4">
                        <h3 class="text-sm font-semibold text-gray-800 mb-3"><i class="fas fa-envelope mr-2"></i>留言通知设置</h3>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                        <label class="text-sm font-medium text-gray-700">留言功能开关</label>
                        <div class="md:col-span-3">
                            <select name="cs_feedback_enabled" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" default="<?php echo $conf['cs_feedback_enabled'] ?? '1'?>">
                                <option value="1">开启</option>
                                <option value="0">关闭</option>
                            </select>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                        <label class="text-sm font-medium text-gray-700">接收留言邮箱</label>
                        <div class="md:col-span-3">
                            <input type="email" name="cs_feedback_email" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm" value="<?php echo htmlspecialchars($conf['cs_feedback_email'] ?? '')?>" placeholder="接收留言通知的邮箱地址">
                            <p class="mt-1 text-xs text-gray-500">有新留言时发送通知到此邮箱，留空则不发送邮件通知</p>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                        <label class="text-sm font-medium text-gray-700">每日留言上限</label>
                        <div class="md:col-span-3">
                            <input type="number" name="cs_feedback_daily_limit" min="0" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm" value="<?php echo htmlspecialchars($conf['cs_feedback_daily_limit'] ?? '0')?>" placeholder="0表示不限制">
                            <p class="mt-1 text-xs text-gray-500">限制用户每天新建留言次数，0为不限制。连续回复不计入次数</p>
                        </div>
                    </div>
                    <div class="flex items-center gap-4 pt-4">
                        <button type="submit" class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition">
                            <i class="fas fa-save mr-2"></i>保存设置
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Tab 2: 问答管理 -->
    <div id="panel_qa" class="tab-panel" style="display:none">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="p-4 md:p-6 border-b border-gray-200 flex items-center justify-between">
                <h2 class="text-base md:text-lg font-semibold text-gray-800">问答管理</h2>
                <button onclick="showQaModal()" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition">
                    <i class="fas fa-plus mr-1"></i>添加问答
                </button>
            </div>
            <div class="p-4 md:p-6">
                <div class="flex items-center gap-2 mb-4">
                    <input type="text" id="qa_search" class="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm" placeholder="搜索问题或回答...">
                    <button onclick="loadQaList(1)" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm rounded-lg"><i class="fas fa-search"></i></button>
                </div>
                <div class="table-responsive">
                    <table class="w-full text-sm">
                        <thead>
                            <tr class="bg-gray-50 text-gray-600">
                                <th class="px-4 py-3 text-left font-medium">ID</th>
                                <th class="px-4 py-3 text-left font-medium">问题</th>
                                <th class="px-4 py-3 text-left font-medium">回答</th>
                                <th class="px-4 py-3 text-center font-medium">匹配类型</th>
                                <th class="px-4 py-3 text-center font-medium">热键</th>
                                <th class="px-4 py-3 text-center font-medium">状态</th>
                                <th class="px-4 py-3 text-center font-medium">排序</th>
                                <th class="px-4 py-3 text-center font-medium">操作</th>
                            </tr>
                        </thead>
                        <tbody id="qa_tbody"></tbody>
                    </table>
                </div>
                <div id="qa_pagination" class="flex items-center justify-between mt-4"></div>
            </div>
        </div>
    </div>

    <!-- Tab 3: 连续问答 -->
    <div id="panel_chain" class="tab-panel" style="display:none">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="p-4 md:p-6 border-b border-gray-200 flex items-center justify-between">
                <h2 class="text-base md:text-lg font-semibold text-gray-800">连续问答管理</h2>
                <button onclick="showChainModal()" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition">
                    <i class="fas fa-plus mr-1"></i>添加问答链
                </button>
            </div>
            <div class="p-4 md:p-6">
                <div class="table-responsive">
                    <table class="w-full text-sm">
                        <thead>
                            <tr class="bg-gray-50 text-gray-600">
                                <th class="px-4 py-3 text-left font-medium">链名称</th>
                                <th class="px-4 py-3 text-center font-medium">步骤数</th>
                                <th class="px-4 py-3 text-center font-medium">状态</th>
                                <th class="px-4 py-3 text-center font-medium">操作</th>
                            </tr>
                        </thead>
                        <tbody id="chain_tbody"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Tab 4: 留言管理 -->
    <div id="panel_feedback" class="tab-panel" style="display:none">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="p-4 md:p-6 border-b border-gray-200 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                <h2 class="text-base md:text-lg font-semibold text-gray-800 whitespace-nowrap">留言管理</h2>
                <div class="flex items-center gap-2 flex-wrap sm:flex-nowrap">
                    <select id="feedback_status_filter" class="px-3 py-2 border border-gray-300 rounded-lg text-sm" onchange="loadFeedbackList(1)">
                        <option value="">全部状态</option>
                        <option value="0">待处理</option>
                        <option value="1">正在处理</option>
                        <option value="2">已处理</option>
                    </select>
                    <button onclick="deleteSelectedFeedback()" class="px-4 py-2 bg-red-50 hover:bg-red-100 text-red-600 text-sm font-medium rounded-lg transition">
                        <i class="fas fa-trash mr-1"></i>删除选中
                    </button>
                </div>
            </div>
            <div class="p-4 md:p-6">
                <div class="table-responsive">
                    <table class="w-full text-sm">
                        <thead>
                            <tr class="bg-gray-50 text-gray-600">
                                <th class="px-4 py-3 text-center font-medium w-10"><input type="checkbox" id="feedback_select_all" onchange="toggleFeedbackSelectAll()"></th>
                                <th class="px-4 py-3 text-left font-medium">ID</th>
                                <th class="px-4 py-3 text-left font-medium">用户</th>
                                <th class="px-4 py-3 text-left font-medium">邮箱</th>
                                <th class="px-4 py-3 text-left font-medium">留言内容</th>
                                <th class="px-4 py-3 text-center font-medium">状态</th>
                                <th class="px-4 py-3 text-center font-medium">时间</th>
                                <th class="px-4 py-3 text-center font-medium">操作</th>
                            </tr>
                        </thead>
                        <tbody id="feedback_tbody"></tbody>
                    </table>
                </div>
                <div id="feedback_pagination" class="flex items-center justify-between mt-4"></div>
            </div>
        </div>
    </div>
</div>

<!-- 问答编辑弹窗 -->
<div id="qaModal" class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/40" onclick="closeQaModal()"></div>
    <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[95vw] max-w-lg bg-white rounded-xl shadow-2xl max-h-[90vh] flex flex-col">
        <div class="p-4 border-b border-gray-200 flex items-center justify-between">
            <h3 class="text-lg font-semibold" id="qaModalTitle">添加问答</h3>
            <button onclick="closeQaModal()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
        </div>
        <div class="p-4 space-y-4 overflow-y-auto flex-1">
            <input type="hidden" id="qa_edit_id" value="0">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">问题</label>
                <input type="text" id="qa_question" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" placeholder="用户可能提问的问题">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">回答 <span class="text-gray-400 font-normal">(支持HTML，可插入图片)</span></label>
                <div class="flex gap-2 mb-2">
                    <button type="button" onclick="insertQaImage()" class="px-3 py-1 bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs rounded-lg"><i class="fas fa-image mr-1"></i>插入图片</button>
                    <button type="button" onclick="insertQaLink()" class="px-3 py-1 bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs rounded-lg"><i class="fas fa-link mr-1"></i>插入链接</button>
                </div>
                <textarea id="qa_answer" rows="4" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" placeholder="机器人的回答内容，支持HTML标签和图片"></textarea>
                <input type="file" id="qa_image_input" accept="image/*" class="hidden" onchange="uploadQaImage(this)">
            </div>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">匹配类型</label>
                    <select id="qa_match_type" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm">
                        <option value="0">精确匹配</option>
                        <option value="1">模糊匹配</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">是否热键</label>
                    <select id="qa_is_hotkey" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm">
                        <option value="1">是</option>
                        <option value="0">否</option>
                    </select>
                </div>
            </div>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">触发关键词</label>
                    <input type="text" id="qa_trigger_keyword" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" placeholder="模糊匹配时使用">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">排序</label>
                    <input type="number" id="qa_sort" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" value="50">
                </div>
            </div>
        </div>
        <div class="p-4 border-t border-gray-200 flex justify-end gap-2 flex-wrap">
            <button onclick="closeQaModal()" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 text-sm rounded-lg">取消</button>
            <button onclick="saveQa()" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm rounded-lg">保存</button>
        </div>
    </div>
</div>

<!-- 连续问答编辑弹窗 -->
<div id="chainModal" class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/40" onclick="closeChainModal()"></div>
    <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-2xl bg-white rounded-xl shadow-2xl max-h-[80vh] flex flex-col">
        <div class="p-4 border-b border-gray-200 flex items-center justify-between">
            <h3 class="text-lg font-semibold" id="chainModalTitle">添加连续问答链</h3>
            <button onclick="closeChainModal()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
        </div>
        <div class="p-4 space-y-4 overflow-y-auto flex-1">
            <input type="hidden" id="chain_edit_id" value="">
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">链名称（也作为触发词和热键文本）</label>
                    <input type="text" id="chain_name" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" placeholder="例如：新手引导">
                </div>
                <div class="flex items-end gap-4">
                    <div class="flex-1">
                        <label class="block text-sm font-medium text-gray-700 mb-1">是否热键</label>
                        <select id="chain_is_hotkey" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm">
                            <option value="1">是</option>
                            <option value="0">否</option>
                        </select>
                    </div>
                    <div class="flex-1">
                        <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                        <select id="chain_status" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm">
                            <option value="1">启用</option>
                            <option value="0">禁用</option>
                        </select>
                    </div>
                </div>
            </div>
            <div>
                <div class="flex items-center justify-between mb-2">
                    <label class="text-sm font-medium text-gray-700">步骤列表</label>
                    <button onclick="addChainStep()" class="px-3 py-1 bg-green-50 hover:bg-green-100 text-green-700 text-xs font-medium rounded-lg"><i class="fas fa-plus mr-1"></i>添加步骤</button>
                </div>
                <div id="chain_steps" class="space-y-3"></div>
            </div>
        </div>
        <div class="p-4 border-t border-gray-200 flex justify-end gap-2">
            <button onclick="closeChainModal()" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 text-sm rounded-lg">取消</button>
            <button onclick="saveChain()" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm rounded-lg">保存</button>
        </div>
    </div>
</div>

<!-- 留言回复弹窗 -->
<div id="feedbackModal" class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/40" onclick="closeFeedbackModal()"></div>
    <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[95vw] max-w-lg bg-white rounded-xl shadow-2xl max-h-[90vh] flex flex-col">
        <div class="p-4 border-b border-gray-200 flex items-center justify-between">
            <h3 class="text-lg font-semibold">回复留言</h3>
            <button onclick="closeFeedbackModal()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
        </div>
        <div class="p-4 space-y-4 overflow-y-auto flex-1">
            <input type="hidden" id="feedback_id">
            <div class="p-3 bg-gray-50 rounded-lg">
                <p class="text-xs text-gray-500 mb-1">对话记录：</p>
                <div id="feedback_conversation" class="text-sm text-gray-700 max-h-72 overflow-y-auto space-y-2" style="word-break:break-word;">暂无对话</div>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">回复内容 <span class="text-gray-400 font-normal">(支持HTML，可插入图片)</span></label>
                <div class="flex gap-2 mb-2">
                    <button type="button" onclick="insertFeedbackImage()" class="px-3 py-1 bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs rounded-lg"><i class="fas fa-image mr-1"></i>插入图片</button>
                </div>
                <textarea id="feedback_reply" rows="4" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" placeholder="输入回复内容..."></textarea>
                <input type="file" id="feedback_image_input" accept="image/*" class="hidden" onchange="uploadFeedbackImage(this)">
            </div>
        </div>
        <div class="p-4 border-t border-gray-200 flex justify-end gap-2 flex-wrap">
            <button onclick="closeFeedbackModal()" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 text-sm rounded-lg">取消</button>
            <button onclick="saveFeedbackReply(1)" class="px-4 py-2 bg-amber-500 hover:bg-amber-600 text-white text-sm rounded-lg">提交回复</button>
            <button onclick="saveFeedbackReply(2)" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm rounded-lg">处理完成</button>
        </div>
    </div>
</div>

<?php include 'foot.php'; ?>
<script>
// Tab 切换
function switchTab(name) {
    document.querySelectorAll('.tab-panel').forEach(function(el){ el.style.display = 'none'; });
    document.querySelectorAll('[id^="tab_"]').forEach(function(el){
        el.classList.remove('border-blue-600','text-blue-600');
        el.classList.add('border-transparent','text-gray-500');
    });
    document.getElementById('panel_' + name).style.display = '';
    document.getElementById('tab_' + name).classList.remove('border-transparent','text-gray-500');
    document.getElementById('tab_' + name).classList.add('border-blue-600','text-blue-600');
    if(name === 'qa') loadQaList(1);
    if(name === 'chain') loadChainList();
    if(name === 'feedback') loadFeedbackList(1);
}

// ========== 基础设置 ==========
function saveConfig(form) {
    showLoading();
    $.ajax({
        type: 'POST', url: 'ajax_customer.php?act=cs_save_config',
        data: $(form).serialize(), dataType: 'json',
        success: function(data) {
            hideLoading();
            showToast(data.msg, data.code == 1 ? 'success' : 'error');
        },
        error: function() { hideLoading(); showToast('服务器错误', 'error'); }
    });
}

function uploadIcon(input) {
    if(!input.files[0]) return;
    var fd = new FormData();
    fd.append('file', input.files[0]);
    showLoading();
    $.ajax({
        type: 'POST', url: 'ajax_customer.php?act=cs_upload_icon',
        data: fd, processData: false, contentType: false, dataType: 'json',
        success: function(data) {
            hideLoading();
            if(data.code == 1) {
                document.getElementById('cs_bubble_icon').value = data.url;
                var preview = document.getElementById('icon_preview');
                preview.style.display = '';
                preview.innerHTML = '<img src="' + data.url + '" class="w-12 h-12 rounded-full object-cover border">';
                showToast('上传成功', 'success');
            } else {
                showToast(data.msg, 'error');
            }
        },
        error: function() { hideLoading(); showToast('上传失败', 'error'); }
    });
}

// ========== 问答管理 ==========
var qaPage = 1;
function loadQaList(page) {
    qaPage = page || 1;
    var kw = document.getElementById('qa_search').value;
    $.post('ajax_customer.php?act=cs_get_qa_list', {page: qaPage, pagesize: 10, kw: kw}, function(data) {
        var html = '';
        if(data.data.length === 0) {
            html = '<tr><td colspan="8" class="px-4 py-8 text-center text-gray-400">暂无数据</td></tr>';
        }
        for(var i = 0; i < data.data.length; i++) {
            var d = data.data[i];
            var answerShort = d.answer.length > 30 ? d.answer.substring(0, 30) + '...' : d.answer;
            html += '<tr class="border-b border-gray-100 hover:bg-gray-50">';
            html += '<td class="px-4 py-3">' + d.id + '</td>';
            html += '<td class="px-4 py-3">' + escHtml(d.question) + '</td>';
            html += '<td class="px-4 py-3 text-gray-500">' + escHtml(answerShort) + '</td>';
            html += '<td class="px-4 py-3 text-center"><span class="px-2 py-1 text-xs rounded-full ' + (d.match_type == '0' ? 'bg-blue-50 text-blue-600' : 'bg-orange-50 text-orange-600') + '">' + (d.match_type == '0' ? '精确' : '模糊') + '</span></td>';
            html += '<td class="px-4 py-3 text-center"><span class="px-2 py-1 text-xs rounded-full ' + (d.is_hotkey == '1' ? 'bg-green-50 text-green-600' : 'bg-gray-100 text-gray-500') + '">' + (d.is_hotkey == '1' ? '是' : '否') + '</span></td>';
            html += '<td class="px-4 py-3 text-center"><button onclick="toggleQaStatus(' + d.id + ',' + (d.status == '1' ? 0 : 1) + ')" class="px-2 py-1 text-xs rounded-full cursor-pointer ' + (d.status == '1' ? 'bg-green-50 text-green-600' : 'bg-red-50 text-red-600') + '">' + (d.status == '1' ? '启用' : '禁用') + '</button></td>';
            html += '<td class="px-4 py-3 text-center">' + d.sort + '</td>';
            html += '<td class="px-4 py-3 text-center whitespace-nowrap">';
            html += '<button onclick="editQa(' + d.id + ')" class="text-blue-600 hover:text-blue-800 text-xs mr-2"><i class="fas fa-edit"></i> 编辑</button>';
            html += '<button onclick="deleteQa(' + d.id + ')" class="text-red-600 hover:text-red-800 text-xs"><i class="fas fa-trash"></i> 删除</button>';
            html += '</td></tr>';
        }
        document.getElementById('qa_tbody').innerHTML = html;
        // 分页
        var pHtml = '<span class="text-sm text-gray-500">共 ' + data.total + ' 条</span><div class="flex gap-1">';
        for(var p = 1; p <= data.end; p++) {
            pHtml += '<button onclick="loadQaList(' + p + ')" class="px-3 py-1 text-sm rounded ' + (p == data.page ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200') + '">' + p + '</button>';
        }
        pHtml += '</div>';
        document.getElementById('qa_pagination').innerHTML = pHtml;
    }, 'json');
}

function showQaModal(id) {
    document.getElementById('qa_edit_id').value = '0';
    document.getElementById('qa_question').value = '';
    document.getElementById('qa_answer').value = '';
    document.getElementById('qa_match_type').value = '0';
    document.getElementById('qa_trigger_keyword').value = '';
    document.getElementById('qa_is_hotkey').value = '1';
    document.getElementById('qa_sort').value = '50';
    document.getElementById('qaModalTitle').textContent = '添加问答';
    document.getElementById('qaModal').classList.remove('hidden');
}

function closeQaModal() {
    document.getElementById('qaModal').classList.add('hidden');
}

function editQa(id) {
    $.post('ajax_customer.php?act=cs_get_qa_list', {page: 1, pagesize: 999}, function(data) {
        for(var i = 0; i < data.data.length; i++) {
            if(parseInt(data.data[i].id) === id) {
                var d = data.data[i];
                document.getElementById('qa_edit_id').value = d.id;
                document.getElementById('qa_question').value = d.question;
                document.getElementById('qa_answer').value = d.answer;
                document.getElementById('qa_match_type').value = d.match_type;
                document.getElementById('qa_trigger_keyword').value = d.trigger_keyword || '';
                document.getElementById('qa_is_hotkey').value = d.is_hotkey;
                document.getElementById('qa_sort').value = d.sort;
                document.getElementById('qaModalTitle').textContent = '编辑问答';
                document.getElementById('qaModal').classList.remove('hidden');
                break;
            }
        }
    }, 'json');
}

function saveQa() {
    var id = document.getElementById('qa_edit_id').value;
    var act = id == '0' ? 'cs_add_qa' : 'cs_edit_qa';
    var postData = {
        id: id,
        question: document.getElementById('qa_question').value,
        answer: document.getElementById('qa_answer').value,
        match_type: document.getElementById('qa_match_type').value,
        trigger_keyword: document.getElementById('qa_trigger_keyword').value,
        is_hotkey: document.getElementById('qa_is_hotkey').value,
        sort: document.getElementById('qa_sort').value
    };
    $.post('ajax_customer.php?act=' + act, postData, function(data) {
        showToast(data.msg, data.code == 1 ? 'success' : 'error');
        if(data.code == 1) { closeQaModal(); loadQaList(qaPage); }
    }, 'json');
}

function deleteQa(id) {
    if(!confirm('确认删除此问答？')) return;
    $.post('ajax_customer.php?act=cs_delete_qa', {id: id}, function(data) {
        showToast(data.msg, data.code == 1 ? 'success' : 'error');
        if(data.code == 1) loadQaList(qaPage);
    }, 'json');
}

function toggleQaStatus(id, status) {
    $.post('ajax_customer.php?act=cs_toggle_status', {id: id, status: status}, function(data) {
        showToast(data.msg, data.code == 1 ? 'success' : 'error');
        loadQaList(qaPage);
    }, 'json');
}

// ========== 连续问答 ==========
function loadChainList() {
    $.post('ajax_customer.php?act=cs_get_chain_list', {}, function(data) {
        var html = '';
        if(!data.data || data.data.length === 0) {
            html = '<tr><td colspan="4" class="px-4 py-8 text-center text-gray-400">暂无连续问答链</td></tr>';
        }
        for(var i = 0; i < (data.data || []).length; i++) {
            var d = data.data[i];
            html += '<tr class="border-b border-gray-100 hover:bg-gray-50">';
            html += '<td class="px-4 py-3 font-medium">' + escHtml(d.chain_name || '') + '</td>';
            html += '<td class="px-4 py-3 text-center">' + d.step_count + ' 步</td>';
            html += '<td class="px-4 py-3 text-center"><button onclick="toggleChainStatus(\'' + d.chain_id + '\',' + (d.status == '1' ? 0 : 1) + ')" class="px-2 py-1 text-xs rounded-full cursor-pointer ' + (d.status == '1' ? 'bg-green-50 text-green-600 hover:bg-green-100' : 'bg-red-50 text-red-600 hover:bg-red-100') + '">' + (d.status == '1' ? '启用' : '禁用') + '</button></td>';
            html += '<td class="px-4 py-3 text-center whitespace-nowrap">';
            html += '<button onclick="editChain(\'' + d.chain_id + '\')" class="text-blue-600 hover:text-blue-800 text-xs mr-2"><i class="fas fa-edit"></i> 编辑</button>';
            html += '<button onclick="deleteChain(\'' + d.chain_id + '\')" class="text-red-600 hover:text-red-800 text-xs"><i class="fas fa-trash"></i> 删除</button>';
            html += '</td></tr>';
        }
        document.getElementById('chain_tbody').innerHTML = html;
    }, 'json');
}

function toggleChainStatus(chainId, status) {
    $.post('ajax_customer.php?act=cs_toggle_chain_status', {chain_id: chainId, status: status}, function(data) {
        showToast(data.msg, data.code == 1 ? 'success' : 'error');
        if(data.code == 1) loadChainList();
    }, 'json');
}

var chainStepCount = 0;
function showChainModal() {
    document.getElementById('chain_edit_id').value = '';
    document.getElementById('chain_name').value = '';
    document.getElementById('chain_is_hotkey').value = '1';
    document.getElementById('chain_status').value = '1';
    document.getElementById('chain_steps').innerHTML = '';
    document.getElementById('chainModalTitle').textContent = '添加连续问答链';
    chainStepCount = 0;
    addChainStep('', '入口回答（用户点击热键后显示的内容）', '');
    addChainStep('下一步', '第1步', '');
    document.getElementById('chainModal').classList.remove('hidden');
}

function closeChainModal() {
    document.getElementById('chainModal').classList.add('hidden');
}

function addChainStep(trigger, question, answer) {
    var idx = chainStepCount++;
    var isFirst = (idx === 0);
    var html = '<div class="border border-gray-200 rounded-lg p-3 bg-gray-50" id="chain_step_' + idx + '">';
    html += '<div class="flex items-center justify-between mb-2">';
    html += '<span class="text-xs font-medium text-gray-500">' + (isFirst ? '入口步骤' : '步骤 ' + idx) + '</span>';
    if(!isFirst) html += '<button onclick="removeChainStep(' + idx + ')" class="text-red-400 hover:text-red-600 text-xs"><i class="fas fa-times"></i></button>';
    html += '</div>';
    if(!isFirst) {
        html += '<div class="mb-2"><input type="text" class="w-full px-2 py-1 border border-gray-300 rounded text-sm chain-trigger" placeholder="触发关键词（如：下一步）" value="' + escAttr(trigger || '下一步') + '"></div>';
    } else {
        html += '<input type="hidden" class="chain-trigger" value="">';
    }
    html += '<div class="mb-2"><input type="text" class="w-full px-2 py-1 border border-gray-300 rounded text-sm chain-question" placeholder="步骤标题" value="' + escAttr(question || '') + '"></div>';
    html += '<div class="flex gap-1 mb-1">';
    html += '<button type="button" onclick="insertChainImage(' + idx + ')" class="px-2 py-0.5 bg-gray-100 hover:bg-gray-200 text-gray-600 text-xs rounded"><i class="fas fa-image"></i></button>';
    html += '<button type="button" onclick="insertChainLink(' + idx + ')" class="px-2 py-0.5 bg-gray-100 hover:bg-gray-200 text-gray-600 text-xs rounded"><i class="fas fa-link"></i></button>';
    html += '</div>';
    html += '<textarea class="w-full px-2 py-1 border border-gray-300 rounded text-sm chain-answer" rows="2" placeholder="回答内容（支持HTML和图片）">' + escHtml(answer || '') + '</textarea>';
    html += '</div>';
    document.getElementById('chain_steps').insertAdjacentHTML('beforeend', html);
}

function removeChainStep(idx) {
    var el = document.getElementById('chain_step_' + idx);
    if(el) el.remove();
}

function editChain(chainId) {
    $.post('ajax_customer.php?act=cs_get_chain_detail', {chain_id: chainId}, function(data) {
        if(data.code != 1 || !data.data.length) { showToast('获取失败', 'error'); return; }
        document.getElementById('chain_edit_id').value = chainId;
        document.getElementById('chain_name').value = data.data[0].chain_name || '';
        document.getElementById('chain_is_hotkey').value = data.data[0].is_hotkey || '1';
        document.getElementById('chain_status').value = data.data[0].status || '1';
        document.getElementById('chain_steps').innerHTML = '';
        document.getElementById('chainModalTitle').textContent = '编辑连续问答链';
        chainStepCount = 0;
        for(var i = 0; i < data.data.length; i++) {
            var s = data.data[i];
            addChainStep(s.trigger_keyword || '', s.question || '', s.answer || '');
        }
        document.getElementById('chainModal').classList.remove('hidden');
    }, 'json');
}

function saveChain() {
    var chainId = document.getElementById('chain_edit_id').value;
    var chainName = document.getElementById('chain_name').value;
    if(!chainName) { showToast('请填写链名称', 'error'); return; }
    var steps = [];
    var stepEls = document.querySelectorAll('#chain_steps > div');
    stepEls.forEach(function(el) {
        steps.push({
            trigger_keyword: el.querySelector('.chain-trigger').value,
            question: el.querySelector('.chain-question').value,
            answer: el.querySelector('.chain-answer').value
        });
    });
    if(steps.length < 1) { showToast('至少需要一个步骤', 'error'); return; }
    $.post('ajax_customer.php?act=cs_save_chain', {
        chain_id: chainId,
        chain_name: chainName,
        is_hotkey: document.getElementById('chain_is_hotkey').value,
        status: document.getElementById('chain_status').value,
        steps: steps
    }, function(data) {
        showToast(data.msg, data.code == 1 ? 'success' : 'error');
        if(data.code == 1) { closeChainModal(); loadChainList(); }
    }, 'json');
}

function deleteChain(chainId) {
    if(!confirm('确认删除此连续问答链？')) return;
    $.post('ajax_customer.php?act=cs_delete_chain', {chain_id: chainId}, function(data) {
        showToast(data.msg, data.code == 1 ? 'success' : 'error');
        if(data.code == 1) loadChainList();
    }, 'json');
}

// ========== 工具函数 ==========
function escHtml(s) { var d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
function escAttr(s) { return String(s).replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/'/g,'&#39;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }

// ========== 图片上传功能 ==========
function insertQaImage() {
    document.getElementById('qa_image_input').click();
}

function uploadQaImage(input) {
    if(!input.files[0]) return;
    var fd = new FormData();
    fd.append('file', input.files[0]);
    showLoading();
    $.ajax({
        type: 'POST', url: 'ajax_customer.php?act=cs_upload_content_image',
        data: fd, processData: false, contentType: false, dataType: 'json',
        success: function(data) {
            hideLoading();
            if(data.code == 1) {
                var textarea = document.getElementById('qa_answer');
                var imgTag = '<img src="' + data.url + '" style="max-width:100%;height:auto;">';
                insertAtCursor(textarea, imgTag);
                showToast('图片已插入', 'success');
            } else {
                showToast(data.msg, 'error');
            }
            input.value = '';
        },
        error: function() { hideLoading(); showToast('上传失败', 'error'); }
    });
}

function insertQaLink() {
    var url = prompt('请输入链接地址：', 'https://');
    if(!url) return;
    var text = prompt('请输入链接文本：', '');
    if(text === null) return;
    var linkTag = '<a href="' + escAttr(url) + '" target="_blank">' + escHtml(text || url) + '</a>';
    var textarea = document.getElementById('qa_answer');
    insertAtCursor(textarea, linkTag);
}

function insertChainImage(idx) {
    var input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = function() {
        if(!input.files[0]) return;
        var fd = new FormData();
        fd.append('file', input.files[0]);
        showLoading();
        $.ajax({
            type: 'POST', url: 'ajax_customer.php?act=cs_upload_content_image',
            data: fd, processData: false, contentType: false, dataType: 'json',
            success: function(data) {
                hideLoading();
                if(data.code == 1) {
                    var stepEl = document.getElementById('chain_step_' + idx);
                    var textarea = stepEl.querySelector('.chain-answer');
                    var imgTag = '<img src="' + data.url + '" style="max-width:100%;height:auto;">';
                    insertAtCursor(textarea, imgTag);
                    showToast('图片已插入', 'success');
                } else {
                    showToast(data.msg, 'error');
                }
            },
            error: function() { hideLoading(); showToast('上传失败', 'error'); }
        });
    };
    input.click();
}

function insertChainLink(idx) {
    var url = prompt('请输入链接地址：', 'https://');
    if(!url) return;
    var text = prompt('请输入链接文本：', '');
    if(text === null) return;
    var linkTag = '<a href="' + escAttr(url) + '" target="_blank">' + escHtml(text || url) + '</a>';
    var stepEl = document.getElementById('chain_step_' + idx);
    var textarea = stepEl.querySelector('.chain-answer');
    insertAtCursor(textarea, linkTag);
}

function insertAtCursor(textarea, text) {
    var start = textarea.selectionStart;
    var end = textarea.selectionEnd;
    var value = textarea.value;
    textarea.value = value.substring(0, start) + text + value.substring(end);
    textarea.selectionStart = textarea.selectionEnd = start + text.length;
    textarea.focus();
}

// ========== 留言管理 ==========
var feedbackPage = 1;
var selectedFeedback = [];

function loadFeedbackList(page) {
    feedbackPage = page || 1;
    var status = document.getElementById('feedback_status_filter').value;
    $.post('ajax_customer.php?act=cs_get_feedback_list', {page: feedbackPage, pagesize: 10, status: status}, function(data) {
        var html = '';
        selectedFeedback = [];
        document.getElementById('feedback_select_all').checked = false;

        if(!data || !data.data) {
            document.getElementById('feedback_tbody').innerHTML = '<tr><td colspan="8" class="px-4 py-8 text-center text-gray-400">加载失败</td></tr>';
            return;
        }

        if(data.msg) {
            document.getElementById('feedback_tbody').innerHTML = '<tr><td colspan="8" class="px-4 py-8 text-center text-orange-500"><i class="fas fa-exclamation-triangle mr-2"></i>' + escHtml(data.msg) + '</td></tr>';
            document.getElementById('feedback_pagination').innerHTML = '';
            return;
        }

        if(data.data.length === 0) {
            html = '<tr><td colspan="8" class="px-4 py-8 text-center text-gray-400">暂无留言</td></tr>';
        }
        for(var i = 0; i < data.data.length; i++) {
            var d = data.data[i];
            var content = d.content || '';
            var textOnly = content.replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ');
            var contentShort = textOnly.length > 30 ? textOnly.substring(0, 30) + '...' : textOnly;
            var hasImages = content.indexOf('<img') !== -1 ? ' <span class="text-blue-500">[有图片]</span>' : '';
            var statusClass = d.status == '0' ? 'bg-yellow-50 text-yellow-600' : (d.status == '1' ? 'bg-blue-50 text-blue-600' : 'bg-green-50 text-green-600');
            var statusText = d.status == '0' ? '待处理' : (d.status == '1' ? '正在处理' : '已处理');
            html += '<tr class="border-b border-gray-100 hover:bg-gray-50">';
            html += '<td class="px-4 py-3 text-center"><input type="checkbox" class="feedback-checkbox" value="' + d.id + '" onchange="updateFeedbackSelect()"></td>';
            html += '<td class="px-4 py-3">' + d.id + '</td>';
            html += '<td class="px-4 py-3">' + escHtml(d.user_name || '用户' + d.user_id) + '</td>';
            html += '<td class="px-4 py-3 text-gray-500">' + escHtml(d.user_email || '-') + '</td>';
            html += '<td class="px-4 py-3 text-gray-500" title="' + escAttr(textOnly) + '">' + escHtml(contentShort) + hasImages + '</td>';
            html += '<td class="px-4 py-3 text-center"><button onclick="setFeedbackStatus(' + d.id + ',' + d.status + ')" class="px-2 py-1 text-xs rounded-full cursor-pointer ' + statusClass + '">' + statusText + '</button></td>';
            html += '<td class="px-4 py-3 text-center text-gray-400">' + (d.addtime || '-') + '</td>';
            html += '<td class="px-4 py-3 text-center whitespace-nowrap">';
            html += '<button onclick="showFeedbackModal(' + d.id + ')" class="text-blue-600 hover:text-blue-800 text-xs mr-2"><i class="fas fa-reply"></i> 回复</button>';
            html += '<button onclick="deleteFeedback(' + d.id + ')" class="text-red-600 hover:text-red-800 text-xs"><i class="fas fa-trash"></i></button>';
            html += '</td></tr>';
        }
        document.getElementById('feedback_tbody').innerHTML = html;
        var pHtml = '<span class="text-sm text-gray-500">共 ' + (data.total || 0) + ' 条</span><div class="flex gap-1">';
        var endPage = data.end || 1;
        for(var p = 1; p <= endPage; p++) {
            pHtml += '<button onclick="loadFeedbackList(' + p + ')" class="px-3 py-1 text-sm rounded ' + (p == data.page ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200') + '">' + p + '</button>';
        }
        pHtml += '</div>';
        document.getElementById('feedback_pagination').innerHTML = pHtml;
    }, 'json').fail(function(xhr, status, error) {
        document.getElementById('feedback_tbody').innerHTML = '<tr><td colspan="8" class="px-4 py-8 text-center text-red-500">加载失败: ' + error + '</td></tr>';
    });
}

function toggleFeedbackSelectAll() {
    var checked = document.getElementById('feedback_select_all').checked;
    document.querySelectorAll('.feedback-checkbox').forEach(function(cb) {
        cb.checked = checked;
    });
    updateFeedbackSelect();
}

function updateFeedbackSelect() {
    selectedFeedback = [];
    document.querySelectorAll('.feedback-checkbox:checked').forEach(function(cb) {
        selectedFeedback.push(cb.value);
    });
}

function deleteSelectedFeedback() {
    if(selectedFeedback.length === 0) {
        showToast('请先选择要删除的留言', 'error');
        return;
    }
    if(!confirm('确认删除选中的 ' + selectedFeedback.length + ' 条留言？')) return;
    $.post('ajax_customer.php?act=cs_delete_feedback', {ids: selectedFeedback.join(',')}, function(data) {
        showToast(data.msg, data.code == 1 ? 'success' : 'error');
        if(data.code == 1) loadFeedbackList(feedbackPage);
    }, 'json');
}

function deleteFeedback(id) {
    if(!confirm('确认删除此留言？')) return;
    $.post('ajax_customer.php?act=cs_delete_feedback', {ids: id}, function(data) {
        showToast(data.msg, data.code == 1 ? 'success' : 'error');
        if(data.code == 1) loadFeedbackList(feedbackPage);
    }, 'json');
}

function setFeedbackStatus(id, currentStatus) {
    var newStatus = (currentStatus + 1) % 3;
    $.post('ajax_customer.php?act=cs_set_feedback_status', {id: id, status: newStatus}, function(data) {
        showToast(data.msg, data.code == 1 ? 'success' : 'error');
        if(data.code == 1) loadFeedbackList(feedbackPage);
    }, 'json');
}

function showFeedbackModal(id) {
    $.post('ajax_customer.php?act=cs_get_feedback_detail', {id: id}, function(data) {
        if(data.code == 1) {
            document.getElementById('feedback_id').value = data.data.id;
            document.getElementById('feedback_conversation').innerHTML = formatFeedbackConversation(data.data.content, data.data.reply, data.data.user_qq || '');
            document.getElementById('feedback_reply').value = '';
            document.getElementById('feedbackModal').classList.remove('hidden');
            setTimeout(function() {
                var box = document.getElementById('feedback_conversation');
                if (box) box.scrollTop = box.scrollHeight;
            }, 0);
        } else {
            showToast(data.msg, 'error');
        }
    }, 'json');
}

function closeFeedbackModal() {
    document.getElementById('feedbackModal').classList.add('hidden');
}

function formatFeedbackConversation(contentHtml, replyHtml, userQq) {
    var items = [];
    var userItems = parseFeedbackSegments(contentHtml, 'user');
    var botItems = parseFeedbackSegments(replyHtml, 'bot');
    items = items.concat(userItems, botItems);
    if (items.length === 0) return '暂无对话';
    var adminQq = '<?php echo $conf['qq'] ?? '1223134470'; ?>';
    var adminAvatar = '//q4.qlogo.cn/headimg_dl?dst_uin=' + encodeURIComponent(adminQq) + '&spec=100';
    var userAvatar = '';
    if (/^\d+$/.test(String(userQq || ''))) {
        userAvatar = '//q4.qlogo.cn/headimg_dl?dst_uin=' + encodeURIComponent(userQq) + '&spec=100';
    }

    items.sort(function(a, b) {
        if (a.ts !== b.ts) return a.ts - b.ts;
        if (a.role !== b.role) return a.role === 'user' ? -1 : 1;
        return a.seq - b.seq;
    });

    var out = [];
    for (var i = 0; i < items.length; i++) {
        var it = items[i];
        if (it.role === 'user') {
            out.push(
                '<div class="flex justify-start items-start gap-2">' +
                    (userAvatar ?
                        '<img src="' + userAvatar + '" class="w-7 h-7 rounded-full border border-white shadow-sm object-cover">' :
                        '<div class="w-7 h-7 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center text-xs border border-white shadow-sm"><i class="fas fa-user"></i></div>'
                    ) +
                    '<div class="max-w-[78%] bg-blue-500 text-white rounded-xl px-3 py-2 shadow-sm">' + it.html + '</div>' +
                '</div>'
            );
        } else {
            out.push(
                '<div class="flex justify-end items-start gap-2">' +
                    '<div class="max-w-[78%] bg-white border border-gray-200 text-gray-800 rounded-xl px-3 py-2 shadow-sm">' + it.html + '</div>' +
                    '<img src="' + adminAvatar + '" class="w-7 h-7 rounded-full border border-white shadow-sm object-cover">' +
                '</div>'
            );
        }
    }
    return out.join('');
}

function parseFeedbackSegments(html, role) {
    var src = String(html || '');
    if (!src) return [];
    var parts = src.split(/<hr[^>]*>/ig);
    var out = [];
    for (var i = 0; i < parts.length; i++) {
        var part = String(parts[i] || '').trim();
        if (!part) continue;
        var m = part.match(/（(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})）/);
        var ts = m ? Date.parse(m[1].replace(/-/g, '/')) : (Date.now() + i);
        if (isNaN(ts)) ts = Date.now() + i;
        out.push({ role: role, html: part, ts: ts, seq: i });
    }
    return out;
}

function insertFeedbackImage() {
    document.getElementById('feedback_image_input').click();
}

function uploadFeedbackImage(input) {
    if(!input.files[0]) return;
    var fd = new FormData();
    fd.append('file', input.files[0]);
    showLoading();
    $.ajax({
        type: 'POST', url: 'ajax_customer.php?act=cs_upload_content_image',
        data: fd, processData: false, contentType: false, dataType: 'json',
        success: function(data) {
            hideLoading();
            if(data.code == 1) {
                var imgTag = '<img src="' + data.url + '" style="max-width:100%;border-radius:8px;margin:4px 0;">';
                var textarea = document.getElementById('feedback_reply');
                insertAtCursor(textarea, imgTag);
            } else {
                showToast(data.msg, 'error');
            }
        },
        error: function() { hideLoading(); showToast('上传失败', 'error'); }
    });
    input.value = '';
}

function saveFeedbackReply(status) {
    var id = document.getElementById('feedback_id').value;
    var reply = document.getElementById('feedback_reply').value;
    if(!reply.trim()) {
        showToast('请输入回复内容', 'error');
        return;
    }
    showLoading();
    $.post('ajax_customer.php?act=cs_reply_feedback', {id: id, reply: reply, status: status}, function(data) {
        hideLoading();
        showToast(data.msg, data.code == 1 ? 'success' : 'error');
        if(data.code == 1) {
            closeFeedbackModal();
            loadFeedbackList(feedbackPage);
        }
    }, 'json');
}

var items = document.querySelectorAll("select[default]");
for(var i = 0; i < items.length; i++) {
    items[i].value = items[i].getAttribute("default") || items[i].options[0].value;
}
</script>
