<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import { renderMarkdown } from '@/utils/markdown'
import http from '@/utils/http'
import {
  analyzeStream,
  search,
  analyze,
  getProjects,
  getCacheStats,
  clearCache,
  exportReport,
  submitRecord,
} from '@/api/troubleshoot'
import type { MatchedCase } from '@/types/troubleshoot'
import { ElMessage, ElMessageBox } from 'element-plus'

const userStore = useUserStore()

// ============================================================
// 表单数据
// ============================================================
const form = ref({
  projectName: '',
  systemType: '',
  apkProduct: '',
  query: '',
  model: 'glm-5.1',
})
const projectList = ref<string[]>([])
const loading = ref(false)
const loadingText = ref('正在连接服务...')

// ============================================================
// 结果数据
// ============================================================
const resultVisible = ref(false)
const resultTime = ref('')
const matchedCases = ref<MatchedCase[]>([])
const responseContent = ref('')
const lastMatchedCases = ref<MatchedCase[]>([])
const exportLoading = ref(false)
const submitLoading = ref(false)

// ============================================================
// 弹窗状态
// ============================================================
const submitDialogVisible = ref(false)
const submitForm = ref({
  projectName: '',
  phenomenon: '',
  troubleshootSteps: '',
  rootCause: '',
  solution: '',
  recorder: '',
})
const cacheDialogVisible = ref(false)
const cacheStats = ref({
  totalFiles: 0,
  totalSizeMb: 0,
  oldest: '-' as string | null,
  newest: '-' as string | null,
})
const cacheLoading = ref(false)
const cacheClearing = ref(false)

// 记录详情弹窗
const recordDetailVisible = ref(false)
const recordDetailLoading = ref(false)
const recordDetailContent = ref('')
const recordDetailTitle = ref('')
const recordDetailRecordId = ref('')

// ============================================================
// 模型选择持久化
// ============================================================
const MODEL_STORAGE_KEY = 'troubleshoot_model'

function restoreModelSelection() {
  const saved = localStorage.getItem(MODEL_STORAGE_KEY)
  if (saved) {
    form.value.model = saved
  }
}

function saveModelSelection() {
  localStorage.setItem(MODEL_STORAGE_KEY, form.value.model)
}

watch(() => form.value.model, saveModelSelection)

// ============================================================
// 项目列表
// ============================================================
async function loadProjects() {
  try {
    const res = await getProjects()
    if (res.success) {
      projectList.value = res.projects || []
    }
  } catch (e) {
    console.error('加载项目列表失败:', e)
  }
}

// ============================================================
// 表单提交 — SSE 流式分析
// ============================================================
let sseConn: { close: () => void } | null = null

// 组件卸载时关闭 SSE 连接
onBeforeUnmount(() => {
  if (sseConn) {
    sseConn.close()
    sseConn = null
  }
})

async function handleSubmit() {
  // 关闭之前的连接
  if (sseConn) {
    sseConn.close()
    sseConn = null
  }

  // 表单验证
  if (!form.value.projectName) {
    ElMessage.warning('请输入项目名称')
    return
  }
  if (!form.value.systemType) {
    ElMessage.warning('请选择系统类型')
    return
  }
  if (!form.value.query) {
    ElMessage.warning('请输入问题描述')
    return
  }

  // 重置结果
  resultVisible.value = false
  matchedCases.value = []
  responseContent.value = ''
  lastMatchedCases.value = []
  resultTime.value = ''

  // 显示加载
  loading.value = true
  loadingText.value = '正在连接服务...'

  // 开始 SSE 流式分析
  startStreamAnalyze()
}

function startStreamAnalyze() {
  const { projectName, systemType, apkProduct, query, model } = form.value

  sseConn = analyzeStream(
    {
      project_name: projectName,
      system_type: systemType,
      apk_product: apkProduct || undefined,
      query,
      model, // 修复 Flask 模板 bug：model 未传给 SSE 端点
    },
    {
      start: (data: any) => {
        loadingText.value = data.message || '正在分析...'
      },
      matched_cases: (data: any) => {
        if (data.cases && data.cases.length > 0) {
          lastMatchedCases.value = data.cases
          showMatchedCases(data.cases, '<1s')
        }
        loadingText.value = '正在生成排查步骤...'
      },
      chunk: (data: any) => {
        responseContent.value += data.content || ''
        updateResponseContent(responseContent.value)
      },
      done: (data: any) => {
        sseConn = null
        loading.value = false
        resultTime.value = `AI 分析 ${data.api_time}s`
      },
      error: (data: any) => {
        sseConn = null
        loading.value = false
        ElMessage.error('分析失败：' + (data.message || '未知错误'))
      },
    },
    () => {
      // SSE 连接错误（降级）
      if (responseContent.value === '' && matchedCases.value.length === 0) {
        sseConn = null
        console.error('SSE 连接错误，降级到普通请求')
        fallbackToNormalRequest()
      }
    }
  )
}

// 降级：普通请求
async function fallbackToNormalRequest() {
  try {
    loadingText.value = '正在尝试普通模式...'

    // 搜索
    const searchRes = await search({
      project_name: form.value.projectName,
      query: form.value.query,
    })

    if (searchRes.success) {
      showMatchedCases(searchRes.matched_cases, searchRes.search_time + 's')
    }

    // 分析
    const analyzeRes = await analyze({
      project_name: form.value.projectName,
      system_type: form.value.systemType,
      apk_product: form.value.apkProduct || undefined,
      query: form.value.query,
      matched_cases: searchRes.matched_cases || [],
    })

    if (analyzeRes.success) {
      showAIResponse(analyzeRes)
    } else {
      ElMessage.error('分析失败')
    }
  } catch (e) {
    ElMessage.error('服务异常，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 显示匹配案例
function showMatchedCases(cases: MatchedCase[], searchTime: string) {
  matchedCases.value = cases
  resultVisible.value = true
  resultTime.value = `搜索 ${searchTime}s | AI 分析中...`
}

// 显示 AI 响应（降级路径）
function showAIResponse(data: any) {
  resultTime.value = `AI 分析 ${data.api_time}s`
  responseContent.value = data.response || ''
  updateResponseContent(responseContent.value)
}

// 更新 AI 响应内容（流式追加）
function updateResponseContent(_content: string) {
  resultVisible.value = true
  // 使用 nextTick 确保 DOM 更新后滚动到底部
  setTimeout(() => {
    const container = document.querySelector('.response-content')
    if (container) {
      container.scrollTop = container.scrollHeight
    }
  }, 50)
}

// ============================================================
// 清空表单
// ============================================================
function clearForm() {
  form.value.projectName = ''
  form.value.systemType = ''
  form.value.apkProduct = ''
  form.value.query = ''
  // 不重置模型选择
  resultVisible.value = false
  matchedCases.value = []
  responseContent.value = ''
  lastMatchedCases.value = []
  resultTime.value = ''
}

// ============================================================
// 记录详情查看/下载
// ============================================================
async function showRecordDetail(c: MatchedCase) {
  if (!c.record_id) return
  recordDetailRecordId.value = c.record_id
  recordDetailTitle.value = c.title
  recordDetailContent.value = ''
  recordDetailLoading.value = true
  recordDetailVisible.value = true

  try {
    const res = await http.get(`/api/troubleshoot/record/${c.record_id}`)
    if (res.data?.success && res.data.record) {
      recordDetailContent.value = res.data.record.full_text || ''
      recordDetailTitle.value = res.data.record.title || c.title
    } else {
      recordDetailContent.value = '加载失败'
    }
  } catch {
    recordDetailContent.value = '加载失败'
  } finally {
    recordDetailLoading.value = false
  }
}

function downloadRecord() {
  if (!recordDetailRecordId.value) return
  window.open(`/api/troubleshoot/record/${recordDetailRecordId.value}/download`, '_blank')
}

// ============================================================
// 导出 Word 报告
// ============================================================
async function handleExport() {
  exportLoading.value = true
  try {
    const blob = await exportReport({
      project_name: form.value.projectName,
      system_type: form.value.systemType,
      apk_product: form.value.apkProduct || undefined,
      query: form.value.query,
      matched_cases: lastMatchedCases.value,
      response: responseContent.value,
    })

    // 触发下载
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
    a.download = `排查报告_${form.value.projectName}_${timestamp}.docx`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功！')
  } catch (e: any) {
    ElMessage.error('导出失败：' + (e.message || '未知错误'))
  } finally {
    exportLoading.value = false
  }
}

// ============================================================
// 提交记录入库
// ============================================================
function openSubmitDialog() {
  submitForm.value.projectName = form.value.projectName
  submitForm.value.phenomenon = form.value.query

  // 从 AI 响应中提取排查步骤（截取到 ⚠️ 注意事项之前）
  const responseEl = document.querySelector('.response-content')
  const stepsText = responseEl
    ? (responseEl as HTMLElement).innerText.replace(/⚠️ 注意事项[\s\S]*/, '').trim()
    : ''
  submitForm.value.troubleshootSteps = stepsText
  submitForm.value.rootCause = ''
  submitForm.value.solution = ''
  submitForm.value.recorder = ''

  submitDialogVisible.value = true
}

async function confirmSubmit() {
  const data = submitForm.value
  if (!data.projectName) {
    ElMessage.warning('请输入项目名称')
    return
  }
  if (!data.phenomenon) {
    ElMessage.warning('请输入问题现象')
    return
  }
  if (!data.recorder) {
    ElMessage.warning('请输入记录人')
    return
  }

  submitLoading.value = true
  try {
    const res = await submitRecord({
      project_name: data.projectName,
      phenomenon: data.phenomenon,
      system_type: form.value.systemType || undefined,
      apk_product: form.value.apkProduct || undefined,
      troubleshoot_steps: data.troubleshootSteps || undefined,
      root_cause: data.rootCause || undefined,
      solution: data.solution || undefined,
      recorder: data.recorder,
    })
    if (res.success) {
      submitDialogVisible.value = false
      ElMessage.success('提交成功！问题已入库')
    } else {
      ElMessage.error('提交失败')
    }
  } catch (e: any) {
    ElMessage.error('提交异常，请稍后重试')
  } finally {
    submitLoading.value = false
  }
}

// ============================================================
// 缓存管理
// ============================================================
async function openCacheDialog() {
  cacheDialogVisible.value = true
  cacheLoading.value = true
  try {
    const res = await getCacheStats()
    if (res.success && res.stats) {
      cacheStats.value = {
        totalFiles: res.stats.total_files || 0,
        totalSizeMb: res.stats.total_size_mb || 0,
        oldest: res.stats.oldest || '-',
        newest: res.stats.newest || '-',
      }
    }
  } catch (e) {
    ElMessage.error('获取缓存统计失败')
  } finally {
    cacheLoading.value = false
  }
}

async function handleClearCache() {
  try {
    await ElMessageBox.confirm('确定要清空所有缓存吗？这将删除所有已缓存的排查结果。', '确认清空', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    cacheClearing.value = true
    const res = await clearCache()
    if (res.success) {
      ElMessage.success(res.message || '缓存已清空')
      // 刷新统计
      const statsRes = await getCacheStats()
      if (statsRes.success && statsRes.stats) {
        cacheStats.value = {
          totalFiles: statsRes.stats.total_files || 0,
          totalSizeMb: statsRes.stats.total_size_mb || 0,
          oldest: statsRes.stats.oldest || '-',
          newest: statsRes.stats.newest || '-',
        }
      }
    }
  } catch {
    // 取消操作
  } finally {
    cacheClearing.value = false
  }
}

// ============================================================
// 系统类型选项
// ============================================================
const systemTypeOptions = [
  { value: '标准版预定2.0', label: '标准版预定2.0' },
  { value: '标准版运维集控系统', label: '标准版运维集控系统' },
  { value: '新统一平台', label: '新统一平台' },
  { value: '统一平台', label: '统一平台' },
]

const modelOptions = [
  { value: 'glm-4-flash', label: '快速模式（5-10秒，简单问题）' },
  { value: 'glm-5.1', label: '标准模式（20-50秒，推荐）' },
  { value: 'glm-4-plus', label: '深度模式（30-60秒，复杂问题）' },
]

// ============================================================
// 初始化
// ============================================================
onMounted(() => {
  restoreModelSelection()
  loadProjects()
})
</script>

<template>
  <div class="page-troubleshoot">
    <AppNavbar show-module module-label="运行维护平台" home-path="/troubleshoot" logs-path="/troubleshoot/logs" />

    <div class="container">
      <el-card class="main-card" shadow="always">
        <!-- 卡片头部 -->
        <template #header>
          <div class="card-header">
            <h1 class="card-title">🔍 运行维护平台</h1>
            <p class="card-subtitle">基于历史知识库的 AI 问题排查，357 条记录 · 安全过滤</p>
          </div>
        </template>

        <!-- 警告提示 -->
        <el-alert
          title="排查步骤均为只读操作，不会修改系统。如需执行重启/删除等危险操作，请联系研发组。"
          type="warning"
          :closable="false"
          show-icon
          class="warning-alert"
        />

        <!-- 排查表单 -->
        <el-form
          :model="form"
          label-position="top"
          @submit.prevent="handleSubmit"
          class="troubleshoot-form"
        >
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12">
              <el-form-item label="项目名称" required>
                <el-input
                  v-model="form.projectName"
                  placeholder="输入项目名称"
                  clearable
                  class="full-width"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="系统类型" required>
                <el-select
                  v-model="form.systemType"
                  placeholder="请选择..."
                  clearable
                  class="full-width"
                >
                  <el-option
                    v-for="opt in systemTypeOptions"
                    :key="opt.value"
                    :label="opt.label"
                    :value="opt.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="APK 产品">
            <el-input
              v-model="form.apkProduct"
              placeholder="如：门口屏5.0、无纸化、桌牌（可选）"
              clearable
            />
            <div class="form-hint">仅涉及 APK 产品时填写</div>
          </el-form-item>

          <el-form-item label="模型选择">
            <el-select
              v-model="form.model"
              class="full-width"
            >
              <el-option
                v-for="opt in modelOptions"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </el-select>
            <div class="form-hint">快速模式适合简单问题，深度模式适合复杂问题</div>
          </el-form-item>

          <el-form-item label="问题描述" required>
            <el-input
              v-model="form.query"
              type="textarea"
              :rows="5"
              placeholder="请详细描述遇到的问题，例如：
门口屏绑定失败，提示 MQTT 连接错误...

包含以下信息有助于更精准分析：
- 报错信息或截图内容
- 问题发生时间
- 近期是否有变更"
            />
          </el-form-item>

          <div class="btn-group">
            <el-button
              type="primary"
              native-type="submit"
              :loading="loading"
              size="large"
              class="btn-submit"
            >
              🔬 帮我排查
            </el-button>
            <el-button
              size="large"
              @click="clearForm"
              :disabled="loading"
            >
              🔄 清空
            </el-button>
          </div>
        </el-form>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-section">
          <div class="loading-spinner" />
          <span class="loading-text">{{ loadingText }}</span>
        </div>

        <!-- 结果区域 -->
        <div v-if="resultVisible" class="result-section">
          <div class="result-header">
            <h2>✅ 排查诊断结果</h2>
            <el-tag v-if="resultTime" type="success" effect="plain">
              {{ resultTime }}
            </el-tag>
          </div>

          <!-- 匹配案例 -->
          <div v-if="matchedCases.length > 0" class="matched-cases">
            <h3>📋 匹配到的历史案例</h3>
            <div
              v-for="c in matchedCases"
              :key="c.rank"
              class="matched-case-item"
            >
              <el-tag
                size="small"
                type="primary"
                class="score-tag"
              >
                {{ Math.round(c.score * 100) }}%
              </el-tag>
              <span class="case-title">
                {{ c.title }}
              </span>
              <el-button
                v-if="c.record_id"
                link
                type="primary"
                size="small"
                @click="showRecordDetail(c)"
              >
                查看详情
              </el-button>
            </div>
          </div>

          <!-- 等待 AI 分析占位 -->
          <div
            v-if="!responseContent && matchedCases.length > 0"
            class="waiting-placeholder"
          >
            <div class="loading-spinner small" />
            <p>正在等待 AI 分析结果...</p>
          </div>

          <!-- AI 响应内容 -->
          <div
            v-if="responseContent"
            class="response-content"
            v-html="renderMarkdown(responseContent)"
          />

          <!-- 操作按钮 -->
          <div v-if="responseContent" class="action-bar">
            <el-button
              :loading="exportLoading"
              @click="handleExport"
            >
              📄 导出 Word 文档
            </el-button>
          </div>

          <!-- 提交入库 -->
          <div v-if="responseContent" class="submit-section">
            <p>✅ 问题已解决？点击提交记录入库，帮助其他同事快速排查同类问题。</p>
            <el-button
              type="primary"
              @click="openSubmitDialog"
            >
              📝 提交记录入库
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 页脚 -->
      <div class="footer">
        <span>运行维护平台 · 基于 Claude AI · 安全过滤保障</span>
        <el-button
          v-if="userStore.isAdmin"
          text
          size="small"
          class="cache-btn"
          @click="openCacheDialog"
        >
          📊 缓存管理
        </el-button>
      </div>
    </div>

    <!-- 提交记录弹窗 -->
    <el-dialog
      v-model="submitDialogVisible"
      title="提交问题记录"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="submitForm"
        label-position="top"
      >
        <el-form-item label="项目名称" required>
          <el-input v-model="submitForm.projectName" placeholder="项目名称" />
        </el-form-item>
        <el-form-item label="问题现象" required>
          <el-input
            v-model="submitForm.phenomenon"
            type="textarea"
            :rows="3"
            placeholder="描述遇到的问题"
          />
        </el-form-item>
        <el-form-item label="排查过程">
          <el-input
            v-model="submitForm.troubleshootSteps"
            type="textarea"
            :rows="4"
            placeholder="排查步骤（自动填充，可编辑）"
          />
        </el-form-item>
        <el-form-item label="实际根因">
          <el-input
            v-model="submitForm.rootCause"
            type="textarea"
            :rows="3"
            placeholder="请填写排查确认的根因"
          />
        </el-form-item>
        <el-form-item label="解决方案">
          <el-input
            v-model="submitForm.solution"
            type="textarea"
            :rows="3"
            placeholder="请填写解决方案"
          />
        </el-form-item>
        <el-form-item label="记录人" required>
          <el-input v-model="submitForm.recorder" placeholder="请填写您的姓名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="submitDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="confirmSubmit"
        >
          确认提交
        </el-button>
      </template>
    </el-dialog>

    <!-- 缓存管理弹窗 -->
    <el-dialog
      v-model="cacheDialogVisible"
      title="📊 缓存管理"
      width="500px"
    >
      <div v-loading="cacheLoading" class="cache-stats">
        <div class="stat-row">
          <span class="stat-label">缓存文件总数：</span>
          <span class="stat-value">{{ cacheStats.totalFiles }}</span>
        </div>
        <div class="stat-row">
          <span class="stat-label">缓存总大小：</span>
          <span class="stat-value">{{ cacheStats.totalSizeMb }} MB</span>
        </div>
        <div class="stat-row">
          <span class="stat-label">最早缓存时间：</span>
          <span class="stat-value">{{ cacheStats.oldest }}</span>
        </div>
        <div class="stat-row">
          <span class="stat-label">最新缓存时间：</span>
          <span class="stat-value">{{ cacheStats.newest }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="cacheDialogVisible = false">关闭</el-button>
        <el-button
          type="danger"
          :loading="cacheClearing"
          @click="handleClearCache"
        >
          🗑️ 清除所有缓存
        </el-button>
      </template>
    </el-dialog>

    <!-- 记录详情弹窗 -->
    <el-dialog
      v-model="recordDetailVisible"
      :title="recordDetailTitle"
      width="700px"
      destroy-on-close
    >
      <div v-loading="recordDetailLoading" class="record-detail-content">
        <div
          v-if="recordDetailContent"
          class="record-detail-md"
          v-html="renderMarkdown(recordDetailContent)"
        />
      </div>
      <template #footer>
        <el-button @click="recordDetailVisible = false">关闭</el-button>
        <el-button type="primary" @click="downloadRecord">
          📥 下载文档
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.page-troubleshoot {
  min-height: 100vh;
  padding-top: 56px;
  padding-bottom: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.container {
  max-width: 900px;
  margin: 0 auto;
  padding: 0 20px;
}

.main-card {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);

  :deep(.el-card__body) {
    padding: 32px;
  }
}

.card-header {
  .card-title {
    font-size: 24px;
    font-weight: 700;
    margin-bottom: 4px;
  }

  .card-subtitle {
    font-size: 14px;
    opacity: 0.8;
  }
}

// card-header is inside el-card header slot
:deep(.el-card__header) {
  background: linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%);
  color: white;
  padding: 24px 32px;
  border: none;
}

.warning-alert {
  margin-bottom: 24px;
}

.troubleshoot-form {
  :deep(.el-form-item__label) {
    font-weight: 600;
    font-size: 14px;
    color: $gray-700;
    padding-bottom: 6px;
  }
}

.full-width {
  width: 100%;
}

.form-hint {
  font-size: 12px;
  color: $gray-500;
  margin-top: 4px;
  line-height: 1.4;
}

.btn-group {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

.btn-submit {
  min-width: 140px;
}

// ============================================================
// 加载状态
// ============================================================
.loading-section {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 40px;
  margin-top: 32px;
  border-top: 1px solid $gray-200;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid $gray-200;
  border-top-color: $primary;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  flex-shrink: 0;

  &.small {
    width: 20px;
    height: 20px;
    border-width: 2px;
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-text {
  color: $gray-700;
  font-size: 14px;
}

// ============================================================
// 结果区域
// ============================================================
.result-section {
  margin-top: 32px;
  padding-top: 32px;
  border-top: 1px solid $gray-200;
}

.result-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;

  h2 {
    font-size: 18px;
    color: $gray-900;
    margin: 0;
  }
}

.matched-cases {
  background: $gray-50;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;

  h3 {
    font-size: 14px;
    color: $gray-700;
    margin-bottom: 12px;
  }
}

.matched-case-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  border-bottom: 1px solid $gray-200;

  &:last-child {
    border-bottom: none;
  }
}

.score-tag {
  flex-shrink: 0;
}

.case-title {
  flex: 1;
  font-size: 14px;
  color: $gray-700;
}

.waiting-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 20px;
  color: $gray-500;
  font-size: 14px;

  p {
    margin: 0;
  }
}

.response-content {
  background: $gray-50;
  border-radius: 8px;
  padding: 24px;
  line-height: 1.8;
  max-height: 600px;
  overflow-y: auto;

  // Markdown 渲染样式
  :deep(h3) {
    color: $primary;
    margin-top: 20px;
    margin-bottom: 12px;
    font-size: 16px;

    &:first-child {
      margin-top: 0;
    }
  }

  :deep(p), :deep(li) {
    color: $gray-700;
    font-size: 14px;
  }

  :deep(ul), :deep(ol) {
    padding-left: 20px;
    margin: 8px 0;
  }

  :deep(code) {
    background: #f1f5f9;
    color: #1e40af;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 13px;
    font-family: "Cascadia Code", "Fira Code", "Consolas", monospace;
    border: 1px solid #e2e8f0;
  }

  :deep(pre) {
    background: #1e293b;
    color: #e2e8f0;
    padding: 16px;
    border-radius: 8px;
    overflow-x: auto;
    margin: 16px 0;

    code {
      background: none;
      color: inherit;
      border: none;
      padding: 0;
      font-size: 13px;
    }
  }

  :deep(blockquote) {
    border-left: 3px solid $primary;
    padding: 8px 16px;
    margin: 16px 0;
    background: #f8fafc;
    border-radius: 0 8px 8px 0;
    color: $gray-700;
  }

  :deep(table) {
    width: 100%;
    border-collapse: collapse;
    margin: 16px 0;

    th, td {
      border: 1px solid $gray-200;
      padding: 8px 12px;
      text-align: left;
      font-size: 14px;
    }

    th {
      background: $gray-100;
      font-weight: 600;
      color: $gray-700;
    }

    tr:nth-child(even) td {
      background: $gray-50;
    }
  }

  :deep(hr) {
    border: none;
    border-top: 1px solid $gray-200;
    margin: 24px 0;
  }

  :deep(a) {
    color: $primary;
    text-decoration: underline;

    &:hover {
      color: $primary-hover;
    }
  }
}

.action-bar {
  margin-top: 24px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.submit-section {
  margin-top: 24px;
  padding: 16px;
  background: #f0fdf4;
  border-radius: 8px;
  border: 1px solid #86efac;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;

  p {
    color: #166534;
    font-size: 14px;
    margin: 0;
  }

  @media screen and (max-width: 768px) {
    flex-direction: column;
    align-items: stretch;
    text-align: center;
  }
}

// ============================================================
// 页脚
// ============================================================
.footer {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
  padding: 24px 20px;
  color: white;
  opacity: 0.8;
  font-size: 12px;
}

.cache-btn {
  color: white !important;
  opacity: 0.8;
  font-size: 12px;

  &:hover {
    opacity: 1;
  }
}

// ============================================================
// 记录详情
// ============================================================
.record-detail-content {
  min-height: 200px;
}

.record-detail-md {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  max-height: 500px;
  overflow-y: auto;
  line-height: 1.8;

  :deep(h1), :deep(h2), :deep(h3) {
    color: #303133;
    margin-top: 16px;
    margin-bottom: 8px;
  }

  :deep(h1) { font-size: 18px; }
  :deep(h2) { font-size: 16px; color: #2563eb; }
  :deep(h3) { font-size: 14px; }

  :deep(p), :deep(li) {
    color: #606266;
    font-size: 14px;
  }

  :deep(ol), :deep(ul) {
    padding-left: 20px;
    margin: 8px 0;
  }

  :deep(code) {
    background: #eef2ff;
    color: #1e40af;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 13px;
  }

  :deep(pre) {
    background: #1e293b;
    color: #e2e8f0;
    padding: 12px;
    border-radius: 8px;
    overflow-x: auto;
  }

  :deep(blockquote) {
    border-left: 3px solid #2563eb;
    padding: 8px 16px;
    margin: 12px 0;
    background: #f8fafc;
  }
}

// ============================================================
// 缓存统计
// ============================================================
.cache-stats {
  line-height: 2.2;
  min-height: 120px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  padding: 4px 0;
}

.stat-label {
  font-weight: 600;
  color: $gray-700;
}

.stat-value {
  color: $gray-900;
}

// ============================================================
// 响应式适配
// ============================================================
@media screen and (max-width: 1024px) {
  .container {
    max-width: 100%;
    padding: 16px;
  }
}

@media screen and (max-width: 768px) {
  .container {
    padding: 12px;
  }

  :deep(.el-card__body) {
    padding: 20px !important;
  }

  :deep(.el-card__header) {
    padding: 20px !important;
  }

  .card-header {
    .card-title {
      font-size: 20px;
    }
  }

  .btn-group {
    flex-direction: column;
  }

  .btn-submit {
    width: 100%;
  }
}

@media screen and (max-width: 375px) {
  :deep(.el-card__body) {
    padding: 16px !important;
  }
}
</style>