<template>
  <div class="knowledge-page">
    <div class="page-header">
      <div class="header-left">
        <div class="page-title">📚 知识库管理</div>
        <p class="page-desc">AI 驱动的企业知识管理，智能问答与知识沉淀</p>
      </div>
      <div class="header-actions">
        <button class="btn btn-secondary" @click="showImportModal = true">
          <i class="fas fa-file-import"></i> 批量导入
        </button>
        <button class="btn btn-primary" @click="addKnowledgeDocument()">
          <i class="fas fa-plus"></i> 添加知识
        </button>
      </div>
    </div>

    <!-- Stats -->
    <div class="stats-row">
      <div class="stat-card-lg">
        <div class="stat-icon-lg green"><i class="fas fa-check-circle"></i></div>
        <div class="stat-content-lg">
          <h3>{{ formatNumber(knowledgeStats.totalDatasets) }}</h3>
          <p>知识库总数</p>
        </div>
      </div>
      <div class="stat-card-lg">
        <div class="stat-icon-lg purple"><i class="fas fa-folder"></i></div>
        <div class="stat-content-lg">
          <h3>{{ knowledgeStats.totalDocuments }}</h3>
          <p>文档总数</p>
        </div>
      </div>
      <div class="stat-card-lg">
        <div class="stat-icon-lg blue"><i class="fas fa-book"></i></div>
        <div class="stat-content-lg">
          <h3>{{ knowledgeStats.totalChunks }}</h3>
          <p>文本块总数</p>
        </div>
      </div>
      <div class="stat-card-lg">
        <div class="stat-icon-lg orange"><i class="fas fa-chart-line"></i></div>
        <div class="stat-content-lg">
          <h3>+{{ knowledgeStats.thisWeekNewChunks }}</h3>
          <p>本周新增文本块数</p>
        </div>
      </div>
    </div>

    <!-- AI Learning Progress -->
    <!-- <div class="learning-section">
      <div class="learning-header">
        <h3><i class="fas fa-graduation-cap"></i> AI 学习进度</h3>
        <div class="learning-status">
          <span class="status-dot active"></span>
          <span>持续学习中</span>
        </div>
      </div>
      <div class="learning-stats">
        <div class="learning-item">
          <div class="learning-label">产品知识掌握度</div>
          <div class="learning-progress">
            <div class="progress-bar">
              <div class="progress-fill" style="width: 92%"></div>
            </div>
            <span class="progress-value">92%</span>
          </div>
        </div>
        <div class="learning-item">
          <div class="learning-label">价格政策理解度</div>
          <div class="learning-progress">
            <div class="progress-bar">
              <div class="progress-fill" style="width: 88%"></div>
            </div>
            <span class="progress-value">88%</span>
          </div>
        </div>
        <div class="learning-item">
          <div class="learning-label">行业知识覆盖度</div>
          <div class="learning-progress">
            <div class="progress-bar">
              <div class="progress-fill" style="width: 76%"></div>
            </div>
            <span class="progress-value">76%</span>
          </div>
        </div>
        <div class="learning-item">
          <div class="learning-label">客户问答准确率</div>
          <div class="learning-progress">
            <div class="progress-bar">
              <div class="progress-fill success" style="width: 94%"></div>
            </div>
            <span class="progress-value success">94%</span>
          </div>
        </div>
      </div>
    </div> -->

    <!-- Tabs -->
    <div class="tabs-container">
      <div class="tabs">
        <div v-for="tab in tabs" :key="tab.key" 
             class="tab-item"
             :class="{ active: activeTab === tab.key }"
             @click="changeTab(tab.key)">
          <i :class="tab.icon"></i>
          {{ tab.label }}
          <span class="tab-count">{{ tab.count }}</span>
        </div>
      </div>
      <div class="tab-actions">
        <div class="search-box">
          <i class="fas fa-search search-icon"></i>
          <input type="text" v-model="searchQuery" class="search-input" placeholder="搜索知识...">
        </div>
      </div>
    </div>

    <!-- 知识分类 Tab -->
    <div v-if="activeTab === 'categories'" class="section">
      <div class="category-grid">
        <div v-for="category in categories" :key="category.id"
             class="category-card"
             @click="openCategory(category)">
          <!-- <div class="category-header">
            <div class="category-icon" :style="{ background: category.iconBg }">{{ category.icon }}</div>
            <div class="category-badge" v-if="category.trending">
              <i class="fas fa-fire"></i> 热门
            </div>
          </div> -->
          <div class="category-name">{{ category.name }}</div>
          <div class="category-desc">{{ category.description }}</div>
          <div class="category-stats">
            <div class="category-stat">
              <span class="stat-value">{{ category.document_count }}</span>
              <span class="stat-label">知识点</span>
            </div>
            <div class="category-stat">
              <span class="stat-value">{{ category.queries }}</span>
              <span class="stat-label">本月查询</span>
            </div>
            <div class="category-stat">
              <span class="stat-value">{{ category.accuracy }}%</span>
              <span class="stat-label">准确率</span>
            </div>
          </div>
          <div class="category-footer">
            <span class="update-time">更新于 {{ category.timeip }}</span>
            <i class="fas fa-chevron-right"></i>
          </div>
        </div>
      </div>
      <div class="pagination-area">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="1000">
        </el-pagination>
      </div>
      
    </div>

    <!-- 全部知识 Tab -->
    <div v-if="activeTab === 'all'" class="section">
      <div class="knowledge-list">
        <div v-for="item in knowledgeList" :key="item.id"
             class="knowledge-card"
             @click="showKnowledgeDetail(item)">
          <!-- <div class="knowledge-icon" :style="{ background: item.iconBg }">{{ item.icon }}</div> -->
          <div class="knowledge-content">
            <div class="knowledge-header">
              <div class="knowledge-question">{{ item.name }}</div>
              <!-- <span class="knowledge-category" :style="{ background: item.iconBg }">{{ item.categoryName }}</span> -->
            </div>
            <!-- <div class="knowledge-answer">{{ item.text }}</div> -->
            <!-- <div class="knowledge-meta">
              <span><i class="fas fa-eye"></i> {{ item.views }}次查看</span>
              <span><i class="fas fa-thumbs-up"></i> {{ item.likes }}次好评</span>
              <span><i class="fas fa-clock"></i> {{ item.time }}</span>
            </div> -->
          </div>
          <div class="knowledge-actions" @click.stop>
            <button class="btn btn-secondary btn-sm" @click="editKnowledge(item)">
              <i class="fas fa-edit"></i>
            </button>
            <button class="btn btn-secondary btn-sm" @click="deleteKnowledge(item)">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 问答记录 Tab -->
    <div v-if="activeTab === 'qa'" class="section">
      <div class="qa-section">
        <div class="qa-header">
          <h4><i class="fas fa-comments"></i> 智能问答记录</h4>
          <div class="qa-filters">
            <!-- <select v-model="qaFilter" class="filter-select">
              <option value="all">全部来源</option>
              <option value="customer">客户问答</option>
              <option value="internal">内部查询</option>
            </select> -->
            <select v-model="qaRating" class="filter-select">
              <option value="all">全部评价</option>
              <option value="positive">好评</option>
              <option value="negative">待优化</option>
            </select>
          </div>
        </div>
        <div class="qa-list">
          <div v-for="qa in filteredQA" :key="qa.id" class="qa-card">
            <!-- <div class="qa-source">
              <span class="source-badge" :class="qa.sourceType">{{ qa.sourceLabel }}</span>
            </div> -->
            <div class="qa-content">
              <div class="qa-question">
                <span class="qa-label">问</span>
                {{ qa.query }}
              </div>
              <div class="qa-answer-block">
                <span class="qa-label answer">答</span>
                {{ qa.answer }}
              </div>
            </div>
            <div class="qa-footer">
              <div class="qa-time">{{ qa.time }}</div>
              <div class="qa-rating">
                <button class="rating-btn" :class="{ active: qa.rating === 'positive' }" @click="rateQA(qa, 'positive')">
                  <i class="fas fa-thumbs-up"></i><span style="margin-left: 2px;">{{qa.agree}}</span>
                </button>
                <button class="rating-btn" :class="{ active: qa.rating === 'negative' }" @click="rateQA(qa, 'negative')">
                  <i class="fas fa-thumbs-down"></i><span style="margin-left: 2px;">{{qa.disagree}}</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- AI训练 Tab -->
    <div v-if="activeTab === 'training'" class="section">
      <div class="training-section">
        <div class="training-header">
          <h4><i class="fas fa-dumbbell"></i> AI 训练任务</h4>
          <button class="btn btn-primary btn-sm" @click="showTrainModal = true">
            <i class="fas fa-plus"></i> 新建训练
          </button>
        </div>
        <div class="training-list">
          <div v-for="task in trainingTasks" :key="task.id" class="training-card">
            <div class="training-icon" :class="task.status==0?'running':'completed'">
              <i :class="task.status === 0 ? 'fas fa-spinner fa-spin' : 'fas fa-check'"></i>
            </div>
            <div class="training-content">
              <div class="training-name">{{ task.name }}</div>
              <div class="training-desc">{{ task.description }}</div>
              <div class="training-progress" v-if="task.status === 0">
                <div class="progress-bar">
                  <div class="progress-fill" :style="{ width: task.progress + '%' }"></div>
                </div>
                <span class="progress-text">{{ task.progress }}%</span>
              </div>
            </div>
            <div class="training-stats">
              <div class="training-stat">
                <span class="value">{{ task.totalDocumentCount }}</span>
                <span class="label">文档数</span>
              </div>
              <div class="training-stat">
                <span class="value">{{ task.completedDcumentCount }}</span>
                <span class="label">已学习</span>
              </div>
            </div>
            <div class="training-status" :class="task.status==0?'running':'completed'">
              {{ task.status==0?'训练中':'已完成' }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 设置 Tab -->
    <div v-if="activeTab === 'settings'" class="section">
      <div class="settings-section">
        <div class="settings-card">
          <div class="settings-header">
            <i class="fas fa-robot"></i>
            <div class="settings-title">AI 回复设置</div>
          </div>
          <div class="settings-content">
            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">自动回复客户问题</div>
                <div class="setting-desc">当客户咨询时，AI 自动从知识库匹配答案</div>
              </div>
              <div class="setting-toggle active" @click="toggleSetting('autoReply')">
                <div class="toggle-slider"></div>
              </div>
            </div>
            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">知识库实时更新</div>
                <div class="setting-desc">新知识添加后立即生效，无需重新训练</div>
              </div>
              <div class="setting-toggle active" @click="toggleSetting('realtimeUpdate')">
                <div class="toggle-slider"></div>
              </div>
            </div>
            <div class="setting-item">
              <div class="setting-info">
                <div class="setting-label">置信度阈值</div>
                <div class="setting-desc">低于此阈值的答案将标记为待人工确认</div>
              </div>
              <div class="setting-value">
                <input type="number" class="threshold-input" v-model="confidenceThreshold" min="0" max="100">
                <span>%</span>
              </div>
            </div>
          </div>
        </div>

        <div class="settings-card">
          <div class="settings-header">
            <i class="fas fa-database"></i>
            <div class="settings-title">知识库同步</div>
          </div>
          <div class="settings-content">
            <div class="sync-status">
              <div class="sync-item">
                <i class="fas fa-check-circle success"></i>
                <span>产品目录已同步 ({{ syncStatus.products }} 条)</span>
              </div>
              <div class="sync-item">
                <i class="fas fa-check-circle success"></i>
                <span>价格表已同步 ({{ syncStatus.prices }} 条)</span>
              </div>
              <div class="sync-item">
                <i class="fas fa-check-circle success"></i>
                <span>客户 FAQ 已同步 ({{ syncStatus.faq }} 条)</span>
              </div>
              <div class="sync-item warning">
                <i class="fas fa-clock"></i>
                <span>行业报告待更新 (上次同步: {{ syncStatus.lastSync }})</span>
              </div>
            </div>
            <button class="btn btn-primary sync-btn" @click="syncKnowledge">
              <i class="fas fa-sync"></i> 立即同步
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Add Knowledge Modal -->
    <div v-if="showAddModal" class="modal-overlay" @click.self="showAddModal = false">
      <div class="modal add-modal">
        <div class="modal-header">
          <div class="modal-title"><i class="fas fa-plus"></i> 添加知识</div>
          <button class="modal-close" @click="showAddModal = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label class="form-label">问题/关键词 <span class="required">*</span></label>
            <input type="text" class="form-input" v-model="newKnowledge.name" placeholder="例如：MOQ最小起订量是多少？">
          </div>
          <div class="form-group">
            <label class="form-label">答案/内容 <span class="required">*</span></label>
            <textarea class="form-textarea" v-model="newKnowledge.text" rows="4" placeholder="输入详细答案..."></textarea>
          </div>
          <div class="form-group">
            <label class="form-label">知识分类 <span class="required">*</span></label>
            <select class="form-select" v-model="newKnowledge.dataset_id">
              <option value="">选择分类</option>
              <option v-for="cat in categories" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
            </select>
          </div>
            <!-- <div class="form-group">
              <label class="form-label">关键词标签</label>
              <input type="text" class="form-input" v-model="newKnowledge.tags" placeholder="用逗号分隔多个标签">
            </div> -->
          <!-- <div class="form-group">
            <label class="form-label">关联问题（可选）</label>
            <input type="text" class="form-input" v-model="newKnowledge.relatedQuestions" placeholder="例如：起订量,MOQ,最小订单">
          </div> -->
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showAddModal = false">取消</button>
          <button class="btn btn-primary" @click="addKnowledge"><i class="fas fa-plus"></i> 添加</button>
        </div>
      </div>
    </div>

    <!-- Knowledge Detail Modal -->
    <div v-if="showDetailModal && selectedKnowledge" class="modal-overlay" @click.self="showDetailModal = false">
      <div class="modal detail-modal">
        <div class="modal-header">
          <div class="modal-title">
            <span class="detail-icon" :style="{ background: selectedKnowledge.iconBg }">{{ selectedKnowledge.icon }}</span>
            <div>
              <h3>{{ selectedKnowledge.question }}</h3>
              <p>{{ selectedKnowledge.categoryName }}</p>
            </div>
          </div>
          <button class="modal-close" @click="showDetailModal = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">
          <div class="detail-section">
            <div class="detail-label"><i class="fas fa-lightbulb"></i> 答案内容</div>
            <div class="detail-content">{{ selectedKnowledge.answer }}</div>
          </div>
          <div class="detail-section" v-if="selectedKnowledge.extendedAnswer">
            <div class="detail-label"><i class="fas fa-file-alt"></i> 扩展说明</div>
            <div class="detail-content extended">{{ selectedKnowledge.extendedAnswer }}</div>
          </div>
          <div class="detail-section">
            <div class="detail-label"><i class="fas fa-tags"></i> 关键词标签</div>
            <div class="detail-tags">
              <span v-for="tag in selectedKnowledge.tags" :key="tag" class="tag">{{ tag }}</span>
            </div>
          </div>
          <div class="detail-section" v-if="selectedKnowledge.relatedQuestions && selectedKnowledge.relatedQuestions.length">
            <div class="detail-label"><i class="fas fa-link"></i> 相关问题</div>
            <div class="related-questions">
              <div v-for="(q, idx) in selectedKnowledge.relatedQuestions" :key="idx" class="related-item">{{ q }}</div>
            </div>
          </div>
          <div class="detail-stats-row">
            <div class="detail-stat">
              <i class="fas fa-eye"></i>
              <span>{{ selectedKnowledge.views }} 次查看</span>
            </div>
            <div class="detail-stat">
              <i class="fas fa-thumbs-up"></i>
              <span>{{ selectedKnowledge.likes }} 次好评</span>
            </div>
            <div class="detail-stat">
              <i class="fas fa-clock"></i>
              <span>更新于 {{ selectedKnowledge.timeip }}</span>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showDetailModal = false">关闭</button>
          <button class="btn btn-secondary" @click="editKnowledge(selectedKnowledge)"><i class="fas fa-edit"></i> 编辑</button>
          <button class="btn btn-primary" @click="optimizeAnswer(selectedKnowledge)"><i class="fas fa-sync"></i> 优化答案</button>
        </div>
      </div>
    </div>

    <!-- Import Modal -->
    <div v-if="showImportModal" class="modal-overlay" @click.self="showImportModal = false">
      <div class="modal import-modal">
        <div class="modal-header">
          <div class="modal-title"><i class="fas fa-file-import"></i> 批量导入知识</div>
          <button class="modal-close" @click="showImportModal = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">
          <div class="import-zone">
            <el-upload
              class="upload-demo"
              drag
              action="https://jsonplaceholder.typicode.com/posts/"
              multiple>
              <div class="import-icon"><i class="fas fa-cloud-upload-alt"></i></div>
              <div class="import-text">拖拽文件到此处，或点击上传</div>
              <div class="import-formats">支持 Excel、CSV、JSON、PDF 格式</div>
            </el-upload>
          </div>
          <div class="import-options">
            <div class="import-option">
              <i class="fas fa-file-excel"></i>
              <span>Excel 模板</span>
              <button class="btn btn-secondary btn-sm">下载模板</button>
            </div>
            <div class="import-option">
              <i class="fas fa-file-code"></i>
              <span>JSON 格式</span>
              <button class="btn btn-secondary btn-sm">查看示例</button>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showImportModal = false">取消</button>
          <button class="btn btn-primary" @click="startImport"><i class="fas fa-upload"></i> 开始导入</button>
        </div>
      </div>
    </div>

    <!-- 新建训练 -->
    <div v-if="showTrainModal" class="modal-overlay" @click.self="showTrainModal = false">
      <div class="modal import-modal">
        <div class="modal-header">
          <div class="modal-title"><i class="fas fa-file-import"></i> 新建训练</div>
          <button class="modal-close" @click="showTrainModal = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label class="form-label">知识分类 <span class="required">*</span></label>
            <select class="form-select" v-model="trainKnowledge.datasetId">
              <option value="">选择分类</option>
              <option v-for="cat in categories" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">标题 <span class="required">*</span></label>
            <input type="text" class="form-input" maxlength="30" v-model="trainKnowledge.name" placeholder="30字内">
          </div>
          <div class="form-group">
            <label class="form-label">备注信息 <span class="required">*</span></label>
            <textarea class="form-textarea" v-model="trainKnowledge.description" rows="4" maxlength="60" placeholder="请输入内容60字内"></textarea>
          </div>
          
          <div class="import-zone">
            <el-upload
              class="upload-demo"
              drag
              action=""
              :auto-upload="false"
              :show-file-list="false"
              @change="handleFileChange"
              multiple>
              <div class="import-icon"><i class="fas fa-cloud-upload-alt"></i></div>
              <div class="import-text">拖拽文件到此处，或点击上传</div>
              <div class="import-formats">支持 Excel、CSV、JSON、PDF 格式</div>
            </el-upload>
          </div>
          <div class="import-options">
            <div class="import-option" v-for="item in fileListRaw" :key="item.name">
              <i class="fas fa-file-excel"></i>
              <span>{{ item.name }}</span>
              <button icon="el-icon-edit"></button>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showTrainModal = false">取消</button>
          <button class="btn btn-primary" @click="startTrain"><i class="fas fa-upload"></i>添加</button>
        </div>
      </div>
    </div>

    <!-- Toast -->
    <transition name="toast">
      <div v-if="showToast" class="toast" :class="toastType">
        <i :class="toastType === 'success' ? 'fas fa-check-circle' : 'fas fa-info-circle'"></i>
        {{ toastMessage }}
        
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { knowledgeDatasets,knowledgeDocuments,createKnowledge,chatMessages,baseTraining,creatTraining,baseStatistics } from '../api/knowledge'
import { formatTimeAgo } from '@/utils/time'
import { ElMessage } from 'element-plus'

const showAddModal = ref(false)
const showDetailModal = ref(false)
const showImportModal = ref(false)
const showTrainModal = ref(false)
const selectedKnowledge = ref(null)
const activeTab = ref('categories')
const searchQuery = ref('')
const qaFilter = ref('all')
const qaRating = ref('all')
const confidenceThreshold = ref(70)
const showToast = ref(false)
const toastMessage = ref('')
const toastType = ref('success')


const syncStatus = {
  products: 234,
  prices: 156,
  faq: 89,
  lastSync: '2天前'
}

const tabs = ref([
  { key: 'categories', label: '知识分类', count: 0, icon: 'fas fa-folder' },
  { key: 'all', label: '全部知识', count: 0, icon: 'fas fa-book' },
  { key: 'qa', label: '问答记录', count: 0, icon: 'fas fa-comments' },
  { key: 'training', label: 'AI 训练', count: 0, icon: 'fas fa-dumbbell' },
  // { key: 'settings', label: '设置', count: 0, icon: 'fas fa-cog' }
])

const newKnowledge = ref({
  dataset_id: '',
  text: '',
  name: '',
  indexing_technique: "high_quality",
  doc_form: "qa_model",
  doc_language:"Chinese Simplified"
})

// const categories = ref([
//   { id: 1, icon: '📦', iconBg: 'rgba(99, 102, 241, 0.2)', name: '产品知识', description: '产品规格、型号、功能特性', count: 234, queries: 1256, accuracy: 96, trending: true, updatedAt: '2小时前' },
//   { id: 2, icon: '💰', iconBg: 'rgba(16, 185, 129, 0.2)', name: '价格政策', description: '价格体系、折扣规则、付款条件', count: 156, queries: 892, accuracy: 98, trending: false, updatedAt: '昨天' },
//   { id: 3, icon: '🚚', iconBg: 'rgba(245, 158, 11, 0.2)', name: '物流信息', description: '交期、运费、物流方式', count: 89, queries: 567, accuracy: 92, trending: false, updatedAt: '3天前' },
//   { id: 4, icon: '📋', iconBg: 'rgba(139, 92, 246, 0.2)', name: '商务条款', description: '合同条款、质保政策、售后服务', count: 178, queries: 445, accuracy: 94, trending: false, updatedAt: '昨天' },
//   { id: 5, icon: '🏭', iconBg: 'rgba(6, 182, 212, 0.2)', name: '行业知识', description: '行业趋势、技术标准、认证信息', count: 245, queries: 334, accuracy: 88, trending: true, updatedAt: '1周前' },
//   { id: 6, icon: '🌍', iconBg: 'rgba(236, 72, 153, 0.2)', name: '市场信息', description: '市场行情、竞争对手、客户案例', count: 167, queries: 289, accuracy: 85, trending: false, updatedAt: '5天前' },
//   { id: 7, icon: '🔧', iconBg: 'rgba(59, 130, 246, 0.2)', name: '技术参数', description: '技术规格、性能指标、兼容性', count: 98, queries: 456, accuracy: 97, trending: false, updatedAt: '2天前' },
//   { id: 8, icon: '❓', iconBg: 'rgba(148, 163, 184, 0.2)', name: '常见问题', description: '客户高频问题及标准回答', count: 80, queries: 1234, accuracy: 95, trending: true, updatedAt: '今天' }
// ])

// const knowledgeList = ref([
//   { id: 1, icon: '📦', iconBg: 'rgba(99, 102, 241, 0.2)', categoryName: '产品知识', question: 'MOQ最小起订量是多少？', answer: '标准产品MOQ为50件，定制产品MOQ为100件，具体视产品类型而定。', extendedAnswer: '对于常规库存产品，我们接受最低50件起订。定制产品由于需要单独开模和生产准备，最低起订量为100件。大客户可享受更灵活的起订量政策，请联系销售经理协商。', tags: ['MOQ', '起订量', '订单'], relatedQuestions: ['可以降低起订量吗？', '首单有优惠吗？'], views: 1234, likes: 89, time: '2小时前' },
//   { id: 2, icon: '🚚', iconBg: 'rgba(245, 158, 11, 0.2)', categoryName: '物流信息', question: '交期一般是多久？', answer: '常规产品15-20天，定制产品30-45天，加急订单可缩短至7天。', extendedAnswer: '标准产品通常有库存，交期15-20个工作日。定制产品需要根据复杂程度评估，一般为30-45天。如有紧急需求，我们提供加急服务，最快可7天交货，但需收取10-20%的加急费用。', tags: ['交期', '发货', '物流'], relatedQuestions: ['可以加急吗？', '运费谁承担？'], views: 987, likes: 67, time: '昨天' },
//   { id: 3, icon: '💰', iconBg: 'rgba(16, 185, 129, 0.2)', categoryName: '价格政策', question: '付款方式有哪些？', answer: '支持T/T、L/C、PayPal等多种付款方式，新客户首单建议30%预付款。', extendedAnswer: '我们接受电汇(T/T)、信用证(L/C)、PayPal、西联汇款等付款方式。对于老客户可提供月结30天账期。新客户首单建议预付30%，发货前付清尾款。大额订单可协商分期付款。', tags: ['付款', 'T/T', '信用证'], relatedQuestions: ['可以月结吗？', '支持什么货币？'], views: 876, likes: 54, time: '2天前' },
//   { id: 4, icon: '🔧', iconBg: 'rgba(59, 130, 246, 0.2)', categoryName: '技术参数', question: 'SSD的使用寿命是多久？', answer: '企业级SSD设计寿命为5-10年，写入寿命(TBW)根据容量不同。', extendedAnswer: '我们的企业级SSD采用高耐久性NAND闪存，设计寿命5-10年。1TB型号TBW为600TB，2TB型号为1200TB。在正常工作负载下，可稳定运行超过200万小时(MTBF)。', tags: ['SSD', '寿命', 'TBW'], relatedQuestions: ['如何查看剩余寿命？', '保修期多久？'], views: 654, likes: 45, time: '3天前' },
//   { id: 5, icon: '📋', iconBg: 'rgba(139, 92, 246, 0.2)', categoryName: '商务条款', question: '质保期是多久？', answer: '标准产品提供3年质保，企业级产品提供5年质保。', extendedAnswer: '消费级产品提供3年有限质保，企业级产品提供5年质保服务。质保期内非人为损坏可免费更换。我们提供全球联保服务，无论在哪购买均可享受本地化售后服务。', tags: ['质保', '售后', '保修'], relatedQuestions: ['质保包括哪些？', '如何申请保修？'], views: 543, likes: 38, time: '4天前' },
//   { id: 6, icon: '🏭', iconBg: 'rgba(6, 182, 212, 0.2)', categoryName: '行业知识', question: 'NVMe和SATA有什么区别？', answer: 'NVMe采用PCIe通道，速度更快延迟更低，适合高性能应用。', extendedAnswer: 'NVMe SSD通过PCIe总线直接与CPU通信，理论带宽可达32GB/s，延迟极低。SATA SSD受限于SATA接口，最大速度约600MB/s。对于需要高IOPS的应用场景，NVMe是更好的选择。', tags: ['NVMe', 'SATA', '技术'], relatedQuestions: ['如何选择接口？', '兼容性如何？'], views: 432, likes: 34, time: '5天前' }
// ])

// const qaRecords = ref([
//   { id: 1, sourceType: 'customer', sourceLabel: '客户问答', question: '你们的NVMe SSD支持哪些接口？', answer: '我们提供M.2 2280、M.2 2242和U.2三种接口规格，支持PCIe 4.0 x4总线，向下兼容PCIe 3.0。', time: '10分钟前', rating: 'positive' },
//   { id: 2, sourceType: 'internal', sourceLabel: '内部查询', question: '中东地区的主要竞争对手有哪些？', answer: '中东SSD市场主要竞争者包括Samsung、WD、Kingston以及本地品牌。我们在价格和交期方面有竞争优势。', time: '1小时前', rating: null },
//   { id: 3, sourceType: 'customer', sourceLabel: '客户问答', question: '能否提供样品测试？', answer: '可以提供样品，标准样品免费提供（限2片），定制样品需支付样品费（后续订单可抵扣）。', time: '2小时前', rating: 'positive' },
//   { id: 4, sourceType: 'customer', sourceLabel: '客户问答', question: '产品有CE认证吗？', answer: '所有出口产品均通过CE、FCC、RoHS认证，可提供认证证书副本。', time: '3小时前', rating: 'positive' },
//   { id: 5, sourceType: 'internal', sourceLabel: '内部查询', question: '上周最热门的产品是什么？', answer: '上周销量最高的是NVMe SSD 1TB企业级型号，其次是2TB消费级型号。', time: '昨天', rating: 'negative' }
// ])

// const trainingTasks = ref([
//   { id: 1, name: '新产品知识训练', description: '导入2024新品规格文档进行训练', status: 'running', progress: 68, documents: 45, learned: 31 },
//   { id: 2, name: '行业报告更新', description: '更新Q1存储行业市场报告数据', status: 'completed', progress: 100, documents: 12, learned: 12 },
//   { id: 3, name: '客户问答优化', description: '基于历史问答记录优化回复准确性', status: 'paused', progress: 35, documents: 234, learned: 82 }
// ])

const knowledgeStats = ref({
  totalDatasets:0,
  totalDocuments:0,
  totalChunks:0,
  thisWeekNewChunks:0,
})
// 获取汇总数
const getBaseStatistics = () => {
    baseStatistics().then(res => {
    knowledgeStats.value = res.result
    tabs.value[1].count = res.result.totalDocuments
    console.log('res :>> ', res);
  })
}
getBaseStatistics()


const changeTab = (tab)=>{
  activeTab.value = tab 
  if(tab =='qa'){
    getChatMessages()
  }
}
const categories = ref([])
// 获取知识分类
const getKnowledgeDatasets = () => {
    knowledgeDatasets({ pageIndex: 1, pageSize: 10 }).then(res => {
    categories.value = res.result.data
    res.result.data.forEach(el => {
      el.timeip = formatTimeAgo(el.updated_at)
    });
    tabs.value[0].count = res.result.total
    console.log('res :>> ', res);
  })
}
getKnowledgeDatasets()

const knowledgeList = ref([])
// 获取知识分类下的知识
const documentsParams = ref({})
const openCategory = (category) => {
  activeTab.value = 'all'
  searchQuery.value = category.name
  showToastMessage(`正在加载 ${category.name} 分类...`, 'success')
  documentsParams.value = {
    pageIndex:1,
    pageSize:10,
    dataset_id:category.id
  }
  knowledgeDocuments(documentsParams.value).then(res => {
    knowledgeList.value = res.result.data
    tabs.value[1].count = res.result.total
  })
}

const qaRecords = ref([])
// 获取问答记录
const chatParams=ref({
  pageIndex: 1, 
  pageSize: 10,
  keyword:'',
})
const getChatMessages = () => {
    chatMessages(chatParams.value).then(res => {
    tabs.value[2].count = res.result.total
    res.result.records.forEach(el => {
      el.time = formatTimeAgo(el.createdAt)
    });
    qaRecords.value = res.result.records
    console.log('res :>> ', res);
  })
}
getChatMessages()

const trainingTasks = ref([])
//获取ai训练列表
const trainingParams=ref({
  pageIndex: 1, 
  pageSize: 10,
  keyword:'',
})
const getTraining = () => {
    baseTraining(trainingParams.value).then(res => {
    tabs.value[3].count = res.result.total
    trainingTasks.value = res.result.records
    console.log('res :>> ', res);
  })
}
getTraining()

const fileListRaw = ref([])
const handleFileChange = (file, fileList) => {
  // 提取所有原生File对象
  fileListRaw.value = fileList.map(item => item.raw)
  console.log('当前选中所有文件：', fileListRaw.value)
}
const trainKnowledge = ref({
  datasetId: '',
  name: '',
  description: '',
})
const startTrain = async () => {
  if (fileListRaw.value.length === 0) {
    return ElMessage.warning('请先选择文件')
  }
  const formData = new FormData()
  const jsonBody = {
    datasetsId: trainKnowledge.value.datasetId,
    name: trainKnowledge.value.name,
    description: trainKnowledge.value.description,
  }
  formData.append('data', JSON.stringify(jsonBody))
  
  fileListRaw.value.forEach(file => {
    formData.append('file', file)
  })

  try {
    await creatTraining(formData)
    ElMessage.success('全部文件上传成功')
    // 清空上传列表、缓存文件
    uploadRef.value.clearFiles()
    fileListRaw.value = []
  } catch (err) {
    ElMessage.error(err?.message || '上传失败，请重试')
  }
}

// const filteredCategories = computed(() => {
//   if (!searchQuery.value) return categories.value
//   return categories.value.filter(c => c.name.includes(searchQuery.value) || c.description.includes(searchQuery.value))
// })

// const filteredKnowledge = computed(() => {
//   if (!searchQuery.value) return knowledgeList.value
//   return knowledgeList.value.filter(k => 
//     k.question.includes(searchQuery.value) || 
//     k.answer.includes(searchQuery.value) ||
//     k.tags.some(t => t.includes(searchQuery.value))
//   )
// })

const filteredQA = computed(() => {
  let result = qaRecords.value
  if (qaFilter.value !== 'all') {
    result = result.filter(qa => qa.sourceType === qaFilter.value)
  }
  if (qaRating.value !== 'all') {
    result = result.filter(qa => qa.rating === qaRating.value)
  }
  return result
})

const formatNumber = (num) => num.toLocaleString()




const showKnowledgeDetail = (item) => {
  selectedKnowledge.value = item
  showDetailModal.value = true
}

const editKnowledge = (item) => {
  showDetailModal.value = false
  showToastMessage('正在编辑知识...', 'success')
}

const deleteKnowledge = (item) => {
  showToastMessage('知识已删除', 'success')
}

const addKnowledgeDocument = ()=> {
  newKnowledge.value.name = ''
  newKnowledge.value.text=''
  newKnowledge.value.dataset_id=''
  showAddModal.value = true
}
const addKnowledge = () => {
  if(!newKnowledge.value.name||!newKnowledge.value.text||!newKnowledge.value.dataset_id){
    ElMessage.error('请填入必填项')
    return false
  }
  createKnowledge(newKnowledge.value).then(res => {
    if(res.success){
      howToastMessage('知识添加成功，AI 已学习', 'success')
      showAddModal.value = false
    }
  })
}

const optimizeAnswer = (item) => {
  showToastMessage('AI 正在优化答案...', 'success')
}

const rateQA = (qa, rating) => {
  qa.rating = rating
  showToastMessage('感谢您的反馈', 'success')
}

const toggleSetting = (key) => {
  showToastMessage('设置已更新', 'success')
}

const syncKnowledge = () => {
  showToastMessage('知识库同步中...', 'success')
}

const startImport = () => {
  showImportModal.value = false
  showToastMessage('开始导入知识...', 'success')
}

const showToastMessage = (message, type = 'success') => {
  toastMessage.value = message
  toastType.value = type
  showToast.value = true
  setTimeout(() => showToast.value = false, 3000)
}
</script>

<style scoped>
.knowledge-page { flex: 1; display: flex; flex-direction: column; padding: 24px; overflow-y: auto; background: var(--bg-dark); }
.page-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 24px; }
.header-left { display: flex; flex-direction: column; gap: 4px; }
.page-title { font-size: 20px; font-weight: 600; }
.page-desc { font-size: 13px; color: var(--text-secondary); }
.header-actions { display: flex; gap: 8px; }
.stats-row { display: grid; grid-template-columns: repeat(5, 1fr); gap: 16px; margin-bottom: 24px; }
.stat-card-lg { display: flex; align-items: center; gap: 14px; padding: 18px; background: var(--bg-card); border-radius: 14px; border: 1px solid var(--border); cursor: pointer; transition: all 0.2s; }
.stat-card-lg:hover { border-color: var(--primary); }
.stat-icon-lg { width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 20px; background: rgba(99, 102, 241, 0.2); color: var(--primary); }
.stat-icon-lg.green { background: rgba(16, 185, 129, 0.2); color: var(--success); }
.stat-icon-lg.purple { background: rgba(139, 92, 246, 0.2); color: var(--secondary); }
.stat-icon-lg.orange { background: rgba(245, 158, 11, 0.2); color: var(--warning); }
.stat-content-lg h3 { font-size: 24px; font-weight: 700; }
.stat-content-lg p { font-size: 12px; color: var(--text-secondary); }

/* Learning Section */
.learning-section { background: var(--bg-card); border-radius: 14px; padding: 20px; margin-bottom: 24px; border: 1px solid var(--border); }
.learning-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.learning-header h3 { font-size: 14px; display: flex; align-items: center; gap: 8px; margin: 0; }
.learning-header h3 i { color: var(--primary); }
.learning-status { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--success); }
.status-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--success); }
.status-dot.active { animation: pulse 2s infinite; }
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
.learning-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; }
.learning-item { display: flex; flex-direction: column; gap: 8px; }
.learning-label { font-size: 12px; color: var(--text-secondary); }
.learning-progress { display: flex; align-items: center; gap: 12px; }
.learning-progress .progress-bar { flex: 1; height: 6px; background: var(--bg-dark); border-radius: 3px; overflow: hidden; }
.learning-progress .progress-fill { height: 100%; background: var(--gradient-1); border-radius: 3px; }
.learning-progress .progress-fill.success { background: var(--success); }
.progress-value { font-size: 12px; font-weight: 600; color: var(--primary); min-width: 36px; }
.progress-value.success { color: var(--success); }

/* Tabs */
.tabs-container { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--border); padding-bottom: 12px; }
.tab-item { display: flex; align-items: center; gap: 8px; padding: 10px 20px; border-radius: 10px; cursor: pointer; font-size: 14px; color: var(--text-secondary); transition: all 0.2s; }
.tab-item:hover { background: var(--bg-hover); }
.tab-item.active { background: var(--bg-card); color: var(--text-primary); font-weight: 600; }
.tab-count { font-size: 11px; padding: 2px 8px; background: var(--bg-dark); border-radius: 10px; color: var(--text-muted); }
.tab-item.active .tab-count { background: var(--primary); color: white; }
.tab-actions { display: flex; gap: 12px; }
.search-box { position: relative; width: 280px; }
.search-icon { position: absolute; left: 14px; top: 50%; transform: translateY(-50%); color: var(--text-muted); }
.search-input { width: 100%; padding: 10px 14px 10px 40px; background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; color: var(--text-primary); font-size: 13px; }
.search-input:focus { outline: none; border-color: var(--primary); }

/* Section */
.section { margin-bottom: 24px; }

/* Categories */
.category-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; }
.category-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 14px; padding: 20px; cursor: pointer; transition: all 0.2s; }
.category-card:hover { border-color: var(--primary); transform: translateY(-2px); }
.category-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px; }
.category-icon { width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 24px; }
.category-badge { font-size: 10px; padding: 3px 8px; border-radius: 10px; background: rgba(239, 68, 68, 0.2); color: var(--danger); display: flex; align-items: center; gap: 4px; }
.category-name { font-size: 15px; font-weight: 600; margin-bottom: 4px; }
.category-desc { font-size: 12px; color: var(--text-secondary); margin-bottom: 12px; line-height: 1.4; }
.category-stats { display: flex; gap: 16px; margin-bottom: 12px; padding: 10px; background: var(--bg-hover); border-radius: 10px; }
.category-stat { display: flex; flex-direction: column; gap: 2px; }
.category-stat .stat-value { font-size: 14px; font-weight: 600; }
.category-stat .stat-label { font-size: 10px; color: var(--text-muted); }
.category-footer { display: flex; justify-content: space-between; align-items: center; }
.update-time { font-size: 11px; color: var(--text-muted); }

/* Knowledge List */
.knowledge-list { display: flex; flex-direction: column; gap: 12px; }
.knowledge-card { display: flex; align-items: flex-start; gap: 16px; padding: 16px; background: var(--bg-card); border: 1px solid var(--border); border-radius: 14px; cursor: pointer; transition: all 0.2s; }
.knowledge-card:hover { border-color: var(--primary); }
.knowledge-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 18px; flex-shrink: 0; }
.knowledge-content { flex: 1; }
.knowledge-header { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
.knowledge-question { font-size: 14px; font-weight: 600; }
.knowledge-category { font-size: 10px; padding: 2px 8px; border-radius: 10px; }
.knowledge-answer { font-size: 12px; color: var(--text-secondary); margin-bottom: 8px; line-height: 1.5; }
.knowledge-meta { display: flex; gap: 16px; font-size: 11px; color: var(--text-muted); }
.knowledge-actions { display: flex; gap: 8px; }

/* QA Section */
.qa-section { background: var(--bg-card); border-radius: 14px; padding: 20px; border: 1px solid var(--border); }
.qa-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.qa-header h4 { font-size: 14px; display: flex; align-items: center; gap: 8px; margin: 0; }
.qa-filters { display: flex; gap: 8px; }
.filter-select { padding: 6px 12px; background: var(--bg-hover); border: 1px solid var(--border); border-radius: 8px; color: var(--text-primary); font-size: 12px; }
.qa-list { display: flex; flex-direction: column; gap: 12px; }
.qa-card { background: var(--bg-hover); border-radius: 12px; padding: 16px; }
.qa-source { margin-bottom: 10px; }
.source-badge { font-size: 10px; padding: 3px 8px; border-radius: 10px; }
.source-badge.customer { background: rgba(99, 102, 241, 0.2); color: var(--primary); }
.source-badge.internal { background: rgba(139, 92, 246, 0.2); color: var(--secondary); }
.qa-content { margin-bottom: 12px; }
.qa-question, .qa-answer-block { display: flex; gap: 10px; font-size: 13px; line-height: 1.5; margin-bottom: 8px; }
.qa-label { width: 20px; height: 20px; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-size: 11px; font-weight: 600; background: var(--primary); color: white; flex-shrink: 0; }
.qa-label.answer { background: var(--success); }
.qa-footer { display: flex; justify-content: space-between; align-items: center; }
.qa-time { font-size: 11px; color: var(--text-muted); }
.qa-rating { display: flex; gap: 8px; }
.rating-btn { width: 28px; height: 28px; border-radius: 8px; border: 1px solid var(--border); background: transparent; color: var(--text-muted); cursor: pointer; display: flex; align-items: center; justify-content: center; }
.rating-btn:hover, .rating-btn.active { background: var(--bg-card); color: var(--primary); }
.rating-btn.active { border-color: var(--primary); }

/* Training Section */
.training-section { background: var(--bg-card); border-radius: 14px; padding: 20px; border: 1px solid var(--border); }
.training-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.training-header h4 { font-size: 14px; display: flex; align-items: center; gap: 8px; margin: 0; }
.training-list { display: flex; flex-direction: column; gap: 12px; }
.training-card { display: flex; align-items: center; gap: 16px; padding: 16px; background: var(--bg-hover); border-radius: 12px; }
.training-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 16px; }
.training-icon.running { background: rgba(99, 102, 241, 0.2); color: var(--primary); }
.training-icon.completed { background: rgba(16, 185, 129, 0.2); color: var(--success); }
.training-icon.paused { background: rgba(245, 158, 11, 0.2); color: var(--warning); }
.training-content { flex: 1; }
.training-name { font-size: 14px; font-weight: 600; margin-bottom: 4px; }
.training-desc { font-size: 12px; color: var(--text-secondary); margin-bottom: 8px; }
.training-progress { display: flex; align-items: center; gap: 12px; }
.training-progress .progress-bar { flex: 1; height: 4px; background: var(--bg-dark); border-radius: 2px; overflow: hidden; }
.training-progress .progress-fill { height: 100%; background: var(--gradient-1); border-radius: 2px; }
.progress-text { font-size: 11px; color: var(--primary); font-weight: 500; }
.training-stats { display: flex; gap: 20px; margin-right: 20px; }
.training-stat { text-align: center; }
.training-stat .value { font-size: 16px; font-weight: 600; display: block; }
.training-stat .label { font-size: 10px; color: var(--text-muted); }
.training-status { font-size: 11px; padding: 4px 10px; border-radius: 10px; }
.training-status.running { background: rgba(99, 102, 241, 0.2); color: var(--primary); }
.training-status.completed { background: rgba(16, 185, 129, 0.2); color: var(--success); }
.training-status.paused { background: rgba(245, 158, 11, 0.2); color: var(--warning); }

/* Settings Section */
.settings-section { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }
.settings-card { background: var(--bg-card); border-radius: 14px; padding: 20px; border: 1px solid var(--border); }
.settings-header { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
.settings-header i { font-size: 20px; color: var(--primary); }
.settings-title { font-size: 14px; font-weight: 600; }
.settings-content { display: flex; flex-direction: column; gap: 16px; }
.setting-item { display: flex; justify-content: space-between; align-items: center; padding: 12px; background: var(--bg-hover); border-radius: 10px; }
.setting-info { flex: 1; }
.setting-label { font-size: 13px; font-weight: 500; margin-bottom: 2px; }
.setting-desc { font-size: 11px; color: var(--text-secondary); }
.setting-toggle { width: 44px; height: 24px; background: var(--border); border-radius: 12px; position: relative; cursor: pointer; flex-shrink: 0; }
.setting-toggle.active { background: var(--success); }
.setting-toggle .toggle-slider { position: absolute; top: 3px; left: 3px; width: 18px; height: 18px; background: white; border-radius: 50%; transition: all 0.2s; }
.setting-toggle.active .toggle-slider { left: 23px; }
.setting-value { display: flex; align-items: center; gap: 4px; }
.threshold-input { width: 60px; padding: 6px 10px; background: var(--bg-dark); border: 1px solid var(--border); border-radius: 6px; color: var(--text-primary); font-size: 13px; text-align: center; }
.sync-status { display: flex; flex-direction: column; gap: 10px; }
.sync-item { display: flex; align-items: center; gap: 10px; font-size: 12px; }
.sync-item i { font-size: 14px; }
.sync-item i.success { color: var(--success); }
.sync-item i.warning { color: var(--warning); }
.sync-btn { width: 100%; margin-top: 16px; }

/* Modals */
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.7); display: flex; align-items: center; justify-content: center; z-index: 1000; padding: 20px; }
.modal { background: var(--bg-card); border-radius: 16px; width: 100%; max-width: 600px; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column; }
.detail-modal { max-width: 700px; }
.import-modal { max-width: 500px; }
.modal-header { display: flex; justify-content: space-between; align-items: center; padding: 20px; border-bottom: 1px solid var(--border); }
.modal-title { display: flex; align-items: center; gap: 12px; font-size: 16px; font-weight: 600; }
.modal-title h3 { font-size: 16px; font-weight: 600; margin: 0; }
.modal-title p { font-size: 12px; color: var(--text-secondary); margin: 4px 0 0 0; }
.detail-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 18px; }
.modal-close { width: 32px; height: 32px; background: var(--bg-hover); border: none; border-radius: 8px; color: var(--text-secondary); cursor: pointer; display: flex; align-items: center; justify-content: center; }
.modal-close:hover { background: var(--border); color: var(--text-primary); }
.modal-body { flex: 1; overflow-y: auto; padding: 20px; }
.modal-footer { display: flex; justify-content: flex-end; gap: 12px; padding: 20px; border-top: 1px solid var(--border); }

/* Form Elements */
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.form-group { margin-bottom: 16px; }
.form-label { display: block; font-size: 12px; color: var(--text-secondary); margin-bottom: 6px; }
.form-input { width: 100%; padding: 10px 14px; background: var(--bg-dark); border: 1px solid var(--border); border-radius: 8px; color: var(--text-primary); font-size: 13px; }
.form-input:focus { outline: none; border-color: var(--primary); }
.form-textarea { width: 100%; padding: 10px 14px; background: var(--bg-dark); border: 1px solid var(--border); border-radius: 8px; color: var(--text-primary); font-size: 13px; resize: vertical; }
.form-textarea:focus { outline: none; border-color: var(--primary); }
.form-select { width: 100%; padding: 10px 14px; background: var(--bg-dark); border: 1px solid var(--border); border-radius: 8px; color: var(--text-primary); font-size: 13px; }
.required { color: var(--danger); }

/* Detail Modal Content */
.detail-section { margin-bottom: 20px; }
.detail-label { font-size: 12px; color: var(--text-secondary); margin-bottom: 8px; display: flex; align-items: center; gap: 6px; }
.detail-label i { color: var(--primary); }
.detail-content { font-size: 13px; line-height: 1.6; padding: 12px; background: var(--bg-hover); border-radius: 10px; }
.detail-content.extended { white-space: pre-line; }
.detail-tags { display: flex; flex-wrap: wrap; gap: 8px; }
.tag { font-size: 11px; padding: 4px 10px; background: rgba(99, 102, 241, 0.2); color: var(--primary); border-radius: 10px; }
.related-questions { display: flex; flex-direction: column; gap: 8px; }
.related-item { font-size: 12px; padding: 8px 12px; background: var(--bg-hover); border-radius: 8px; cursor: pointer; }
.related-item:hover { background: var(--border); }
.detail-stats-row { display: flex; gap: 20px; padding: 12px; background: var(--bg-hover); border-radius: 10px; }
.detail-stat { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--text-secondary); }
.detail-stat i { color: var(--primary); }

/* Import Zone */
.import-zone { border: 2px dashed var(--border); border-radius: 14px; padding: 0px; text-align: center; margin-bottom: 20px; }
.import-zone :deep(.el-upload-dragger){border: none;background: none;}
.import-icon { font-size: 48px; color: var(--primary); margin-bottom: 12px; }
.import-text { font-size: 14px; font-weight: 500; margin-bottom: 4px; }
.import-formats { font-size: 12px; color: var(--text-muted); }
.import-options { display: flex; flex-direction: column; gap: 10px; }
.import-option { display: flex; align-items: center; gap: 12px; padding: 12px; background: var(--bg-hover); border-radius: 10px; }
.import-option i { font-size: 20px; color: var(--success); }
.import-option span { flex: 1; font-size: 13px; }

/* Toast */
.toast { position: fixed; bottom: 24px; right: 24px; padding: 12px 20px; background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; display: flex; align-items: center; gap: 10px; font-size: 13px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); z-index: 2000; }
.toast.success { border-color: var(--success); }
.toast.success i { color: var(--success); }
.toast-enter-active, .toast-leave-active { transition: all 0.3s ease; }
.toast-enter-from, .toast-leave-to { opacity: 0; transform: translateY(20px); }

/* Responsive */
@media (max-width: 1400px) { .category-grid { grid-template-columns: repeat(3, 1fr); } .stats-row { grid-template-columns: repeat(3, 1fr); } }
@media (max-width: 992px) { .category-grid { grid-template-columns: repeat(2, 1fr); } .stats-row { grid-template-columns: repeat(2, 1fr); } .learning-stats { grid-template-columns: repeat(2, 1fr); } .settings-section { grid-template-columns: 1fr; } }
@media (max-width: 768px) { .category-grid { grid-template-columns: 1fr; } .form-row { grid-template-columns: 1fr; } .tabs { flex-wrap: wrap; } }

.pagination-area{
  padding: 40px 0;
}
</style>
