<template>
  <div class="container">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="历史告警列表"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <!-- 时间范围选择器插槽 -->
      <template #form-items>
        <a-col :span="8">
          <a-form-item label="时间范围" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
            <a-space>
              <a-date-picker
                v-model="formModel.starts_at"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="开始时间"
                style="width: 180px;"
              />
              <span>-</span>
              <a-date-picker
                v-model="formModel.ends_at"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="结束时间"
                style="width: 180px;"
              />
            </a-space>
          </a-form-item>
        </a-col>
      </template>
      
      <!-- 序号 -->
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
      </template>
      
      <!-- 状态 -->
      <template #status="{ record }">
        <a-tag :color="getStatusColor(record.status)">
          {{ getStatusText(record.status) }}
        </a-tag>
      </template>
      
      <!-- 告警级别 -->
      <template #severity="{ record }">
        <div v-if="record.severity" style="display: flex; align-items: center; gap: 8px;">
          <div
            :style="{
              width: '16px',
              height: '16px',
              backgroundColor: record.severity.color,
              border: '1px solid var(--color-border-2)',
              borderRadius: '3px'
            }"
          ></div>
          <span>{{ record.severity.name }}</span>
        </div>
        <span v-else>-</span>
      </template>
      
      <!-- 开始时间 -->
      <template #starts_at="{ record }">
        {{ formatDate(record.starts_at) }}
      </template>
      
      <!-- 结束时间 -->
      <template #ends_at="{ record }">
        {{ formatDate(record.ends_at) || '-' }}
      </template>
      
      <!-- 持续时长 -->
      <template #duration="{ record }">
        {{ formatDuration(record.duration) }}
      </template>
      
      <!-- 处理时间 -->
      <template #processed_at="{ record }">
        {{ formatDate(record.processed_at) || '-' }}
      </template>
      
      <!-- 操作 -->
      <template #actions="{ record }">
        <a-button type="text" size="small" @click="handleDetail(record)">
          详情
        </a-button>
        <a-button type="text" size="small" @click="handleViewProcess(record)">
          处理记录
        </a-button>
      </template>
    </search-table>
    
    <!-- 告警记录详情对话框 -->
    <history-detail-dialog
      v-model:visible="detailVisible"
      :record-id="currentRecordId"
    />

    <!-- 告警处理记录对话框 -->
    <history-process-list-dialog
      v-model:visible="processVisible"
      :alert-record-id="currentProcessAlertRecordId"
      :alert-record="currentProcessAlertRecord"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormItem } from '@/components/search-form/types'
import SearchTable from '@/components/search-table/index.vue'
import { columns as columnsConfig } from './config/columns'
import {
  fetchHistories,
} from '@/api/ops/alertHistory'
import { fetchAlertLevelOptions } from '@/api/ops/alertLevel'
import HistoryDetailDialog from './components/HistoryDetailDialog.vue'
import HistoryProcessListDialog from './components/HistoryProcessListDialog.vue'

// 状态管理
const loading = ref(false)
const tableData = ref<any[]>([])

// 初始化表单模型，设置默认时间范围（最近7天）
const getDefaultDateRange = () => {
  const now = new Date()
  const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
  
  const formatDate = (date: Date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  
  return {
    starts_at: formatDate(sevenDaysAgo),
    ends_at: formatDate(now),
  }
}

const formModel = ref({
  keyword: '',
  status: 'resolved', // 默认显示已解决的告警
  rule_id: undefined,
  severity_id: undefined,
  ...getDefaultDateRange(),
})

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

// 告警级别列表
const severityOptions = ref<any[]>([])

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    field: 'keyword',
    label: '关键字',
    type: 'input',
    placeholder: '请输入告警名称、摘要或描述',
  },
  {
    field: 'status',
    label: '告警状态',
    type: 'select',
    placeholder: '请选择告警状态',
    options: [
      { label: '待处理', value: 'pending' },
      { label: '触发中', value: 'firing' },
      { label: '已解决', value: 'resolved' },
      { label: '已屏蔽', value: 'silenced' },
      { label: '已抑制', value: 'suppressed' },
      { label: '已确认', value: 'acked' },
    ],
  },
  {
    field: 'rule_id',
    label: '规则',
    type: 'select',
    placeholder: '请选择规则',
    options: [],
  },
  {
    field: 'severity_id',
    label: '告警级别',
    type: 'select',
    placeholder: '请选择告警级别',
    options: severityOptions.value.map((s: any) => ({
      label: s.name,
      value: s.id,
    })),
  },
])

// 表格列配置
const columns = computed(() => columnsConfig)

// 当前选中的告警记录
const currentRecordId = ref<number | undefined>(undefined)

// 对话框可见性
const detailVisible = ref(false)

// 处理记录对话框可见性
const processVisible = ref(false)

// 当前用于“处理记录”的告警记录
const currentProcessAlertRecord = ref<any>(null)
const currentProcessAlertRecordId = computed(() => currentProcessAlertRecord.value?.id)

// 加载告警级别列表
const loadSeverityOptions = async () => {
  try {
    const res: any = await fetchAlertLevelOptions({ enabled: 'true' })
    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 fetchHistoriesData = async () => {
  loading.value = true
  
  try {
    const params: any = {
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: formModel.value.keyword || undefined,
      status: formModel.value.status || undefined,
      rule_id: formModel.value.rule_id || undefined,
      severity_id: formModel.value.severity_id || undefined,
      starts_at: formModel.value.starts_at || undefined,
      ends_at: formModel.value.ends_at || undefined,
    }

    const res = await fetchHistories(params)
    
    tableData.value = res.details?.data || []
    pagination.total = res.details?.total || 0
  } catch (error) {
    console.error('获取告警记录列表失败:', error)
    Message.error('获取告警记录列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
}

// 格式化持续时长
const formatDuration = (duration: number) => {
  if (!duration) return '-'
  
  const hours = Math.floor(duration / 3600)
  const minutes = Math.floor((duration % 3600) / 60)
  const seconds = duration % 60
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else if (minutes > 0) {
    return `${minutes}分钟${seconds}秒`
  } else {
    return `${seconds}秒`
  }
}

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    pending: 'gray',
    firing: 'red',
    resolved: 'green',
    silenced: 'blue',
    suppressed: 'orange',
    acked: 'purple',
  }
  return colorMap[status] || 'gray'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待处理',
    firing: '触发中',
    resolved: '已解决',
    silenced: '已屏蔽',
    suppressed: '已抑制',
    acked: '已确认',
  }
  return textMap[status] || status
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchHistoriesData()
}

// 处理表单模型更新
const handleFormModelUpdate = (value: any) => {
  formModel.value = {
    ...formModel.value,
    ...value,
  }
}

// 重置
const handleReset = () => {
  formModel.value = {
    keyword: '',
    status: 'resolved',
    rule_id: undefined,
    severity_id: undefined,
    ...getDefaultDateRange(),
  }
  pagination.current = 1
  fetchHistoriesData()
}

// 分页变化
const handlePageChange = (current: number) => {
  pagination.current = current
  fetchHistoriesData()
}

// 刷新
const handleRefresh = () => {
  fetchHistoriesData()
  Message.success('数据已刷新')
}

// 详情
const handleDetail = (record: any) => {
  currentRecordId.value = record.id
  detailVisible.value = true
}

// 查看处理记录
const handleViewProcess = (record: any) => {
  currentProcessAlertRecord.value = record
  processVisible.value = true
}

// 初始化加载数据
onMounted(async () => {
  await loadSeverityOptions()
  fetchHistoriesData()
})
</script>

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

<style scoped lang="less">
.container {
  margin-top: 20px;
}
</style>
