<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { notificationApi } from '@/api/service-monitor'
import type { NotificationConfig } from '@/types/service-monitor'

// Config state
const config = ref<NotificationConfig>({
  email: {
    enabled: false,
    smtp_host: '',
    smtp_port: 465,
    smtp_user: '',
    smtp_password: '',
    use_ssl: true,
    recipients: [],
    subject_template: '【巡检报告】{target} - {status}',
  },
  dingtalk: {
    enabled: false,
    webhook_url: '',
    secret: '',
    at_mobiles: [],
  },
  wecom: {
    enabled: false,
    webhook: '',
  },
  trigger: {
    on_complete: true,
    on_abnormal_only: false,
    include_details: true,
    include_link: true,
  },
  alert_on_consecutive: {
    enabled: false,
    consecutive_threshold: 3,
    alert_level: 'critical',
    channels: [],
  },
  report_missing: {
    enabled: false,
    missing_days: 2,
    channels: [],
  },
})

const loading = ref(false)
const saving = ref(false)

// Test states
const testingEmail = ref(false)
const testingDingtalk = ref(false)
const testingWecom = ref(false)
const emailTestResult = ref<{ success: boolean; message: string } | null>(null)
const dingtalkTestResult = ref<{ success: boolean; message: string } | null>(null)
const wecomTestResult = ref<{ success: boolean; message: string } | null>(null)

// Form helpers
const emailRecipients = ref('')
const dingtalkAtMobiles = ref('')

// Load config
async function loadConfig() {
  loading.value = true
  try {
    const res = await notificationApi.getNotificationConfig()
    if (res.success && res.config) {
      config.value = {
        ...res.config,
        email: res.config.email || config.value.email,
        dingtalk: res.config.dingtalk || config.value.dingtalk,
        wecom: res.config.wecom || config.value.wecom,
        trigger: res.config.trigger || config.value.trigger,
        alert_on_consecutive: res.config.alert_on_consecutive || config.value.alert_on_consecutive,
        report_missing: res.config.report_missing || config.value.report_missing,
      }
      emailRecipients.value = (config.value.email.recipients || []).join(', ')
      dingtalkAtMobiles.value = (config.value.dingtalk.at_mobiles || []).join(', ')
    }
  } catch {
    ElMessage.error('加载配置失败')
  } finally {
    loading.value = false
  }
}

// Save config
async function saveConfig(silent = false) {
  // Sync text fields to arrays
  config.value.email.recipients = emailRecipients.value.split(',').map(s => s.trim()).filter(Boolean)
  config.value.dingtalk.at_mobiles = dingtalkAtMobiles.value.split(',').map(s => s.trim()).filter(Boolean)

  saving.value = true
  try {
    const res = await notificationApi.saveNotificationConfig(config.value)
    if (res.success) {
      if (!silent) ElMessage.success('配置已保存')
      return true
    } else {
      if (!silent) ElMessage.error('保存失败')
      return false
    }
  } catch (e: any) {
    if (!silent) ElMessage.error(e?.message || '请求失败')
    return false
  } finally {
    saving.value = false
  }
}

// Test handlers
async function handleTestEmail() {
  testingEmail.value = true
  emailTestResult.value = null
  try {
    await saveConfig(true)
    const res = await notificationApi.testEmail()
    emailTestResult.value = { success: res.success, message: res.message || (res.success ? '发送成功' : '发送失败') }
  } catch (e: any) {
    emailTestResult.value = { success: false, message: e?.message || '请求失败' }
  } finally {
    testingEmail.value = false
  }
}

async function handleTestDingtalk() {
  testingDingtalk.value = true
  dingtalkTestResult.value = null
  try {
    await saveConfig(true)
    const res = await notificationApi.testDingTalk()
    dingtalkTestResult.value = { success: res.success, message: res.message || (res.success ? '发送成功' : '发送失败') }
  } catch (e: any) {
    dingtalkTestResult.value = { success: false, message: e?.message || '请求失败' }
  } finally {
    testingDingtalk.value = false
  }
}

async function handleTestWecom() {
  testingWecom.value = true
  wecomTestResult.value = null
  try {
    await saveConfig(true)
    const res = await notificationApi.testWeCom()
    wecomTestResult.value = { success: res.success, message: res.message || (res.success ? '发送成功' : '发送失败') }
  } catch (e: any) {
    wecomTestResult.value = { success: false, message: e?.message || '请求失败' }
  } finally {
    testingWecom.value = false
  }
}

// Alert channels toggle
function isAlertChannel(channel: string) {
  return (config.value.alert_on_consecutive?.channels || []).includes(channel)
}

function toggleAlertChannel(channel: string) {
  if (!config.value.alert_on_consecutive) {
    config.value.alert_on_consecutive = { enabled: false, consecutive_threshold: 3, alert_level: 'critical', channels: [] }
  }
  const channels = config.value.alert_on_consecutive.channels || []
  const idx = channels.indexOf(channel)
  if (idx >= 0) channels.splice(idx, 1)
  else channels.push(channel)
}

// Missing report channels toggle
function isMissingChannel(channel: string) {
  return (config.value.report_missing?.channels || []).includes(channel)
}

function toggleMissingChannel(channel: string) {
  if (!config.value.report_missing) {
    config.value.report_missing = { enabled: false, missing_days: 2, channels: [] }
  }
  const channels = config.value.report_missing.channels || []
  const idx = channels.indexOf(channel)
  if (idx >= 0) channels.splice(idx, 1)
  else channels.push(channel)
}

onMounted(loadConfig)
</script>

<template>
  <div class="page-notification" v-loading="loading">
    <div class="section-head">
      <h1 class="section-title">🔔 通知配置</h1>
    </div>

    <!-- Email Section -->
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">📧 邮件通知</span>
          <el-switch v-model="config.email.enabled" />
        </div>
      </template>
      <div v-if="config.email.enabled" class="config-body">
        <div class="form-row">
          <el-form-item label="SMTP 服务器">
            <el-input v-model="config.email.smtp_host" placeholder="如：smtp.qq.com" />
          </el-form-item>
          <el-form-item label="端口" class="port-input">
            <el-input-number v-model="config.email.smtp_port" :min="1" :max="65535" />
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="发件人邮箱">
            <el-input v-model="config.email.smtp_user" placeholder="admin@example.com" />
          </el-form-item>
          <el-form-item label="邮箱授权码">
            <el-input v-model="config.email.smtp_password" type="password" placeholder="SMTP 认证密码" show-password />
          </el-form-item>
        </div>
        <el-form-item label="收件人列表">
          <el-input v-model="emailRecipients" type="textarea" :rows="2" placeholder="多个邮箱用英文逗号分隔" />
          <div class="form-hint">多个收件人用英文逗号分隔</div>
        </el-form-item>
        <div class="toggle-row">
          <span class="toggle-label">使用 SSL 加密</span>
          <el-switch v-model="config.email.use_ssl" />
        </div>
        <el-form-item label="邮件主题模板">
          <el-input v-model="config.email.subject_template" placeholder="【巡检报告】{target} - {status}" />
          <div class="form-hint">支持变量：{target} {status} {suite}</div>
        </el-form-item>
        <div class="test-section">
          <el-button :loading="testingEmail" @click="handleTestEmail">发送测试邮件</el-button>
          <span v-if="emailTestResult" class="test-msg" :class="emailTestResult.success ? 'success' : 'error'">
            {{ emailTestResult.message }}
          </span>
        </div>
      </div>
    </el-card>

    <!-- DingTalk Section -->
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">📱 钉钉机器人</span>
          <el-switch v-model="config.dingtalk.enabled" />
        </div>
      </template>
      <div v-if="config.dingtalk.enabled" class="config-body">
        <el-form-item label="Webhook 地址">
          <el-input v-model="config.dingtalk.webhook_url" placeholder="https://oapi.dingtalk.com/robot/send?access_token=xxx" />
          <div class="form-hint">钉钉群机器人设置页面获取</div>
        </el-form-item>
        <el-form-item label="签名密钥（可选）">
          <el-input v-model="config.dingtalk.secret" type="password" placeholder="加签机器人的密钥" show-password />
          <div class="form-hint">如果机器人设置了加签，需要填写密钥</div>
        </el-form-item>
        <el-form-item label="@人员手机号（可选）">
          <el-input v-model="dingtalkAtMobiles" placeholder="多个手机号用英文逗号分隔" />
        </el-form-item>
        <div class="test-section">
          <el-button :loading="testingDingtalk" @click="handleTestDingtalk">发送测试消息</el-button>
          <span v-if="dingtalkTestResult" class="test-msg" :class="dingtalkTestResult.success ? 'success' : 'error'">
            {{ dingtalkTestResult.message }}
          </span>
        </div>
      </div>
    </el-card>

    <!-- WeCom Section -->
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">💬 企业微信机器人</span>
          <el-switch v-model="config.wecom.enabled" />
        </div>
      </template>
      <div v-if="config.wecom.enabled" class="config-body">
        <el-form-item label="Webhook 地址">
          <el-input v-model="config.wecom.webhook" placeholder="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx" />
        </el-form-item>
        <div class="test-section">
          <el-button :loading="testingWecom" @click="handleTestWecom">发送测试消息</el-button>
          <span v-if="wecomTestResult" class="test-msg" :class="wecomTestResult.success ? 'success' : 'error'">
            {{ wecomTestResult.message }}
          </span>
        </div>
      </div>
    </el-card>

    <!-- Trigger Section -->
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">⚡ 触发条件</span>
        </div>
      </template>
      <div class="config-body">
        <div class="toggle-row">
          <span class="toggle-label">报告完成后立即通知</span>
          <el-switch v-model="config.trigger.on_complete" />
        </div>
        <div class="toggle-row">
          <span class="toggle-label">仅异常（警告/严重）时通知</span>
          <el-switch v-model="config.trigger.on_abnormal_only" />
        </div>
        <div class="toggle-row">
          <span class="toggle-label">包含异常详情</span>
          <el-switch v-model="config.trigger.include_details" />
        </div>
        <div class="toggle-row">
          <span class="toggle-label">包含报告链接</span>
          <el-switch v-model="config.trigger.include_link" />
        </div>
      </div>
    </el-card>

    <!-- Alert on Consecutive Section -->
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">🔄 连续异常告警</span>
          <el-switch v-model="config.alert_on_consecutive!.enabled" />
        </div>
      </template>
      <div v-if="config.alert_on_consecutive?.enabled" class="config-body">
        <div class="form-row">
          <el-form-item label="连续次数阈值">
            <el-input-number v-model="config.alert_on_consecutive!.consecutive_threshold" :min="2" :max="10" />
            <div class="form-hint">同一检测项连续 N 次异常时发送告警</div>
          </el-form-item>
          <el-form-item label="告警级别">
            <el-select v-model="config.alert_on_consecutive!.alert_level">
              <el-option value="critical" label="仅严重" />
              <el-option value="all" label="警告 + 严重" />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="通知渠道">
          <div class="channel-checks">
            <el-checkbox :model-value="isAlertChannel('email')" @change="toggleAlertChannel('email')">邮件</el-checkbox>
            <el-checkbox :model-value="isAlertChannel('dingtalk')" @change="toggleAlertChannel('dingtalk')">钉钉</el-checkbox>
            <el-checkbox :model-value="isAlertChannel('wecom')" @change="toggleAlertChannel('wecom')">企微</el-checkbox>
          </div>
          <div class="form-hint">复用上方已配置的通知渠道</div>
        </el-form-item>
      </div>
    </el-card>

    <!-- Report Missing Section -->
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">📭 报告缺失告警</span>
          <el-switch v-model="config.report_missing!.enabled" />
        </div>
      </template>
      <div v-if="config.report_missing?.enabled" class="config-body">
        <div class="form-row">
          <el-form-item label="缺失天数阈值">
            <el-input-number v-model="config.report_missing!.missing_days" :min="1" :max="14" />
            <div class="form-hint">目标超过 N 天未生成报告时发送告警（每天 09:30 检测）</div>
          </el-form-item>
        </div>
        <el-form-item label="通知渠道">
          <div class="channel-checks">
            <el-checkbox :model-value="isMissingChannel('email')" @change="toggleMissingChannel('email')">邮件</el-checkbox>
            <el-checkbox :model-value="isMissingChannel('dingtalk')" @change="toggleMissingChannel('dingtalk')">钉钉</el-checkbox>
            <el-checkbox :model-value="isMissingChannel('wecom')" @change="toggleMissingChannel('wecom')">企微</el-checkbox>
          </div>
          <div class="form-hint">复用上方已配置的通知渠道</div>
        </el-form-item>
      </div>
    </el-card>

    <!-- Save Button -->
    <div class="actions-bar">
      <el-button type="primary" :loading="saving" @click="saveConfig()">保存配置</el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.page-notification {
  padding: 0 0 40px;
}

.section-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: 700;
  color: $gray-900;
}

.config-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 16px;

  :deep(.el-card__header) {
    padding: 14px 20px;
    background: $gray-50;
    border-bottom: 1px solid $gray-200;
  }
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-title {
  font-size: 16px;
  font-weight: 700;
  color: $gray-900;
}

.config-body {
  padding: 4px 0;
}

.form-row {
  display: flex;
  gap: 16px;

  .el-form-item {
    flex: 1;
    margin-bottom: 14px;
  }

  .port-input {
    flex: 0 0 120px;
  }
}

.el-form-item {
  margin-bottom: 14px;
}

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

.toggle-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid $gray-100;

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

.toggle-label {
  font-size: 14px;
  color: $gray-700;
}

.test-section {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 10px;
}

.test-msg {
  font-size: 13px;
  padding: 6px 12px;
  border-radius: 6px;

  &.success {
    background: #dcfce7;
    color: #15803d;
  }

  &.error {
    background: #fee2e2;
    color: #b91c1c;
  }
}

.channel-checks {
  display: flex;
  gap: 16px;
  margin-top: 6px;
}

.actions-bar {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

@media screen and (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 0;

    .el-form-item {
      margin-bottom: 14px;
    }

    .port-input {
      flex: 1;
    }
  }

  .config-card {
    margin-bottom: 12px;
  }

  .section-head {
    margin-bottom: 12px;
  }
}

@media screen and (max-width: 480px) {
  .card-title {
    font-size: 14px;
  }

  .config-body {
    padding: 0;
  }
}
</style>
