<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 #index="{ rowIndex }">
        {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
      </template>
      
      <!-- 策略名称 -->
      <template #name="{ record }">
        <a-space>
          <a-tag v-if="!record.enabled" color="gray">禁用</a-tag>
          <span>{{ record.name }}</span>
        </a-space>
      </template>
      
      <!-- 启用状态 -->
      <template #enabled="{ record }">
        <a-switch
          :model-value="record.enabled"
          :checked-value="true"
          :unchecked-value="false"
          @change="handleToggleEnabled(record)"
        />
      </template>
      
      <!-- 规则数 -->
      <template #rule_count="{ record }">
        <span>{{ record.rules?.length || 0 }} 条</span>
      </template>
      
      <!-- 通知渠道数 -->
      <template #channel_count="{ record }">
        <span>{{ record.channels?.length || 0 }} 个</span>
      </template>
      
      <!-- 抑制规则数 -->
      <template #suppression_rule_count="{ record }">
        <span>{{ record.suppression_rules?.length || 0 }} 条</span>
      </template>
      
      <!-- 自动建单 -->
      <template #auto_create_ticket="{ record }">
        <a-tag :color="record.auto_create_ticket ? 'green' : 'gray'">
          {{ record.auto_create_ticket ? '是' : '否' }}
        </a-tag>
      </template>
      
      <!-- 创建时间 -->
      <template #created_at="{ record }">
        {{ formatDate(record.created_at) }}
      </template>
      
      <!-- 最后修改 -->
      <template #updated_at="{ record }">
        {{ formatDate(record.updated_at) }}
      </template>
      
      <!-- 操作 -->
      <template #actions="{ record }">
        <a-space>
          <a-button type="text" size="small" @click="handleEdit(record)">
            编辑
          </a-button>
          <a-button type="text" size="small" @click="handleManageRules(record)">
            规则管理
          </a-button>
          <a-popconfirm
            content="确定要删除该策略吗？删除后将无法恢复，且会影响告警评估。"
            @ok="handleDelete(record)"
          >
            <a-button type="text" size="small" status="danger">
              删除
            </a-button>
          </a-popconfirm>
        </a-space>
      </template>
      
      <!-- 工具栏左侧按钮 -->
      <template #toolbar-left>
        <a-button type="primary" @click="handleCreate">
          <template #icon>
            <icon-plus />
          </template>
          新建策略
        </a-button>
      </template>
    </search-table>
    
    <!-- 编辑策略弹窗 -->
    <policy-form-dialog
      v-model:visible="policyFormVisible"
      :policy-id="currentPolicyId"
      @success="handlePolicyFormSuccess"
    />

    <!-- 新建策略弹窗 -->
    <policy-create-dialog
      v-model:visible="createPolicyVisible"
      @success="handlePolicyFormSuccess"
    />
    
    <!-- 规则管理弹窗 -->
    <rule-manage-dialog
      v-model:visible="ruleManageVisible"
      :policy-id="currentPolicyId"
      :policy-name="currentPolicyName"
      @success="handleRuleManageSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } 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 {
  fetchPolicyList,
  deletePolicy,
  updatePolicy,
} from '@/api/ops/alertPolicy'
import PolicyFormDialog from './components/PolicyFormDialog.vue'
import PolicyCreateDialog from './components/PolicyCreateDialog.vue'
import RuleManageDialog from './components/RuleManageDialog.vue'

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

const formModel = ref({
  keyword: '',
  enabled: 'all',
  priority: undefined,
})

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

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

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

// 当前选中的策略
const currentPolicyId = ref<number | undefined>(undefined)
const currentPolicyName = ref('')

// 弹窗可见性
const policyFormVisible = ref(false)
const createPolicyVisible = ref(false)
const ruleManageVisible = ref(false)

// 获取策略列表
const fetchPolicyData = async () => {
  loading.value = true
  
  try {
    const params: any = {
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: formModel.value.keyword || undefined,
    }

    // 处理启用状态筛选
    if (formModel.value.enabled && formModel.value.enabled !== 'all') {
      params.enabled = formModel.value.enabled === 'true'
    }

    // 处理优先级筛选
    if (formModel.value.priority !== undefined && formModel.value.priority !== null) {
      params.priority = Number(formModel.value.priority)
    }

    const res = await fetchPolicyList(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 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 handleSearch = () => {
  pagination.current = 1
  fetchPolicyData()
}

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

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

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

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

// 新建策略
const handleCreate = () => {
  createPolicyVisible.value = true
}

// 编辑策略
const handleEdit = (record: any) => {
  currentPolicyId.value = record.id
  policyFormVisible.value = true
}

// 切换启用状态
const handleToggleEnabled = async (record: any) => {
  try {
    const newStatus = !record.enabled
    await updatePolicy({
      id: record.id,
      enabled: newStatus,
    })
    
    Message.success(newStatus ? '策略已启用' : '策略已禁用')
    record.enabled = newStatus
  } catch (error) {
    console.error('更新策略状态失败:', error)
    Message.error('更新策略状态失败')
  }
}

// 删除策略
const handleDelete = async (record: any) => {
  try {
    await deletePolicy(record.id)
    Message.success('策略删除成功')
    
    // 如果当前页只有一条数据，且不是第一页，则跳到上一页
    if (tableData.value.length === 1 && pagination.current > 1) {
      pagination.current--
    }
    
    fetchPolicyData()
  } catch (error) {
    console.error('删除策略失败:', error)
    Message.error('删除策略失败')
  }
}

// 规则管理
const handleManageRules = (record: any) => {
  currentPolicyId.value = record.id
  currentPolicyName.value = record.name
  ruleManageVisible.value = true
}

// 策略表单成功回调
const handlePolicyFormSuccess = () => {
  fetchPolicyData()
}

// 规则管理成功回调
const handleRuleManageSuccess = () => {
  fetchPolicyData()
}

// 初始化加载数据
onMounted(() => {
  fetchPolicyData()
})
</script>

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

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