<template>
  <div class="template-edit-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <a-button type="text" @click="handleBack">
          <template #icon><icon-left /></template>
          返回列表
        </a-button>
        <a-divider direction="vertical" />
        <h2 class="page-title">{{ pageTitle }}</h2>
      </div>
      <div class="header-right">
        <a-space>
          <a-button @click="handleBack">取消</a-button>
          <a-button type="primary" :loading="submitting" @click="handleSubmit">
            {{ isEdit ? '保存' : '创建' }}
          </a-button>
        </a-space>
      </div>
    </div>

    <!-- 表单内容 -->
    <div class="page-content">
      <a-spin :loading="loading" style="width: 100%">
        <a-row :gutter="20">
          <!-- 左侧：基础信息 -->
          <a-col :xs="24" :sm="24" :md="10" :lg="8">
            <a-form
              ref="formRef"
              :model="formData"
              :rules="formRules"
              layout="vertical"
            >
              <a-card class="info-card" title="基础信息">
                <a-form-item label="模板名称" field="name" required>
                  <a-input
                    v-model="formData.name"
                    placeholder="请输入模板名称"
                    allow-clear
                  />
                </a-form-item>

                <a-form-item label="模板分类" field="category" required>
                  <a-select v-model="formData.category" placeholder="请选择分类" @change="handleCategoryChange">
                    <a-option v-for="item in TEMPLATE_CATEGORIES" :key="item.value" :value="item.value">
                      {{ item.label }}
                    </a-option>
                  </a-select>
                </a-form-item>

                <a-form-item label="是否启用" field="enabled">
                  <a-switch v-model="formData.enabled" />
                </a-form-item>

                <a-form-item label="标签" field="tagsList" required>
                  <a-input-tag
                    v-model="formData.tagsList"
                    placeholder="输入后按回车添加"
                    allow-clear
                  />
                </a-form-item>

                <a-form-item label="描述" field="description">
                  <a-textarea
                    v-model="formData.description"
                    placeholder="请输入模板描述"
                    :max-length="500"
                    :auto-size="{ minRows: 3, maxRows: 5 }"
                    show-word-limit
                  />
                </a-form-item>
              </a-card>

              <!-- 通知渠道 -->
              <a-card class="info-card" title="通知渠道">
                <a-form-item label="选择通知渠道" field="selectedChannelIds" required>
                  <a-select
                    v-model="formData.selectedChannelIds"
                    placeholder="请选择通知渠道"
                    multiple
                    allow-search
                    :filter-option="false"
                    @search="handleChannelSearch"
                    @dropdown-visible-change="handleChannelDropdownChange"
                  >
                    <a-option v-for="item in channelOptions" :key="item.id" :value="item.id">
                      {{ item.name }}
                    </a-option>
                  </a-select>
                </a-form-item>
              </a-card>

              <!-- 抑制规则 -->
              <a-card class="info-card" title="抑制规则">
                <a-form-item label="选择抑制规则" field="suppression_rule_ids" required>
                  <a-select
                    v-model="formData.suppression_rule_ids"
                    placeholder="请选择抑制规则"
                    multiple
                    allow-search
                    :filter-option="false"
                    @search="handleSuppressionSearch"
                    @dropdown-visible-change="handleSuppressionDropdownChange"
                  >
                    <a-option v-for="item in suppressionOptions" :key="item.id" :value="item.id">
                      {{ item.name }}
                    </a-option>
                  </a-select>
                </a-form-item>
              </a-card>
            </a-form>
          </a-col>

          <!-- 右侧：规则配置 -->
          <a-col :xs="24" :sm="24" :md="14" :lg="16">
            <a-card class="rules-card">
              <template #title>
                <div class="rules-card-title">
                  <span>规则配置</span>
                  <a-badge :count="formData.rules.length" :dot-style="{ backgroundColor: '#165dff' }" />
                </div>
              </template>
              <template #extra>
                <a-button type="primary" size="small" @click="handleAddRule">
                  <template #icon><icon-plus /></template>
                  添加规则
                </a-button>
              </template>

              <div class="rules-content">
                <a-empty v-if="formData.rules.length === 0" description="暂无规则，请添加">
                  <a-button type="primary" @click="handleAddRule">
                    <template #icon><icon-plus /></template>
                    添加第一条规则
                  </a-button>
                </a-empty>
                <RuleEditor
                  v-else
                  ref="ruleEditorRef"
                  v-model:rules="formData.rules"
                  :severity-options="severityOptions"
                  @remove="handleRemoveRule"
                />
              </div>
            </a-card>
          </a-col>
        </a-row>
      </a-spin>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue/es/form'
import RuleEditor from '../components/RuleEditor.vue'
import {
  createTemplate,
  updateTemplate,
  fetchTemplateDetail,
  fetchChannelList,
  fetchSuppressionList,
  fetchSeverityOptions,
  fetchMetricsMeta,
  TEMPLATE_CATEGORIES,
  type AlertTemplate,
  type AlertRule,
  type NotificationChannel,
  type SuppressionRule,
  type AlertSeverity,
  type MetricMeta,
} from '@/api/ops/alertTemplate'

interface RuleItem extends AlertRule {
  _metrics?: MetricMeta[]
  _metricsLoading?: boolean
}

interface FormData {
  name: string
  category: string
  description: string
  enabled: boolean
  tagsList: string[]
  rules: RuleItem[]
  selectedChannelIds: number[]
  suppression_rule_ids: number[]
}

const route = useRoute()
const router = useRouter()

// 页面状态
const isEdit = ref(false)
const templateId = ref<number | null>(null)
const pageTitle = ref('新建告警模板')
const loading = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()
const ruleEditorRef = ref<{ validate: () => Promise<any> } | null>(null)

// 下拉选项
const channelOptions = ref<NotificationChannel[]>([])
const suppressionOptions = ref<SuppressionRule[]>([])
const severityOptions = ref<AlertSeverity[]>([])

// 表单数据
const formData = ref<FormData>({
  name: '',
  category: '',
  description: '',
  enabled: true,
  tagsList: [],
  rules: [],
  selectedChannelIds: [],
  suppression_rule_ids: [],
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入模板名称' },
    { minLength: 2, message: '模板名称至少2个字符' },
    { maxLength: 100, message: '模板名称最多100个字符' },
  ],
  category: [{ required: true, message: '请选择模板分类' }],
  tagsList: [{ required: true, type: 'array', message: '请添加标签' }],
  selectedChannelIds: [{ required: true, type: 'array', message: '请选择通知渠道' }],
  suppression_rule_ids: [{ required: true, type: 'array', message: '请选择抑制规则' }],
}

// 初始化页面
const initPage = async () => {
  // 加载下拉选项
  await loadSeverityOptions()
  loadChannelOptions()
  loadSuppressionOptions()

  // 判断是否为编辑模式
  const id = route.query.id
  if (id) {
    isEdit.value = true
    templateId.value = Number(id)
    pageTitle.value = '编辑告警模板'
    await loadTemplateDetail()
  }
}

// 加载模板详情
const loadTemplateDetail = async () => {
  if (!templateId.value) return

  loading.value = true
  try {
    const res: any = await fetchTemplateDetail(templateId.value)
    if (res.code === 0) {
      const details = res.details
      
      // 解析 JSON 字符串字段
      const rules = typeof details.rules === 'string' ? JSON.parse(details.rules) : (details.rules || [])
      const channels = typeof details.channels === 'string' ? JSON.parse(details.channels) : (details.channels || [])
      const suppressionIds = typeof details.suppression_rule_ids === 'string' 
        ? JSON.parse(details.suppression_rule_ids) 
        : (details.suppression_rule_ids || [])
      
      const tagsList = (details.tags || '').split(',').filter(Boolean)
      const selectedChannelIds = (channels || []).map((c: any) => c.channel_id)

      // 初始化规则数据
      const rulesWithMetrics = rules.map((r: any) => ({
        ...r,
        _metrics: [],
        _metricsLoading: false,
      }))

      formData.value = {
        name: details.name,
        category: details.category,
        description: details.description || '',
        enabled: details.enabled ?? true,
        tagsList,
        rules: rulesWithMetrics,
        selectedChannelIds,
        suppression_rule_ids: suppressionIds,
      }

      // 为已有规则加载指标数据
      for (let i = 0; i < rulesWithMetrics.length; i++) {
        if (rulesWithMetrics[i].data_source) {
          await loadMetricsForRule(i)
        }
      }
    } else {
      Message.error(res.msg || '获取模板详情失败')
      router.push('/alert/template')
    }
  } catch (error: any) {
    console.error('获取模板详情失败:', error)
    Message.error(error.message || '获取模板详情失败')
    router.push('/alert/template')
  } finally {
    loading.value = false
  }
}

// 为规则加载指标数据
const loadMetricsForRule = async (index: number) => {
  const rule = formData.value.rules[index]
  if (!rule.data_source || rule._metrics?.length) return

  rule._metricsLoading = true
  try {
    const res: any = await fetchMetricsMeta({
      data_source: rule.data_source,
      limit: 500,
    })
    if (res.code === 0) {
      rule._metrics = res.details?.metrics || []
    }
  } catch (error) {
    console.error('加载指标失败:', error)
  } finally {
    rule._metricsLoading = false
  }
}

// 加载告警级别
const loadSeverityOptions = async () => {
  try {
    const res: any = await fetchSeverityOptions({ enabled: 'true' })
    // 兼容：后端可能返回数组，也可能是 { code, details: { data } }
    const list = Array.isArray(res?.details)
      ? res.details
      : res?.details?.data || res?.details?.list || res?.data || res
    severityOptions.value = Array.isArray(list) ? list : []
  } catch (error) {
    console.error('加载告警级别失败:', error)
  }
}

// 加载通知渠道
const loadChannelOptions = async () => {
  try {
    const res: any = await fetchChannelList({ enabled: true })
    if (res.code === 0) {
      channelOptions.value = res.details?.data || res.details?.list || []
    }
  } catch (error) {
    console.error('加载通知渠道失败:', error)
  }
}

// 加载抑制规则
const loadSuppressionOptions = async () => {
  try {
    const res: any = await fetchSuppressionList({ enabled: true })
    if (res.code === 0) {
      suppressionOptions.value = res.details?.data || res.details?.list || []
    }
  } catch (error) {
    console.error('加载抑制规则失败:', error)
  }
}

// 通知渠道搜索
const handleChannelSearch = async (keyword: string) => {
  try {
    const res: any = await fetchChannelList({ enabled: true, keyword })
    if (res.code === 0) {
      channelOptions.value = res.details?.data || res.details?.list || []
    }
  } catch (error) {
    console.error('搜索通知渠道失败:', error)
  }
}

const handleChannelDropdownChange = (visible: boolean) => {
  if (visible && channelOptions.value.length === 0) {
    loadChannelOptions()
  }
}

// 抑制规则搜索
const handleSuppressionSearch = async (keyword: string) => {
  try {
    const res: any = await fetchSuppressionList({ enabled: true, keyword })
    if (res.code === 0) {
      suppressionOptions.value = res.details?.data || res.details?.list || []
    }
  } catch (error) {
    console.error('搜索抑制规则失败:', error)
  }
}

const handleSuppressionDropdownChange = (visible: boolean) => {
  if (visible && suppressionOptions.value.length === 0) {
    loadSuppressionOptions()
  }
}

// 分类变化时加载默认规则
const handleCategoryChange = (category: string) => {
  if (!isEdit.value && formData.value.rules.length === 0) {
    const defaultRules = getDefaultRules(category)
    formData.value.rules = defaultRules.map(r => ({
      ...r,
      _enabled: true,
      _metrics: [],
      _metricsLoading: false,
    }))
  }
}

// 获取默认规则
const getDefaultRules = (category: string): AlertRule[] => {
  const defaultRulesMap: Record<string, AlertRule[]> = {
    'os': [
      { name: 'CPU使用率过高', data_source: 'dc-host', metric_name: 'cpu_usage', rule_type: 'static', compare_op: '>=', threshold: 80, duration: 300, eval_interval: 60, severity_code: 'warning' },
      { name: '内存使用率过高', data_source: 'dc-host', metric_name: 'memory_usage', rule_type: 'static', compare_op: '>=', threshold: 80, duration: 300, eval_interval: 60, severity_code: 'warning' },
      { name: '磁盘使用率过高', data_source: 'dc-host', metric_name: 'disk_usage', rule_type: 'static', compare_op: '>=', threshold: 85, duration: 600, eval_interval: 60, severity_code: 'warning' },
    ],
    'server_hardware': [
      { name: 'CPU温度过高', data_source: 'dc-hardware', metric_name: 'server_temperature_cpu', rule_type: 'static', compare_op: '>=', threshold: 75, duration: 300, eval_interval: 60, severity_code: 'warning' },
      { name: '风扇转速异常', data_source: 'dc-hardware', metric_name: 'fan_speed', rule_type: 'static', compare_op: '<=', threshold: 800, duration: 300, eval_interval: 60, severity_code: 'warning' },
    ],
    'network_device': [
      { name: '接口Down告警', data_source: 'dc-network', metric_name: 'interface_status', rule_type: 'static', compare_op: '==', threshold: 'down', duration: 60, eval_interval: 30, severity_code: 'critical' },
      { name: '端口带宽利用率过高', data_source: 'dc-network', metric_name: 'interface_usage_percent', rule_type: 'static', compare_op: '>=', threshold: 80, duration: 300, eval_interval: 60, severity_code: 'warning' },
    ],
    'database': [
      { name: '数据库连接数使用率过高', data_source: 'dc-database', metric_name: 'db_conn_usage_percent', rule_type: 'static', compare_op: '>=', threshold: 80, duration: 300, eval_interval: 60, severity_code: 'warning' },
      { name: '慢查询次数过多', data_source: 'dc-database', metric_name: 'slow_query_count', rule_type: 'static', compare_op: '>=', threshold: 50, duration: 300, eval_interval: 60, severity_code: 'warning' },
    ],
    'middleware': [
      { name: '请求错误率过高', data_source: 'dc-middleware', metric_name: 'error_rate', rule_type: 'static', compare_op: '>=', threshold: 1, duration: 300, eval_interval: 60, severity_code: 'warning' },
      { name: '队列消息堆积', data_source: 'dc-middleware', metric_name: 'queue_depth', rule_type: 'static', compare_op: '>=', threshold: 10000, duration: 600, eval_interval: 60, severity_code: 'critical' },
    ],
  }

  return defaultRulesMap[category] || []
}

// 添加规则
const handleAddRule = () => {
  formData.value.rules.push({
    name: '',
    data_source: formData.value.category ? getDefaultDataSource(formData.value.category) : 'dc-host',
    metric_name: '',
    rule_type: 'static',
    compare_op: '>=',
    threshold: 0,
    duration: 300,
    eval_interval: 60,
    severity_code: 'warning',
    _metrics: [],
    _metricsLoading: false,
  })
}

// 获取默认数据源
const getDefaultDataSource = (category: string): string => {
  const map: Record<string, string> = {
    'os': 'dc-host',
    'server_hardware': 'dc-hardware',
    'network_device': 'dc-network',
    'database': 'dc-database',
    'middleware': 'dc-middleware',
    'virtualization': 'dc-virtualization',
    'power_env': 'dc-env',
    'safety_env': 'dc-env',
  }
  return map[category] || 'dc-host'
}

// 移除规则
const handleRemoveRule = (index: number) => {
  formData.value.rules.splice(index, 1)
}

// 校验规则字段
const validateRules = (): { valid: boolean; message: string } => {
  if (formData.value.rules.length === 0) {
    return { valid: false, message: '请至少添加一条规则' }
  }

  for (let i = 0; i < formData.value.rules.length; i++) {
    const rule = formData.value.rules[i]
    const ruleNum = i + 1

    if (!rule.name || rule.name.trim() === '') {
      return { valid: false, message: `规则${ruleNum}: 请输入规则名称` }
    }
    if (!rule.data_source) {
      return { valid: false, message: `规则${ruleNum}: 请选择数据源` }
    }
    if (!rule.metric_name) {
      return { valid: false, message: `规则${ruleNum}: 请选择指标名称` }
    }
    if (!rule.rule_type) {
      return { valid: false, message: `规则${ruleNum}: 请选择规则类型` }
    }
    if (!rule.compare_op) {
      return { valid: false, message: `规则${ruleNum}: 请选择比较运算符` }
    }
    if (rule.threshold === undefined || rule.threshold === null || rule.threshold === '') {
      return { valid: false, message: `规则${ruleNum}: 请输入阈值` }
    }
    if (rule.duration === undefined || rule.duration === null) {
      return { valid: false, message: `规则${ruleNum}: 请输入持续时间` }
    }
    if (rule.eval_interval === undefined || rule.eval_interval === null) {
      return { valid: false, message: `规则${ruleNum}: 请输入评估间隔` }
    }
    if (!rule.severity_code) {
      return { valid: false, message: `规则${ruleNum}: 请选择告警级别` }
    }
  }

  return { valid: true, message: '' }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 校验基础表单
    const valid = await formRef.value?.validate()
    if (valid) {
      Message.warning('请检查表单填写是否正确')
      return
    }

    // 校验规则字段（使用 RuleEditor 的 validate 方法）
    if (formData.value.rules.length === 0) {
      Message.warning('请至少添加一条规则')
      return
    }

    try {
      await ruleEditorRef.value?.validate()
    } catch (ruleErrors) {
      Message.warning('请检查规则配置是否完整')
      return
    }

    submitting.value = true

    // 提取规则数据
    const submitRules = formData.value.rules.map(r => {
      const { _metrics, _metricsLoading, ...rest } = r as any
      return rest
    })

    const submitData: AlertTemplate = {
      name: formData.value.name,
      category: formData.value.category,
      description: formData.value.description,
      enabled: formData.value.enabled,
      tags: formData.value.tagsList.join(','),
      rules: submitRules,
      channels: formData.value.selectedChannelIds.map(id => ({ channel_id: id })),
      suppression_rule_ids: formData.value.suppression_rule_ids,
    }

    if (isEdit.value && templateId.value) {
      submitData.id = templateId.value
      const res: any = await updateTemplate(submitData)
      if (res.code === 0) {
        Message.success('模板更新成功')
        router.push('/alert/template')
      } else {
        Message.error(res.msg || '更新失败')
      }
    } else {
      const res: any = await createTemplate(submitData)
      if (res.code === 0) {
        Message.success('模板创建成功')
        router.push('/alert/template')
      } else {
        Message.error(res.msg || '创建失败')
      }
    }
  } catch (error: any) {
    console.error('提交失败:', error)
    Message.error(error.message || '操作失败')
  } finally {
    submitting.value = false
  }
}

// 返回列表
const handleBack = () => {
  router.push('/alert/template')
}

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

<script lang="ts">
export default {
  name: 'AlertTemplateEditPage',
}
</script>

<style scoped lang="less">
.template-edit-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--color-fill-2);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: var(--color-bg-2);
  border-bottom: 1px solid var(--color-border);
  flex-shrink: 0;
  
  .header-left {
    display: flex;
    align-items: center;
    
    .page-title {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }
  }
}

.page-content {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.info-card {
  margin-bottom: 16px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.rules-card {
  height: 100%;
  min-height: 500px;
  display: flex;
  flex-direction: column;
  
  :deep(.arco-card-body) {
    flex: 1;
    overflow: auto;
  }
  
  .rules-card-title {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .rules-content {
    height: 100%;
  }
}

// 表单项样式优化
:deep(.arco-form-item) {
  margin-bottom: 16px;
}

:deep(.arco-card) {
  .arco-card-header {
    border-bottom: 1px solid var(--color-border);
  }
}

// 响应式布局
@media (max-width: 992px) {
  .rules-card {
    min-height: 400px;
    margin-top: 16px;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
    
    .header-right {
      width: 100%;
      justify-content: flex-end;
    }
  }
  
  .rules-card {
    min-height: 300px;
  }
}
</style>