<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="重置"
      refresh-tooltip-text="刷新数据"
      density-tooltip-text="表格密度"
      column-setting-tooltip-text="列设置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
      @row-click="handleRowClick"
      @refresh="handleRefresh"
    >
      <template #form-items>
        <a-col :span="16">
          <a-form-item
            label="时间范围"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
          >
            <a-range-picker
              v-model="timeRange"
              :time-picker-props="{ defaultValue: '00:00:00' }"
              format="YYYY-MM-DD HH:mm:ss"
              show-time
              style="width: 100%; max-width: 420px"
            />
          </a-form-item>
        </a-col>
      </template>

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

      <template #status="{ record }">
        <a-tag :color="getStatusColor(record.status)">
          {{ getStatusText(record.status) }}
        </a-tag>
      </template>

      <template #severity="{ record }">
        <a-tag v-if="record.severity" :color="record.severity.color">
          {{ record.severity.name || record.severity.code }}
        </a-tag>
      </template>

      <template #starts_at="{ record }">
        {{ formatDateTime(record.starts_at) }}
      </template>

      <template #duration="{ record }">
        {{ formatDuration(record.duration) }}
      </template>

      <template #processed_at="{ record }">
        {{ record.processed_at ? formatDateTime(record.processed_at) : '-' }}
      </template>

      <template #notify_status="{ record }">
        <a-tag v-if="record.notify_status" :color="getNotifyStatusColor(record.notify_status)">
          {{ getNotifyStatusText(record.notify_status) }}
        </a-tag>
        <span v-else>-</span>
      </template>

      <template #labels="{ record }">
        <a-tooltip v-if="formatLabelsLine(record.labels)" :content="formatLabelsLine(record.labels)">
          <span class="cell-ellipsis">{{ formatLabelsLine(record.labels) }}</span>
        </a-tooltip>
        <span v-else>-</span>
      </template>

      <template #actions="{ record }">
        <a-space size="small" :wrap="false">
          <a-button
            type="text"
            size="small"
            :disabled="isActionDisabled(record, 'ack')"
            @click.stop="handleAck(record)"
          >
            确认
          </a-button>
          <a-button
            type="text"
            size="small"
            :disabled="isActionDisabled(record, 'resolve')"
            @click.stop="handleResolve(record)"
          >
            解决
          </a-button>
          <a-button
            type="text"
            size="small"
            :disabled="isActionDisabled(record, 'silence')"
            @click.stop="handleSilence(record)"
          >
            屏蔽
          </a-button>
          <a-button
            type="text"
            size="small"
            :disabled="isActionDisabled(record, 'comment')"
            @click.stop="handleComment(record)"
          >
            评论
          </a-button>
          <a-dropdown @select="(v) => handleMoreSelect(v, record)">
            <a-button type="text" size="small" @click.stop>
              更多
            </a-button>
            <template #content>
              <a-doption value="detail">详情</a-doption>
              <a-doption value="process">处理记录</a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </template>
    </search-table>

    <ack-dialog
      v-model:visible="ackDialogVisible"
      :alert-record-id="currentRecord.id"
      @success="handleSuccess"
    />

    <resolve-dialog
      v-model:visible="resolveDialogVisible"
      :alert-record-id="currentRecord.id"
      @success="handleSuccess"
    />

    <silence-dialog
      v-model:visible="silenceDialogVisible"
      :alert-record-id="currentRecord.id"
      @success="handleSuccess"
    />

    <comment-dialog
      v-model:visible="commentDialogVisible"
      :alert-record-id="currentRecord.id"
      @success="handleSuccess"
    />

    <detail-dialog
      v-model:visible="detailDialogVisible"
      :alert-record-id="currentRecord.id"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useRouter } from 'vue-router'
import type { FormItem } from '@/components/search-form/types'
import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface'
import SearchTable from '@/components/search-table/index.vue'
import { searchFormConfig } from './config/search-form'
import { columns } from './config/columns'
import { fetchAlertRecords } from '@/api/ops/alertRecord'
import { fetchAlertLevelOptions } from '@/api/ops/alertLevel'

import AckDialog from './components/AckDialog.vue'
import ResolveDialog from './components/ResolveDialog.vue'
import SilenceDialog from './components/SilenceDialog.vue'
import CommentDialog from './components/CommentDialog.vue'
import DetailDialog from './components/DetailDialog.vue'

const router = useRouter()

const loading = ref(false)
const tableData = ref<any[]>([])
const timeRange = ref<any[]>([])
const currentRecord = ref<any>({})

const ackDialogVisible = ref(false)
const resolveDialogVisible = ref(false)
const silenceDialogVisible = ref(false)
const commentDialogVisible = ref(false)
const detailDialogVisible = ref(false)

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: ['10', '20', '50', '100'],
})

const severityOptions = ref<SelectOptionData[]>([])

const formModel = ref<Record<string, any>>({
  keyword: '',
  status: '',
  severity_id: '',
})

const formItems = computed<FormItem[]>(() =>
  searchFormConfig.map((item) => {
    if (item.field === 'severity_id') {
      return { ...item, options: severityOptions.value }
    }
    return item
  }),
)

onMounted(async () => {
  await loadSeverityOptions()
  handleSearch()
})

const loadSeverityOptions = async () => {
  try {
    const res: any = await fetchAlertLevelOptions({ enabled: 'true' })
    const list = Array.isArray(res?.details)
      ? res.details
      : res?.details?.data || res?.details?.list || res?.data || res || []
    severityOptions.value = (Array.isArray(list) ? list : []).map((item: any) => ({
      label: item.name || item.code,
      value: item.id,
    }))
  } catch (error) {
    console.error('加载告警级别失败:', error)
  }
}

const handleFormModelUpdate = (value: Record<string, any>) => {
  formModel.value = value
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  formModel.value = {
    keyword: '',
    status: '',
    severity_id: '',
  }
  timeRange.value = []
  pagination.current = 1
  loadData()
}

const loadData = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: formModel.value.keyword || undefined,
      status: formModel.value.status || undefined,
    }
    if (formModel.value.severity_id !== '' && formModel.value.severity_id != null) {
      params.severity_id = formModel.value.severity_id
    }

    if (timeRange.value && timeRange.value.length === 2) {
      params.start_time = new Date(timeRange.value[0]).toISOString()
      params.end_time = new Date(timeRange.value[1]).toISOString()
    }

    const result = await fetchAlertRecords(params)
    tableData.value = result.details?.data || []
    pagination.total = result.details?.total || 0
  } catch (error) {
    console.error('加载数据失败:', error)
    Message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  pagination.current = page
  loadData()
}

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

const handleRowClick = (record: any, _ev: Event) => {
  currentRecord.value = record
  detailDialogVisible.value = true
}

type ProcessAction = 'ack' | 'resolve' | 'silence' | 'comment'

// 根据告警受理处理的状态（record.status）控制操作列按钮可点击性
// 约定：
// - pending/firing：允许 ack/resolve/silence/comment
// - acked：禁用 ack，其它允许
// - resolved：只允许 comment
// - silenced/suppressed：只允许 comment
const isActionDisabled = (record: any, action: ProcessAction) => {
  const status = record?.status as string | undefined
  if (!status) return false

  const isResolved = status === 'resolved'
  const isAcked = status === 'acked'
  const isSilenced = status === 'silenced'
  const isSuppressed = status === 'suppressed'

  if (isResolved || isSilenced || isSuppressed) {
    return action !== 'comment'
  }

  if (isAcked) {
    return action === 'ack'
  }

  return false
}

const handleAck = (record: any) => {
  currentRecord.value = record
  ackDialogVisible.value = true
}

const handleResolve = (record: any) => {
  currentRecord.value = record
  resolveDialogVisible.value = true
}

const handleSilence = (record: any) => {
  currentRecord.value = record
  silenceDialogVisible.value = true
}

const handleComment = (record: any) => {
  currentRecord.value = record
  commentDialogVisible.value = true
}

const handleMoreAction = (action: string, record: any) => {
  currentRecord.value = record
  switch (action) {
    case 'detail':
      detailDialogVisible.value = true
      break
    case 'process':
      router.push({
        path: '/ops/alert/process',
        query: { alert_record_id: record.id },
      })
      break
  }
}

const handleMoreSelect = (
  value: string | number | Record<string, unknown> | undefined,
  record: any,
) => {
  handleMoreAction(String(value), record)
}

const handleSuccess = () => {
  loadData()
}

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

const formatDateTime = (datetime: string) => {
  if (!datetime) return '-'
  return new Date(datetime).toLocaleString('zh-CN')
}

const formatDuration = (seconds: number) => {
  if (!seconds) return '-'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)

  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  }
  return `${minutes}分钟`
}

const parsedLabels = (labels: string) => {
  if (!labels) return null
  try {
    return JSON.parse(labels)
  } catch {
    return null
  }
}

/** 单行展示，避免 a-space wrap + 多 tag 撑高整行 td（与其它告警列表页行高一致） */
const formatLabelsLine = (labels: string) => {
  const obj = parsedLabels(labels)
  if (!obj || typeof obj !== 'object') return ''
  return Object.entries(obj as Record<string, unknown>)
    .map(([k, v]) => `${k}: ${v == null ? '' : String(v)}`)
    .join(', ')
}

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    firing: 'red',
    pending: 'orange',
    acked: 'gold',
    resolved: 'green',
    silenced: 'gray',
    suppressed: 'lightgray',
  }
  return colorMap[status] || 'blue'
}

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    firing: '告警中',
    pending: '待处理',
    acked: '已确认',
    resolved: '已解决',
    silenced: '已屏蔽',
    suppressed: '已抑制',
  }
  return textMap[status] || status
}

const getNotifyStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    success: 'green',
    failed: 'red',
    pending: 'orange',
  }
  return colorMap[status] || 'blue'
}

const getNotifyStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    success: '成功',
    failed: '失败',
    pending: '待发送',
  }
  return textMap[status] || status
}
</script>

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

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

  /* 与未设置 table scroll 的告警列表页一致行高；宽表在表格外层横向滚动，避免 Arco scroll 模式改变单元格高度 */
  :deep(.search-table-container .data-table) {
    overflow-x: auto;
  }

  /* 标签列单行省略，与其它页纯文本单元格行高一致 */
  .cell-ellipsis {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 200px;
  }

  /* 与其它告警 SearchTable 页一致：正文单元格垂直居中 */
  :deep(.arco-table-size-medium .arco-table-td) {
    vertical-align: middle;
  }
}
</style>
