<template>
  <div class="container">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="告警级别管理"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <template #toolbar-left>
        <a-button type="primary" @click="handleCreate">
          <template #icon>
            <icon-plus />
          </template>
          新建级别
        </a-button>
      </template>

      <!-- 序号 -->
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
      </template>

      <!-- 颜色标识 -->
      <template #color="{ record }">
        <div style="display: flex; align-items: center; gap: 8px">
          <div
            :style="{
              width: '20px',
              height: '20px',
              backgroundColor: record.color,
              border: '1px solid var(--color-border-2)',
              borderRadius: '4px',
            }"
          ></div>
          <span>{{ record.color }}</span>
        </div>
      </template>

      <!-- 状态 -->
      <template #enabled="{ record }">
        <a-tag :color="record.enabled ? 'green' : 'red'">
          {{ record.enabled ? '启用' : '禁用' }}
        </a-tag>
      </template>

      <!-- 操作 -->
      <template #actions="{ record }">
        <a-button type="text" size="small" @click="handleDetail(record)">详情</a-button>
        <a-button type="text" size="small" @click="handleEdit(record)">编辑</a-button>
        <a-button type="text" size="small" status="danger" @click="handleDelete(record)" :disabled="record.is_default">删除</a-button>
      </template>
    </search-table>

    <!-- 告警级别表单对话框（新建/编辑） -->
    <level-form-dialog v-model:visible="formVisible" :level="editingLevel" @success="handleFormSuccess" />

    <!-- 告警级别详情对话框 -->
    <level-detail-dialog v-model:visible="detailVisible" :level-id="currentLevelId" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import type { FormItem } from '@/components/search-form/types'
import SearchTable from '@/components/search-table/index.vue'
import { searchFormConfig } from './config/search-form'
import { columns as columnsConfig } from './config/columns'
import { fetchAlertLevelList, deleteAlertLevel } from '@/api/ops/alertLevel'
import LevelDetailDialog from './components/LevelDetailDialog.vue'
import LevelFormDialog from './components/LevelFormDialog.vue'

// 状态管理
const loading = ref(false)
const tableData = ref<any[]>([])
const formModel = ref({
  keyword: '',
  enabled: '',
})

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

// 表单项配置
const formItems = computed<FormItem[]>(() => searchFormConfig)

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

// 当前选中的级别
const currentLevelId = ref<number | undefined>(undefined)
const editingLevel = ref<any>(null)

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

// 获取告警级别列表
const fetchLevels = async () => {
  loading.value = true

  try {
    const params: any = {
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: formModel.value.keyword || undefined,
      enabled: formModel.value.enabled || undefined,
    }

    const res = await fetchAlertLevelList(params)

    // 优先适配分页层字段：total/page/page_size/data，并兼容历史返回结构
    const pageData = res?.data?.data ?? res?.details?.data ?? res?.data ?? []
    const pageTotal = res?.data?.total ?? res?.details?.total ?? res?.total ?? 0

    tableData.value = Array.isArray(pageData) ? pageData : []
    pagination.total = Number(pageTotal) || 0
  } catch (error) {
    console.error('获取告警级别列表失败:', error)
    Message.error('获取告警级别列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

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

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

// 重置
const handleReset = () => {
  formModel.value = {
    keyword: '',
    enabled: '',
  }
  pagination.current = 1
  fetchLevels()
}

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

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

// 新建级别
const handleCreate = () => {
  editingLevel.value = null
  formVisible.value = true
}

// 编辑级别
const handleEdit = (record: any) => {
  console.log('编辑告警级别:', record)
  editingLevel.value = record
  formVisible.value = true
}

// 详情
const handleDetail = (record: any) => {
  console.log('查看详情:', record)
  currentLevelId.value = record.id
  detailVisible.value = true
}

// 删除级别
const handleDelete = async (record: any) => {
  console.log('删除告警级别:', record)

  // 系统默认级别不允许删除
  if (record.is_default) {
    Message.warning('系统默认级别不允许删除')
    return
  }

  try {
    Modal.confirm({
      title: '确认删除',
      content: `确认删除告警级别 ${record.name} 吗？`,
      onOk: async () => {
        const res = await deleteAlertLevel(record.id)
        if (res.code === 0) {
          Message.success('删除成功')
          fetchLevels()
        } else {
          Message.error(res.message || '删除失败')
        }
      },
    })
  } catch (error) {
    console.error('删除告警级别失败:', error)
  }
}

// 表单成功回调
const handleFormSuccess = () => {
  formVisible.value = false
  fetchLevels()
}

// 初始化加载数据
fetchLevels()
</script>

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

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