<script setup>
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { cleanupEmailLogs, fetchEmailLogs, fetchEmailSettings, fetchEmailStats, updateEmailSettings } from '../api/email'
import {
  createSmtpConfig,
  clearPrimarySmtpConfig,
  deleteSmtpConfig,
  fetchSmtpConfigs,
  setPrimarySmtpConfig,
  testSmtpConfig,
  updateSmtpConfig,
} from '../api/smtp'
import MetricGrid from '../components/MetricGrid.vue'

// ========== 全局设置 ==========
const emailSettingsLoading = ref(false)
const emailSettingsSaving = ref(false)

const settings = reactive({
  enabled: false,
  failover_enabled: true,
  register_verify_enabled: false,
  login_alert_enabled: true,
  task_notify_enabled: false,
  base_url: '',
  updated_at: null,
})

let saveTimer = null

async function loadEmailSettings() {
  emailSettingsLoading.value = true
  try {
    const data = await fetchEmailSettings()
    settings.enabled = Boolean(data.enabled)
    settings.failover_enabled = Boolean(data.failover_enabled)
    settings.register_verify_enabled = Boolean(data.register_verify_enabled)
    settings.login_alert_enabled = data.login_alert_enabled === undefined ? true : Boolean(data.login_alert_enabled)
    settings.task_notify_enabled = Boolean(data.task_notify_enabled)
    settings.base_url = data.base_url || ''
    settings.updated_at = data.updated_at || null
  } catch {
    // handled by interceptor
  } finally {
    emailSettingsLoading.value = false
  }
}

async function saveEmailSettings() {
  if (emailSettingsLoading.value) return
  emailSettingsSaving.value = true
  try {
    const res = await updateEmailSettings({
      enabled: settings.enabled,
      failover_enabled: settings.failover_enabled,
      register_verify_enabled: settings.register_verify_enabled,
      login_alert_enabled: settings.login_alert_enabled,
      task_notify_enabled: settings.task_notify_enabled,
      base_url: (settings.base_url || '').trim(),
    })
    if (!res?.success) {
      ElMessage.error(res?.error || '更新失败')
      return
    }
    ElMessage.success('邮件设置已更新')
    await loadEmailSettings()
  } catch {
    // handled by interceptor
  } finally {
    emailSettingsSaving.value = false
  }
}

function scheduleSaveEmailSettings() {
  if (saveTimer) window.clearTimeout(saveTimer)
  saveTimer = window.setTimeout(saveEmailSettings, 300)
}

onBeforeUnmount(() => {
  if (saveTimer) window.clearTimeout(saveTimer)
  saveTimer = null
})

// ========== SMTP 配置 ==========
const smtpLoading = ref(false)
const smtpConfigs = ref([])

const smtpDialogOpen = ref(false)
const smtpEditMode = ref(false)
const smtpHasPassword = ref(false)
const smtpIsPrimary = ref(false)

const smtpForm = reactive({
  id: null,
  name: '默认配置',
  enabled: true,
  host: '',
  port: 465,
  username: '',
  password: '',
  use_ssl: true,
  use_tls: false,
  sender_name: '自动化学习',
  sender_email: '',
  daily_limit: 0,
  priority: 0,
})

const SMTP_TEMPLATES = [
  {
    key: 'custom',
    label: '自定义（手动填写）',
    defaults: null,
    note: '适用于其他邮箱/自建SMTP',
    links: [],
  },
  {
    key: 'gmail',
    label: 'Gmail',
    defaults: { host: 'smtp.gmail.com', port: 465, use_ssl: true, use_tls: false },
    note: '通常需要开启两步验证并创建应用专用密码（App Password）',
    links: [
      { label: 'SMTP 设置说明', url: 'https://support.google.com/mail/answer/7126229?hl=zh-Hans' },
      { label: 'App Password', url: 'https://myaccount.google.com/apppasswords' },
    ],
  },
  {
    key: 'qq',
    label: 'QQ 邮箱',
    defaults: { host: 'smtp.qq.com', port: 465, use_ssl: true, use_tls: false },
    note: '需要在邮箱设置中开启 SMTP 并获取授权码（不是QQ登录密码）',
    links: [{ label: 'QQ邮箱 SMTP 帮助', url: 'https://service.mail.qq.com/cgi-bin/help?subtype=1&id=28&no=1001256' }],
  },
  {
    key: '163',
    label: '163 邮箱',
    defaults: { host: 'smtp.163.com', port: 465, use_ssl: true, use_tls: false },
    note: '需要在邮箱设置中开启 SMTP 并使用授权码/客户端授权密码',
    links: [{ label: '网易邮箱 SMTP 帮助', url: 'https://help.mail.163.com/faqDetail.do?code=d7a5dc8471a22b76' }],
  },
  {
    key: '126',
    label: '126 邮箱',
    defaults: { host: 'smtp.126.com', port: 465, use_ssl: true, use_tls: false },
    note: '需要在邮箱设置中开启 SMTP 并使用授权码/客户端授权密码',
    links: [{ label: '网易邮箱帮助', url: 'https://help.mail.163.com/' }],
  },
  {
    key: 'outlook',
    label: 'Outlook/Hotmail',
    defaults: { host: 'smtp-mail.outlook.com', port: 587, use_ssl: false, use_tls: true },
    note: '建议使用 TLS 587（部分账号需开启 SMTP AUTH）',
    links: [
      {
        label: '微软 SMTP 设置',
        url: 'https://support.microsoft.com/office/pop-imap-and-smtp-settings-for-outlook-com-d088b0b7-0d38-4f9a-bc5d-509f9e4c6d3d',
      },
    ],
  },
  {
    key: 'office365',
    label: 'Microsoft 365/Exchange',
    defaults: { host: 'smtp.office365.com', port: 587, use_ssl: false, use_tls: true },
    note: '企业邮箱常用配置（需启用 SMTP AUTH）',
    links: [{ label: '微软官方说明', url: 'https://learn.microsoft.com/exchange/clients-and-mobile-in-exchange-online/authenticated-client-smtp-submission' }],
  },
  {
    key: 'icloud',
    label: 'iCloud',
    defaults: { host: 'smtp.mail.me.com', port: 587, use_ssl: false, use_tls: true },
    note: '需要在 Apple ID 中生成“App 专用密码”',
    links: [{ label: 'Apple 邮件服务器设置', url: 'https://support.apple.com/zh-cn/HT202304' }],
  },
  {
    key: 'tencent_exmail',
    label: '腾讯企业邮箱',
    defaults: { host: 'smtp.exmail.qq.com', port: 465, use_ssl: true, use_tls: false },
    note: '企业邮箱常用配置',
    links: [{ label: '腾讯企业邮箱帮助', url: 'https://service.exmail.qq.com/cgi-bin/help?subtype=1&id=23&no=1001068' }],
  },
  {
    key: 'aliyun_exmail',
    label: '阿里企业邮箱',
    defaults: { host: 'smtp.mxhichina.com', port: 465, use_ssl: true, use_tls: false },
    note: '企业邮箱常用配置',
    links: [{ label: '阿里云文档', url: 'https://help.aliyun.com/document_detail/50652.html' }],
  },
]

const smtpTemplateKey = ref('custom')
const currentSmtpTemplate = computed(() => SMTP_TEMPLATES.find((t) => t.key === smtpTemplateKey.value) || SMTP_TEMPLATES[0])

const smtpPasswordPlaceholder = computed(() =>
  smtpEditMode.value && smtpHasPassword.value ? '留空保持不变' : 'SMTP密码或授权码',
)

function inferSmtpTemplateKey(row) {
  const host = String(row?.host || '').trim().toLowerCase()
  if (!host) return 'custom'
  const byHost = {
    'smtp.gmail.com': 'gmail',
    'smtp.qq.com': 'qq',
    'smtp.163.com': '163',
    'smtp.126.com': '126',
    'smtp-mail.outlook.com': 'outlook',
    'smtp.office365.com': 'office365',
    'smtp.mail.me.com': 'icloud',
    'smtp.exmail.qq.com': 'tencent_exmail',
    'smtp.mxhichina.com': 'aliyun_exmail',
  }
  return byHost[host] || 'custom'
}

function applySmtpTemplate(key) {
  const tpl = SMTP_TEMPLATES.find((t) => t.key === key)
  if (!tpl || !tpl.defaults) return
  smtpForm.host = tpl.defaults.host
  smtpForm.port = tpl.defaults.port
  smtpForm.use_ssl = tpl.defaults.use_ssl
  smtpForm.use_tls = tpl.defaults.use_tls
}

function resetSmtpForm() {
  smtpForm.id = null
  smtpForm.name = '默认配置'
  smtpForm.enabled = true
  smtpForm.host = ''
  smtpForm.port = 465
  smtpForm.username = ''
  smtpForm.password = ''
  smtpForm.use_ssl = true
  smtpForm.use_tls = false
  smtpForm.sender_name = '自动化学习'
  smtpForm.sender_email = ''
  smtpForm.daily_limit = 0
  smtpForm.priority = 0
  smtpHasPassword.value = false
  smtpIsPrimary.value = false
  smtpTemplateKey.value = 'custom'
}

async function loadSmtpConfigs() {
  smtpLoading.value = true
  try {
    smtpConfigs.value = await fetchSmtpConfigs()
  } catch {
    smtpConfigs.value = []
  } finally {
    smtpLoading.value = false
  }
}

function openCreateSmtp() {
  smtpEditMode.value = false
  resetSmtpForm()
  smtpTemplateKey.value = 'custom'
  smtpDialogOpen.value = true
}

function openEditSmtp(row) {
  smtpEditMode.value = true
  resetSmtpForm()

  smtpForm.id = row.id
  smtpForm.name = row.name || '默认配置'
  smtpForm.enabled = Boolean(row.enabled)
  smtpForm.host = row.host || ''
  smtpForm.port = row.port || 465
  smtpForm.username = row.username || ''
  smtpForm.password = ''
  smtpForm.use_ssl = Boolean(row.use_ssl)
  smtpForm.use_tls = Boolean(row.use_tls)
  smtpForm.sender_name = row.sender_name || '自动化学习'
  smtpForm.sender_email = row.sender_email || ''
  smtpForm.daily_limit = row.daily_limit ?? 0
  smtpForm.priority = row.priority ?? 0
  smtpHasPassword.value = Boolean(row.has_password)
  smtpIsPrimary.value = Boolean(row.is_primary)
  smtpTemplateKey.value = inferSmtpTemplateKey(row)

  smtpDialogOpen.value = true
}

function smtpStatusMeta(row) {
  if (row.is_primary) return { label: '主', type: 'warning' }
  if (row.enabled) return { label: '备用', type: 'success' }
  return { label: '禁用', type: 'info' }
}

function smtpDailyText(row) {
  if (row.daily_limit && row.daily_limit > 0) return `${row.daily_sent}/${row.daily_limit}`
  return `${row.daily_sent}/∞`
}

async function saveSmtp() {
  if (!smtpForm.host.trim()) {
    ElMessage.error('SMTP服务器地址不能为空')
    return
  }
  if (!smtpForm.username.trim()) {
    ElMessage.error('SMTP用户名不能为空')
    return
  }

  const basePayload = {
    name: smtpForm.name.trim() || '默认配置',
    enabled: Boolean(smtpForm.enabled),
    priority: Number(smtpForm.priority) || 0,
    host: smtpForm.host.trim(),
    port: Number(smtpForm.port) || 465,
    username: smtpForm.username.trim(),
    use_ssl: Boolean(smtpForm.use_ssl),
    use_tls: Boolean(smtpForm.use_tls),
    sender_name: (smtpForm.sender_name || '').trim(),
    sender_email: (smtpForm.sender_email || '').trim(),
    daily_limit: Number(smtpForm.daily_limit) || 0,
  }

  try {
    if (smtpEditMode.value) {
      const payload = { ...basePayload }
      if (smtpForm.password) payload.password = smtpForm.password

      const res = await updateSmtpConfig(smtpForm.id, payload)
      if (!res?.success) {
        ElMessage.error(res?.error || '更新失败')
        return
      }
      ElMessage.success('保存成功')
    } else {
      const payload = { ...basePayload }
      if (smtpForm.password) payload.password = smtpForm.password
      const res = await createSmtpConfig(payload)
      if (!res?.success) {
        ElMessage.error(res?.error || '创建失败')
        return
      }
      ElMessage.success('创建成功')
    }

    smtpDialogOpen.value = false
    await loadSmtpConfigs()
  } catch {
    // handled by interceptor
  }
}

async function doTestSmtp() {
  if (!smtpEditMode.value || !smtpForm.id) {
    ElMessage.error('请先保存配置后再测试')
    return
  }

  let email
  try {
    const res = await ElMessageBox.prompt('请输入测试收件邮箱', '测试连接', {
      inputPlaceholder: 'name@example.com',
      confirmButtonText: '发送测试邮件',
      cancelButtonText: '取消',
      inputValidator: (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(v || '').trim()),
      inputErrorMessage: '邮箱格式不正确',
    })
    email = String(res.value || '').trim()
  } catch {
    return
  }

  try {
    const res = await testSmtpConfig(smtpForm.id, email)
    if (res?.success) {
      ElMessage.success('测试成功，邮件已发送')
      await loadSmtpConfigs()
    } else {
      await ElMessageBox.alert(res?.error || '测试失败', '测试失败', { confirmButtonText: '知道了' })
    }
  } catch {
    // handled by interceptor
  }
}

async function doSetPrimary() {
  if (!smtpEditMode.value || !smtpForm.id) return
  try {
    await ElMessageBox.confirm('确定将该配置设为主配置吗？', '设为主配置', {
      confirmButtonText: '设为主配置',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }

  try {
    const res = await setPrimarySmtpConfig(smtpForm.id)
    if (!res?.success) {
      ElMessage.error(res?.error || '设置失败')
      return
    }
    ElMessage.success('已设为主配置')
    smtpDialogOpen.value = false
    await loadSmtpConfigs()
  } catch {
    // handled by interceptor
  }
}

async function doClearPrimary() {
  if (!smtpEditMode.value) return
  try {
    await ElMessageBox.confirm('确定取消主配置吗？取消后将按优先级选择可用SMTP。', '取消主配置', {
      confirmButtonText: '取消主配置',
      cancelButtonText: '保留',
      type: 'warning',
    })
  } catch {
    return
  }

  try {
    const res = await clearPrimarySmtpConfig()
    if (!res?.success) {
      ElMessage.error(res?.error || '操作失败')
      return
    }
    ElMessage.success('已取消主配置')
    smtpDialogOpen.value = false
    await loadSmtpConfigs()
  } catch {
    // handled by interceptor
  }
}

async function doDeleteSmtp() {
  if (!smtpEditMode.value || !smtpForm.id) return
  try {
    await ElMessageBox.confirm('确定删除该SMTP配置吗？此操作不可恢复。', '删除配置', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'error',
    })
  } catch {
    return
  }

  try {
    const res = await deleteSmtpConfig(smtpForm.id)
    if (!res?.success) {
      ElMessage.error(res?.error || '删除失败')
      return
    }
    ElMessage.success('已删除')
    smtpDialogOpen.value = false
    await loadSmtpConfigs()
  } catch {
    // handled by interceptor
  }
}

// ========== 邮件统计 / 日志 ==========
const emailStatsLoading = ref(false)
const emailStats = ref({})

const emailLogsLoading = ref(false)
const emailLogTypeFilter = ref('')
const emailLogStatusFilter = ref('')
const emailLogPage = ref(1)
const emailLogPageSize = 15
const emailLogs = ref([])
const emailLogTotal = ref(0)
const emailLogTotalPages = ref(1)

function emailTypeLabel(type) {
  const map = {
    register: '注册验证',
    reset: '密码重置',
    bind: '邮箱绑定',
    task_complete: '任务完成',
    security_alert: '安全告警',
  }
  return map[type] || type
}

function emailLogUserLabel(row) {
  if (row?.username && row?.user_id) return `${row.username} (#${row.user_id})`
  if (row?.user_id) return `用户#${row.user_id}`
  return '系统'
}


const emailSummaryCards = computed(() => [
  { key: 'total_sent', label: '总发送', value: emailStats.value?.total_sent || 0, tone: 'blue' },
  { key: 'total_success', label: '成功', value: emailStats.value?.total_success || 0, tone: 'green' },
  { key: 'total_failed', label: '失败', value: emailStats.value?.total_failed || 0, tone: 'red' },
  { key: 'success_rate', label: '成功率', value: `${emailStats.value?.success_rate || 0}%`, tone: 'purple' },
])

const emailTypeCards = computed(() => [
  { key: 'register_sent', label: '注册验证', value: emailStats.value?.register_sent || 0, tone: 'cyan' },
  { key: 'reset_sent', label: '密码重置', value: emailStats.value?.reset_sent || 0, tone: 'orange' },
  { key: 'bind_sent', label: '邮箱绑定', value: emailStats.value?.bind_sent || 0, tone: 'purple' },
  { key: 'task_complete_sent', label: '任务完成', value: emailStats.value?.task_complete_sent || 0, tone: 'green' },
])

async function loadEmailStats() {
  emailStatsLoading.value = true
  try {
    emailStats.value = await fetchEmailStats()
  } catch {
    emailStats.value = {}
  } finally {
    emailStatsLoading.value = false
  }
}

async function loadEmailLogs(page = 1) {
  emailLogsLoading.value = true
  try {
    const params = {
      page,
      page_size: emailLogPageSize,
    }
    if (emailLogTypeFilter.value) params.type = emailLogTypeFilter.value
    if (emailLogStatusFilter.value) params.status = emailLogStatusFilter.value

    const data = await fetchEmailLogs(params)
    emailLogs.value = data?.logs || []
    emailLogTotal.value = data?.total || 0
    emailLogPage.value = data?.page || page
    emailLogTotalPages.value = data?.total_pages || 1
  } catch {
    emailLogs.value = []
    emailLogTotal.value = 0
    emailLogTotalPages.value = 1
  } finally {
    emailLogsLoading.value = false
  }
}

async function onCleanupEmailLogs() {
  let days
  try {
    const res = await ElMessageBox.prompt('请输入保留天数（将删除该天数之前的日志）', '清理日志', {
      inputValue: '30',
      confirmButtonText: '清理',
      cancelButtonText: '取消',
      inputValidator: (v) => {
        const n = parseInt(String(v), 10)
        return Number.isFinite(n) && n >= 7
      },
      inputErrorMessage: '天数必须大于等于7',
    })
    days = parseInt(String(res.value), 10)
  } catch {
    return
  }

  try {
    await ElMessageBox.confirm(`确定删除 ${days} 天之前的邮件日志吗？`, '二次确认', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }

  try {
    const res = await cleanupEmailLogs(days)
    if (!res?.success) {
      ElMessage.error(res?.error || '清理失败')
      return
    }
    ElMessage.success(`已清理 ${res.deleted} 条日志`)
    await loadEmailLogs(1)
  } catch {
    // handled by interceptor
  }
}

async function refreshAll() {
  await Promise.all([loadEmailSettings(), loadSmtpConfigs(), loadEmailStats(), loadEmailLogs(1)])
}

onMounted(refreshAll)
</script>

<template>
  <div class="page-stack">
    <div class="app-page-title">
      <h2>邮件配置</h2>
    </div>

    <el-card shadow="never" :body-style="{ padding: '16px' }" class="card" v-loading="emailSettingsLoading">
      <h3 class="section-title">全局设置</h3>

      <el-form label-width="140px">
        <el-form-item label="启用邮件功能">
          <el-switch v-model="settings.enabled" :disabled="emailSettingsSaving" @change="scheduleSaveEmailSettings" />
        </el-form-item>
        <el-form-item label="启用故障转移">
          <el-switch
            v-model="settings.failover_enabled"
            :disabled="emailSettingsSaving"
            @change="scheduleSaveEmailSettings"
          />
        </el-form-item>
        <el-form-item label="启用注册邮箱验证">
          <el-switch
            v-model="settings.register_verify_enabled"
            :disabled="emailSettingsSaving"
            @change="scheduleSaveEmailSettings"
          />
        </el-form-item>

        <el-divider content-position="left">通知设置</el-divider>
        <el-form-item label="启用任务完成通知">
          <el-switch
            v-model="settings.task_notify_enabled"
            :disabled="emailSettingsSaving"
            @change="scheduleSaveEmailSettings"
          />
        </el-form-item>
        <el-form-item label="新设备登录提醒">
          <el-switch
            v-model="settings.login_alert_enabled"
            :disabled="emailSettingsSaving"
            @change="scheduleSaveEmailSettings"
          />
          <div class="help">当检测到新设备或新IP登录时，发送邮件提醒用户</div>
        </el-form-item>
        <el-form-item label="网站基础URL">
          <el-input
            v-model="settings.base_url"
            placeholder="例如: https://example.com"
            :disabled="emailSettingsSaving"
            @blur="scheduleSaveEmailSettings"
          />
          <div class="help">用于生成邮件中的验证链接，留空则使用默认配置。</div>
        </el-form-item>
      </el-form>

      <div class="help app-muted">最近更新时间：{{ settings.updated_at || '-' }}</div>
    </el-card>

    <el-card shadow="never" :body-style="{ padding: '16px' }" class="card">
      <div class="section-head">
        <h3 class="section-title">SMTP配置列表</h3>
        <el-button type="primary" @click="openCreateSmtp">+ 添加配置</el-button>
      </div>

      <div class="table-wrap">
        <el-table :data="smtpConfigs" v-loading="smtpLoading" style="width: 100%">
          <el-table-column label="状态" width="90">
            <template #default="{ row }">
              <el-tag :type="smtpStatusMeta(row).type" effect="light">
                {{ smtpStatusMeta(row).label }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" min-width="160" />
          <el-table-column label="服务器" min-width="200">
            <template #default="{ row }">{{ row.host }}:{{ row.port }}</template>
          </el-table-column>
          <el-table-column label="今日/限额" width="110">
            <template #default="{ row }">{{ smtpDailyText(row) }}</template>
          </el-table-column>
          <el-table-column label="成功率" width="100">
            <template #default="{ row }">{{ row.success_rate }}%</template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="openEditSmtp(row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <el-card shadow="never" :body-style="{ padding: '16px' }" class="card" v-loading="emailStatsLoading">
      <h3 class="section-title">邮件发送统计</h3>

      <MetricGrid :items="emailSummaryCards" :loading="emailStatsLoading" :min-width="160" />

      <div class="sub-stats">
        <MetricGrid :items="emailTypeCards" :loading="emailStatsLoading" :min-width="150" />
      </div>

      <div class="help app-muted">最后更新：{{ emailStats.last_updated || '-' }}</div>
    </el-card>

    <el-card shadow="never" :body-style="{ padding: '16px' }" class="card">
      <div class="section-head">
        <h3 class="section-title">邮件发送日志</h3>
        <div class="toolbar">
          <el-select v-model="emailLogTypeFilter" style="width: 140px" @change="loadEmailLogs(1)">
            <el-option label="全部类型" value="" />
            <el-option label="注册验证" value="register" />
            <el-option label="密码重置" value="reset" />
            <el-option label="邮箱绑定" value="bind" />
            <el-option label="任务完成" value="task_complete" />
            <el-option label="安全告警" value="security_alert" />
          </el-select>
          <el-select v-model="emailLogStatusFilter" style="width: 120px" @change="loadEmailLogs(1)">
            <el-option label="全部状态" value="" />
            <el-option label="成功" value="success" />
            <el-option label="失败" value="failed" />
          </el-select>
          <el-button type="danger" plain @click="onCleanupEmailLogs">清理日志</el-button>
        </div>
      </div>

      <div class="table-wrap">
        <el-table :data="emailLogs" v-loading="emailLogsLoading" style="width: 100%">
          <el-table-column prop="created_at" label="时间" width="180" />
          <el-table-column prop="email_to" label="收件人" min-width="180" />
          <el-table-column label="来源用户" min-width="160">
            <template #default="{ row }">
              <span class="ellipsis" :title="emailLogUserLabel(row)">{{ emailLogUserLabel(row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="类型" width="120">
            <template #default="{ row }">{{ emailTypeLabel(row.email_type) }}</template>
          </el-table-column>
          <el-table-column label="主题" min-width="220">
            <template #default="{ row }">
              <span class="ellipsis" :title="row.subject">{{ row.subject }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="90">
            <template #default="{ row }">
              <el-tag :type="row.status === 'success' ? 'success' : 'danger'" effect="light">
                {{ row.status === 'success' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="错误" min-width="200">
            <template #default="{ row }">
              <span class="ellipsis" :title="row.error_message || ''">{{ row.error_message || '-' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          v-model:current-page="emailLogPage"
          :page-size="emailLogPageSize"
          :total="emailLogTotal"
          layout="prev, pager, next, ->, total"
          @current-change="loadEmailLogs"
        />
        <div class="page-hint app-muted">第 {{ emailLogPage }} / {{ emailLogTotalPages }} 页</div>
      </div>
    </el-card>

    <el-dialog
      v-model="smtpDialogOpen"
      :title="smtpEditMode ? '编辑SMTP配置' : '添加SMTP配置'"
      width="min(560px, 92vw)"
    >
      <el-form label-width="120px">
        <el-form-item label="名称">
          <el-input v-model="smtpForm.name" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="smtpForm.enabled" />
        </el-form-item>
        <el-form-item label="邮箱模板">
          <div style="width: 100%">
            <el-select v-model="smtpTemplateKey" placeholder="选择常用邮箱模板" style="width: 100%" @change="applySmtpTemplate">
              <el-option v-for="t in SMTP_TEMPLATES" :key="t.key" :label="t.label" :value="t.key" />
            </el-select>
            <div
              v-if="currentSmtpTemplate.note || (currentSmtpTemplate.links && currentSmtpTemplate.links.length)"
              class="help"
            >
              <span v-if="currentSmtpTemplate.note">{{ currentSmtpTemplate.note }}</span>
              <template v-if="currentSmtpTemplate.links && currentSmtpTemplate.links.length">
                <span v-if="currentSmtpTemplate.note"> · </span>
                <span v-for="(l, idx) in currentSmtpTemplate.links" :key="l.url">
                  <el-link :href="l.url" target="_blank" type="primary" :underline="false">{{ l.label }}</el-link>
                  <span v-if="idx < currentSmtpTemplate.links.length - 1"> · </span>
                </span>
              </template>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="服务器">
          <el-input v-model="smtpForm.host" placeholder="smtp.example.com" />
        </el-form-item>
        <el-form-item label="端口">
          <el-input-number v-model="smtpForm.port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="smtpForm.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="smtpForm.password" type="password" show-password :placeholder="smtpPasswordPlaceholder" />
        </el-form-item>
        <el-form-item label="SSL">
          <el-switch v-model="smtpForm.use_ssl" />
        </el-form-item>
        <el-form-item label="TLS">
          <el-switch v-model="smtpForm.use_tls" />
        </el-form-item>
        <el-form-item label="发件人名称">
          <el-input v-model="smtpForm.sender_name" />
        </el-form-item>
        <el-form-item label="发件人邮箱">
          <el-input v-model="smtpForm.sender_email" placeholder="可选" />
        </el-form-item>
        <el-form-item label="每日限额">
          <el-input-number v-model="smtpForm.daily_limit" :min="0" :max="1000000" />
        </el-form-item>
        <el-form-item label="优先级">
          <el-input-number v-model="smtpForm.priority" :min="0" :max="1000" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-actions">
          <el-button @click="doTestSmtp">测试连接</el-button>
          <el-button v-if="smtpEditMode && smtpIsPrimary" type="warning" plain @click="doClearPrimary">取消主配置</el-button>
          <el-button v-if="smtpEditMode && !smtpIsPrimary" @click="doSetPrimary">设为主配置</el-button>
          <el-button v-if="smtpEditMode" type="danger" plain @click="doDeleteSmtp">删除配置</el-button>
          <div class="spacer"></div>
          <el-button @click="smtpDialogOpen = false">取消</el-button>
          <el-button type="primary" @click="saveSmtp">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page-stack {
  display: flex;
  flex-direction: column;
  gap: 14px;
  min-width: 0;
}

.toolbar {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.card {
  border-radius: var(--app-radius);
  border: 1px solid var(--app-border);
  background: var(--app-card-bg);
  box-shadow: var(--app-shadow-soft);
}

.section-head {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.section-title {
  margin: 0;
  font-size: 15px;
  font-weight: 800;
  letter-spacing: 0.2px;
}

.help {
  margin-top: 8px;
  font-size: 12px;
  color: var(--app-muted);
}

.table-wrap {
  overflow-x: auto;
  border-radius: 10px;
  border: 1px solid var(--app-border);
  background: #fff;
}


.sub-stats {
  margin-top: 12px;
}

.ellipsis {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  margin-top: 14px;
  flex-wrap: wrap;
}

.page-hint {
  font-size: 12px;
}

.dialog-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.spacer {
  flex: 1;
}
</style>
