<template>
  <a-modal
    :visible="visible"
    width="1200px"
    title="告警处理记录"
    :footer="false"
    @cancel="handleCancel"
    @update:visible="handleVisibleChange"
  >
    <a-spin :loading="loading" style="width: 100%">
      <div v-if="preloadedAlertRecord" style="margin-bottom: 16px">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="告警ID">{{ preloadedAlertRecord.id }}</a-descriptions-item>
          <a-descriptions-item label="告警名称">
            {{ preloadedAlertRecord.alert_name || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="getStatusColor(preloadedAlertRecord.status)">
              {{ getStatusText(preloadedAlertRecord.status) }}
            </a-tag>
          </a-descriptions-item>
        </a-descriptions>
      </div>

      <search-table
        :form-model="formModel"
        :form-items="formItems"
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        title="处理记录列表"
        :show-toolbar="false"
        :show-download="false"
        :show-refresh="false"
        :show-density="false"
        :show-column-setting="false"
        @update:form-model="handleFormModelUpdate"
        @search="handleSearch"
        @reset="handleReset"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>

        <template #created_at="{ record }">
          {{ formatDateTime(record.created_at) || '-' }}
        </template>

        <template #resolution_time="{ record }">
          {{ formatDateTime(record.resolution_time) || '-' }}
        </template>

        <template #action="{ record }">
          <a-tag :color="getActionColor(record.action)">
            {{ getActionText(record.action) }}
          </a-tag>
        </template>
      </search-table>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormItem } from '@/components/search-form/types'
import SearchTable from '@/components/search-table/index.vue'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import { fetchAlertProcessList, fetchHistoryDetail } from '@/api/ops/alertHistory'

interface Props {
  visible: boolean
  alertRecordId?: number
  alertRecord?: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const loading = ref(false)
const tableData = ref<any[]>([])

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

const formModel = ref({
  action: undefined as string | undefined,
  keyword: '',
})

const preloadedAlertRecord = ref<any>(props.alertRecord || null)

watch(
  () => props.alertRecord,
  (val) => {
    preloadedAlertRecord.value = val || null
  },
  { immediate: true }
)

const formItems = computed<FormItem[]>(() => [
  {
    field: 'action',
    label: '动作',
    type: 'select',
    placeholder: '请选择动作',
    options: [
      { label: '确认', value: 'ack' },
      { label: '解决', value: 'resolve' },
      { label: '屏蔽', value: 'silence' },
      { label: '评论', value: 'comment' },
      { label: '分配', value: 'assign' },
      { label: '升级', value: 'escalate' },
      { label: '关闭', value: 'close' },
    ],
  },
  {
    field: 'keyword',
    label: '关键字',
    type: 'input',
    placeholder: '匹配操作人/备注',
  },
])

const columns = computed<TableColumnData[]>(() => [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    width: 80,
  },
  {
    title: '时间',
    dataIndex: 'created_at',
    slotName: 'created_at',
    width: 180,
  },
  {
    title: '动作',
    dataIndex: 'action',
    slotName: 'action',
    width: 110,
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    width: 140,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '备注',
    dataIndex: 'comment',
    width: 320,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '完成时间',
    dataIndex: 'resolution_time',
    slotName: 'resolution_time',
    width: 200,
  },
])

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

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

const getActionColor = (action: string) => {
  const colorMap: Record<string, string> = {
    ack: 'gold',
    resolve: 'green',
    silence: 'gray',
    comment: 'blue',
    assign: 'purple',
    escalate: 'orange',
    close: 'red',
  }
  return colorMap[action] || 'blue'
}

const getActionText = (action: string) => {
  const textMap: Record<string, string> = {
    ack: '确认',
    resolve: '解决',
    silence: '屏蔽',
    comment: '评论',
    assign: '分配',
    escalate: '升级',
    close: '关闭',
  }
  return textMap[action] || action
}

const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  if (Number.isNaN(d.getTime())) return dateStr
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
}

const maybePreloadAlertRecord = async () => {
  if (preloadedAlertRecord.value && props.alertRecordId && preloadedAlertRecord.value.id === props.alertRecordId) {
    return
  }
  if (!props.alertRecordId) return

  loading.value = true
  try {
    const res: any = await fetchHistoryDetail(props.alertRecordId)
    if (res?.code === 0 && res?.details) {
      preloadedAlertRecord.value = res.details
    }
  } catch (error) {
    console.error('加载告警记录失败:', error)
    Message.error('加载告警记录失败')
  } finally {
    loading.value = false
  }
}

const loadProcessList = async () => {
  if (!props.alertRecordId) return

  loading.value = true
  try {
    const params: any = {
      alert_record_id: props.alertRecordId,
      action: formModel.value.action || undefined,
      keyword: formModel.value.keyword || undefined,
      page: pagination.current,
      page_size: pagination.pageSize,
    }

    const res: any = await fetchAlertProcessList(params)
    tableData.value = res?.details?.data || []
    pagination.total = res?.details?.total || 0

    // 预加载 AlertRecord：补齐到每一条处理记录上（接口返回为 null 时也能展示/联动）
    if (preloadedAlertRecord.value) {
      const alertRecord = preloadedAlertRecord.value
      tableData.value.forEach((item) => {
        if (!item.alert_record) {
          item.alert_record = alertRecord
        }
      })
    }
  } catch (error) {
    console.error('获取处理记录失败:', error)
    Message.error('获取处理记录失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const init = async () => {
  pagination.current = 1
  pagination.pageSize = pagination.pageSize || 20
  tableData.value = []
  pagination.total = 0
  formModel.value = {
    action: undefined,
    keyword: '',
  }

  // 强制按当前告警ID刷新预加载对象，避免切换时短暂复用旧数据
  preloadedAlertRecord.value = props.alertRecord || null

  await maybePreloadAlertRecord()
  await loadProcessList()
}

watch(
  () => props.visible,
  (val) => {
    if (val) {
      init()
    }
  }
)

const handleCancel = () => {
  emit('update:visible', false)
}

const handleVisibleChange = (val: boolean) => {
  emit('update:visible', val)
}

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

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

const handleReset = () => {
  formModel.value = {
    action: undefined,
    keyword: '',
  }
  pagination.current = 1
  loadProcessList()
}

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

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  loadProcessList()
}
</script>

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