<template>
  <div class="container">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="tableColumns"
      :loading="loading"
      :pagination="pagination"
      :title="pageTitle"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @refresh="handleRefresh"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
    >
      <!-- 工具栏左侧：新建按钮 -->
      <template #toolbar-left>
        <a-space>
          <a-button type="primary" @click="handleOpenCreateModal">
            <template #icon><icon-plus /></template>
            新建抑制规则
          </a-button>
        </a-space>
      </template>

      <!-- 类型列 -->
      <template #type="{ record }">
        <a-tag :color="getTypeColor(record.type)">
          {{ getTypeLabel(record.type) }}
        </a-tag>
      </template>

      <!-- 启用状态列 -->
      <template #enabled="{ record }">
        <a-switch
          v-model="record.enabled"
          :loading="switchLoadingMap[record.id]"
          @change="handleToggleEnabled(record)"
        />
      </template>

      <!-- 作用范围列 -->
      <template #policy="{ record }">
        <span v-if="record.policy_id === 0 || !record.policy_id">
          <a-tag color="gray">全局</a-tag>
        </span>
        <span v-else>
          <a-link @click="handleGoToPolicy(record.policy_id)">
            {{ getPolicyName(record.policy_id) || `策略 #${record.policy_id}` }}
          </a-link>
        </span>
      </template>

      <!-- 关键配置列 -->
      <template #config="{ record }">
        <span class="config-text">{{ getConfigSummary(record) }}</span>
      </template>

      <!-- 匹配条件列 -->
      <template #matchers="{ record }">
        <a-tooltip v-if="record.matchers && record.matchers !== '{}'" :content="record.matchers">
          <a-tag color="arcoblue">
            <icon-code />
            已配置
          </a-tag>
        </a-tooltip>
        <span v-else class="text-gray">全部告警</span>
      </template>

      <!-- 最后命中时间列 -->
      <template #last_hit_at="{ record }">
        <span v-if="record.last_hit_at">{{ formatDateTime(record.last_hit_at) }}</span>
        <span v-else class="text-gray">-</span>
      </template>

      <!-- 创建时间列 -->
      <template #created_at="{ record }">
        {{ formatDateTime(record.created_at) }}
      </template>

      <!-- 操作列 -->
      <template #operations="{ record }">
        <a-space>
          <a-button type="text" size="small" @click="handleOpenEditModal(record)">
            编辑
          </a-button>
          <a-button type="text" size="small" status="danger" @click="handleDelete(record)">
            删除
          </a-button>
        </a-space>
      </template>
    </search-table>

    <!-- 新建/编辑抑制规则弹窗 -->
    <SuppressionModal
      v-model:visible="modalVisible"
      v-model:submitting="submitting"
      :is-edit="isEdit"
      :data="formData"
      :policy-options="policyOptions"
      @success="fetchList"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import SearchTable from '@/components/search-table/index.vue'
import { fetchSuppressionDetail, type SuppressionRule } from '@/api/ops/suppression'
import SuppressionModal from './components/SuppressionModal.vue'
import { PAGE_TITLE, DEFAULT_FORM_DATA } from './constants'
import { getTableColumns } from './config/columns'
import { useFormItems } from './config/formItems'
import { getTypeColor, getTypeLabel, getConfigSummary, formatDateTime } from './utils'
import { usePolicy, useTable } from './hooks'
import type { SuppressionFormData } from './types'

// 页面标题
const pageTitle = PAGE_TITLE

// 策略相关
const { policyOptions, fetchPolicyOptions, getPolicyName } = usePolicy()

// 表格相关
const {
  loading,
  tableData,
  switchLoadingMap,
  formModel,
  pagination,
  fetchList,
  handleFormModelUpdate,
  handleSearch,
  handleReset,
  handleRefresh,
  handlePageChange,
  handlePageSizeChange,
  handleToggleEnabled,
  handleDelete,
  handleGoToPolicy,
} = useTable()

// 筛选表单项配置
const formItems = useFormItems(policyOptions.value)

// 表格列配置
const tableColumns = computed(() => getTableColumns())

// 弹窗相关
const modalVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const formData = ref<SuppressionFormData>({ ...DEFAULT_FORM_DATA })

// 打开新建弹窗
const handleOpenCreateModal = () => {
  isEdit.value = false
  formData.value = { ...DEFAULT_FORM_DATA }
  modalVisible.value = true
}

// 打开编辑弹窗
const handleOpenEditModal = async (record: SuppressionRule) => {
  isEdit.value = true
  try {
    const res = await fetchSuppressionDetail(record.id!)
    if (res.code === 0 && res.details) {
      formData.value = { ...res.details }
      modalVisible.value = true
    } else {
      Message.error(res.message || '获取抑制规则详情失败')
    }
  } catch (error: any) {
    console.error('获取抑制规则详情失败:', error)
    Message.error(error.message || '获取抑制规则详情失败')
  }
}

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

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

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

.config-text {
  font-size: 13px;
  color: var(--color-text-2);
}

.text-gray {
  color: var(--color-text-3);
}
</style>
