<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-button type="primary" @click="handleCreate">
          <template #icon><icon-plus /></template>
          新建模板
        </a-button>
      </template>

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

      <!-- 分类列 -->
      <template #category="{ record }">
        {{ getCategoryLabel(record.category) }}
      </template>

      <!-- 规则数量列 -->
      <template #rulesCount="{ record }">
        <a-badge :count="getRulesCount(record.rules)" :dot-style="{ backgroundColor: '#165dff' }" />
      </template>

      <!-- 操作列 -->
      <template #operations="{ record }">
        <a-space>
          <a-button type="text" size="small" @click="handleViewDetail(record)">
            查看
          </a-button>
          <a-button type="text" size="small" @click="handleEdit(record)">
            编辑
          </a-button>
          <a-button
            type="text"
            size="small"
            :status="record.enabled ? 'warning' : 'success'"
            @click="handleToggleEnabled(record)"
          >
            {{ record.enabled ? '禁用' : '启用' }}
          </a-button>
          <a-popconfirm
            content="确定要删除此模板吗？"
            type="warning"
            @ok="handleDelete(record)"
          >
            <a-button type="text" size="small" status="danger">
              删除
            </a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </search-table>

    <!-- 详情弹窗 -->
    <TemplateDetailDialog
      v-model:visible="detailModalVisible"
      :title="detailModalTitle"
      :template-id="detailTemplateId"
      :channel-options="channelOptions"
      :suppression-options="suppressionOptions"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import SearchTable from '@/components/search-table/index.vue'
import type { FormItem } from '@/components/search-form/types'
import TemplateDetailDialog from './components/TemplateDetailDialog.vue'
import {
  fetchTemplateList,
  updateTemplate,
  deleteTemplate,
  fetchChannelList,
  fetchSuppressionList,
  TEMPLATE_CATEGORIES,
  type AlertTemplate,
  type NotificationChannel,
  type SuppressionRule,
} from '@/api/ops/alertTemplate'

const router = useRouter()

// 页面标题
const pageTitle = '告警模板管理'

// 搜索表单模型
const formModel = ref({
  name: '',
  category: '',
  enabled: '',
})

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    field: 'name',
    label: '模板名称',
    type: 'input',
    span: 8,
    placeholder: '请输入模板名称',
  },
  {
    field: 'category',
    label: '分类',
    type: 'select',
    span: 8,
    placeholder: '请选择',
    options: [
      { value: '', label: '全部' },
      ...TEMPLATE_CATEGORIES,
    ],
  },
  {
    field: 'enabled',
    label: '状态',
    type: 'select',
    span: 8,
    placeholder: '请选择',
    options: [
      { value: '', label: '全部' },
      { value: 'true', label: '已启用' },
      { value: 'false', label: '已禁用' },
    ],
  },
])

// 状态
const loading = ref(false)
const tableData = ref<AlertTemplate[]>([])

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
})

// 表格列配置
const tableColumns = computed(() => [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '模板名称',
    dataIndex: 'name',
    width: 200,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '分类',
    dataIndex: 'category',
    width: 180,
    slotName: 'category',
  },
  {
    title: '规则数量',
    dataIndex: 'rules',
    width: 100,
    slotName: 'rulesCount',
  },
  {
    title: '状态',
    dataIndex: 'enabled',
    width: 100,
    slotName: 'enabled',
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    width: 180,
    render: ({ record }: any) => {
      return record.created_at ? dayjs(record.created_at).format('YYYY-MM-DD HH:mm:ss') : '-'
    },
  },
  {
    title: '操作',
    dataIndex: 'operations',
    width: 280,
    slotName: 'operations',
    fixed: 'right' as const,
  },
])

// 详情弹窗
const detailModalVisible = ref(false)
const detailModalTitle = ref('模板详情')
const detailTemplateId = ref<number | null>(null)

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

// 获取分类标签
const getCategoryLabel = (value: string) => {
  const item = TEMPLATE_CATEGORIES.find(c => c.value === value)
  return item?.label || value
}

// 获取规则数量（解析 JSON 字符串）
const getRulesCount = (rules: any) => {
  if (!rules) return 0
  if (typeof rules === 'string') {
    try {
      const parsed = JSON.parse(rules)
      return Array.isArray(parsed) ? parsed.length : 0
    } catch {
      return 0
    }
  }
  return Array.isArray(rules) ? rules.length : 0
}

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.current,
      page_size: pagination.pageSize,
    }

    if (formModel.value.name) {
      params.name = formModel.value.name
    }
    if (formModel.value.category) {
      params.category = formModel.value.category
    }
    if (formModel.value.enabled) {
      params.enabled = formModel.value.enabled === 'true'
    }

    const res: any = await fetchTemplateList(params)

    if (res.code === 0) {
      tableData.value = res.details?.data || res.details?.list || []
      pagination.total = res.details?.total || 0
    } else {
      Message.error(res.msg || '获取模板列表失败')
    }
  } catch (error: any) {
    console.error('获取模板列表失败:', error)
    Message.error(error.message || '获取模板列表失败')
  } finally {
    loading.value = false
  }
}

// 加载下拉选项
const loadOptions = async () => {
  try {
    // 加载通知渠道
    const channelRes: any = await fetchChannelList({ enabled: true })
    if (channelRes.code === 0) {
      channelOptions.value = channelRes.details?.data || channelRes.details?.list || []
    }

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

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

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

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

// 刷新
const handleRefresh = () => {
  fetchList()
}

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

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  fetchList()
}

// 新建模板
const handleCreate = () => {
  router.push('/alert/template/edit')
}

// 编辑模板
const handleEdit = (record: AlertTemplate) => {
  router.push({
    path: '/alert/template/edit',
    query: { id: record.id },
  })
}

// 查看详情
const handleViewDetail = (record: AlertTemplate) => {
  detailModalTitle.value = `模板详情 - ${record.name}`
  detailTemplateId.value = record.id || null
  detailModalVisible.value = true
}

// 切换启用状态
const handleToggleEnabled = async (record: AlertTemplate) => {
  try {
    const res: any = await updateTemplate({
      id: record.id,
      enabled: !record.enabled,
    } as AlertTemplate)

    if (res.code === 0) {
      Message.success(record.enabled ? '禁用成功' : '启用成功')
      fetchList()
    } else {
      Message.error(res.msg || '操作失败')
    }
  } catch (error: any) {
    console.error('操作失败:', error)
    Message.error(error.message || '操作失败')
  }
}

// 删除模板
const handleDelete = async (record: AlertTemplate) => {
  try {
    const res: any = await deleteTemplate(record.id!)
    if (res.code === 0) {
      Message.success('删除成功')
      fetchList()
    } else {
      Message.error(res.msg || '删除失败')
    }
  } catch (error: any) {
    console.error('删除失败:', error)
    Message.error(error.message || '删除失败')
  }
}

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

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

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