import { ref, reactive } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { fetchSuppressionList, updateSuppression, deleteSuppression, type SuppressionRule } from '@/api/ops/suppression'
import type { SearchFormModel, PaginationConfig, SwitchLoadingMap } from '../types'
import { DEFAULT_PAGINATION, DEFAULT_SEARCH_FORM } from '../constants'

/**
 * 表格相关逻辑
 */
export const useTable = () => {
  const loading = ref(false)
  const tableData = ref<SuppressionRule[]>([])
  const switchLoadingMap = ref<SwitchLoadingMap>({})
  const formModel = ref<SearchFormModel>({ ...DEFAULT_SEARCH_FORM })
  const pagination = reactive<PaginationConfig>({ ...DEFAULT_PAGINATION })

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

      if (formModel.value.keyword) {
        params.keyword = formModel.value.keyword
      }

      if (formModel.value.type) {
        params.type = formModel.value.type
      }

      if (formModel.value.policy_id) {
        params.policy_id = Number(formModel.value.policy_id)
      }

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

      const res = await fetchSuppressionList(params)
      if (res.code === 0 && res.details) {
        tableData.value = (res.details.data || []).map((item: any) => ({
          ...item,
          switchLoading: false,
        }))
        pagination.total = res.details.total || 0
      } else {
        Message.error(res.message || '获取抑制规则列表失败')
      }
    } catch (error: any) {
      console.error('获取抑制规则列表失败:', error)
      Message.error(error.message || '获取抑制规则列表失败')
    } finally {
      loading.value = false
    }
  }

  /**
   * 处理表单模型更新
   */
  const handleFormModelUpdate = (value: Record<string, any>) => {
    formModel.value = value as SearchFormModel
  }

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

  /**
   * 重置
   */
  const handleReset = () => {
    formModel.value = { ...DEFAULT_SEARCH_FORM }
    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 handleToggleEnabled = async (record: SuppressionRule) => {
    if (!record.id) return
    switchLoadingMap.value[record.id] = true
    try {
      const res = await updateSuppression({
        id: record.id,
        enabled: record.enabled,
      })
      if (res.code === 0) {
        Message.success(record.enabled ? '已启用' : '已禁用')
      } else {
        // 恢复原状态
        record.enabled = !record.enabled
        Message.error(res.message || '操作失败')
      }
    } catch (error: any) {
      record.enabled = !record.enabled
      console.error('切换状态失败:', error)
      Message.error(error.message || '操作失败')
    } finally {
      switchLoadingMap.value[record.id] = false
    }
  }

  /**
   * 删除抑制规则
   */
  const handleDelete = (record: SuppressionRule) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除抑制规则「${record.name}」吗？删除后将影响告警降噪行为，请确认是否被模板引用。`,
      okText: '删除',
      cancelText: '取消',
      okButtonProps: { status: 'danger' },
      onOk: async () => {
        try {
          const res = await deleteSuppression(record.id!)
          if (res.code === 0 || res.data === '删除成功') {
            Message.success('删除成功')
            fetchList()
          } else {
            Message.error(res.message || '删除失败')
          }
        } catch (error: any) {
          console.error('删除失败:', error)
          Message.error(error.message || '删除失败')
        }
      },
    })
  }

  /**
   * 跳转到策略详情
   */
  const handleGoToPolicy = (policyId: number) => {
    Message.info(`跳转到策略 #${policyId} 详情页`)
  }

  return {
    loading,
    tableData,
    switchLoadingMap,
    formModel,
    pagination,
    fetchList,
    handleFormModelUpdate,
    handleSearch,
    handleReset,
    handleRefresh,
    handlePageChange,
    handlePageSizeChange,
    handleToggleEnabled,
    handleDelete,
    handleGoToPolicy,
  }
}
