<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"
    >
      <!-- 自定义表单项：创建时间范围 -->
      <template #form-items>
        <a-col :span="8">
          <a-form-item label="创建时间" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
            <a-range-picker
              v-model="formModel.timeRange"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </template>

      <!-- 工具栏左侧：生成报表按钮 -->
      <template #toolbar-left>
        <a-space>
          <a-button type="primary" @click="handleOpenGenerateModal">
            <template #icon><icon-file-add /></template>
            生成报表
          </a-button>
        </a-space>
      </template>

      <!-- 工具栏右侧：查看和导出按钮 -->
      <template #toolbar-right>
        <a-space>
          <a-button v-if="selectedRecord" type="outline" @click="handleViewContent()">
            <template #icon><icon-eye /></template>
            查看内容
          </a-button>
          <a-dropdown v-if="selectedRecord">
            <a-button type="outline">
              <template #icon><icon-download /></template>
              导出
            </a-button>
            <template #content>
              <a-doption @click="handleExport('csv')">导出 CSV</a-doption>
              <a-doption @click="handleExport('xlsx')">导出 Excel</a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </template>

      <!-- 操作列 -->
      <template #operations="{ record }">
        <a-space>
          <a-button
            v-if="record.status === 'success'"
            type="text"
            size="small"
            @click="handleViewContent(record)"
          >
            查看
          </a-button>
          <a-button
            v-if="record.status === 'success'"
            type="text"
            size="small"
            @click="handleExport('csv', record)"
          >
            CSV
          </a-button>
          <a-button
            v-if="record.status === 'success'"
            type="text"
            size="small"
            @click="handleExport('xlsx', record)"
          >
            Excel
          </a-button>
        </a-space>
      </template>
    </search-table>

    <!-- 生成报表弹窗 -->
    <a-modal
      v-model:visible="generateModalVisible"
      title="生成故障报表"
      :width="600"
      :ok-loading="generating"
      @ok="handleGenerate"
      @cancel="handleCloseGenerateModal"
    >
      <a-form :model="generateForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="数据源" field="fault_data_source">
              <a-select v-model="generateForm.fault_data_source" placeholder="请选择" style="width: 100%">
                <a-option value="collector_log">采集器日志</a-option>
                <a-option value="alert">告警</a-option>
                <a-option value="hybrid">混合</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="分组方式" field="group_by">
              <a-select v-model="generateForm.group_by" placeholder="请选择" style="width: 100%">
                <a-option value="none">不分组</a-option>
                <a-option value="service_identity">按服务</a-option>
                <a-option value="day">按日期</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="时间范围" field="timeRange" :rules="[{ required: true, message: '请选择时间范围' }]">
          <a-range-picker
            v-model="generateForm.timeRange"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item label="服务标识" field="service_identities">
          <a-input-tag
            v-model="generateForm.service_identities"
            placeholder="输入后按回车添加"
            style="width: 100%"
          />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="状态过滤" field="status">
              <a-select v-model="generateForm.status" placeholder="请选择" style="width: 100%" allow-clear>
                <a-option value="success">成功</a-option>
                <a-option value="failed">失败</a-option>
                <a-option value="timeout">超时</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="关键字" field="keyword">
              <a-input v-model="generateForm.keyword" placeholder="消息/错误信息模糊匹配" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="报表标题" field="title">
              <a-input v-model="generateForm.title" placeholder="可选，不填自动生成" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="明细条数限制" field="detail_limit">
              <a-input-number
                v-model="generateForm.detail_limit"
                placeholder="不分组时限制条数"
                :min="1"
                :max="50000"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 告警相关参数 -->
        <template v-if="generateForm.fault_data_source === 'alert' || generateForm.fault_data_source === 'hybrid'">
          <a-divider orientation="left">告警过滤</a-divider>
          <a-form-item label="告警级别" field="alert_severities">
            <a-select
              v-model="generateForm.alert_severities"
              placeholder="请选择告警级别"
              style="width: 100%"
              multiple
            >
              <a-option value="critical">严重</a-option>
              <a-option value="warning">警告</a-option>
              <a-option value="info">信息</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="包含原始消息" field="include_raw_messages">
            <a-switch v-model="generateForm.include_raw_messages" />
          </a-form-item>
        </template>
      </a-form>
    </a-modal>

    <!-- 查看内容弹窗 -->
    <a-modal
      v-model:visible="contentModalVisible"
      :title="contentModalTitle"
      :width="900"
      :footer="false"
    >
      <div v-if="contentLoading" class="loading-container">
        <a-spin />
      </div>
      <div v-else-if="reportContent">
        <!-- 分组统计 -->
        <template v-if="reportContent.grouped">
          <a-card v-if="reportContent.summary" title="故障汇总" :bordered="false" class="summary-card">
            <a-descriptions :column="3" bordered>
              <a-descriptions-item
                v-for="(value, key) in reportContent.summary"
                :key="key"
                :label="formatLabel(String(key))"
              >
                {{ formatValue(String(key), value) }}
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
          <a-table
            :data="reportContent.groups || []"
            :columns="groupTableColumns"
            :pagination="{ pageSize: 10 }"
            stripe
          />
        </template>

        <!-- 明细列表 -->
        <template v-else>
          <a-table
            :data="reportContent.items || []"
            :columns="contentTableColumns"
            :pagination="{ pageSize: 10 }"
            stripe
          />
        </template>
      </div>
      <a-empty v-else description="暂无数据" />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import SearchTable from '@/components/search-table/index.vue'
import type { FormItem } from '@/components/search-form/types'
import {
  fetchReportList,
  generateReport,
  fetchReportContent,
  exportReport,
  ReportType,
  type ReportRecord,
  type FaultReportParams,
} from '@/api/ops/report'

// 页面标题
const pageTitle = '故障报表'

// 列表筛选表单模型
const formModel = ref<{
  report_type: string
  status: string
  keyword: string
  timeRange: string[]
}>({
  report_type: ReportType.FAULT,
  status: '',
  keyword: '',
  timeRange: [],
})

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    field: 'status',
    label: '状态',
    type: 'select',
    span: 8,
    placeholder: '请选择',
    options: [
      { value: '', label: '全部' },
      { value: 'pending', label: '等待中' },
      { value: 'running', label: '生成中' },
      { value: 'success', label: '成功' },
      { value: 'failed', label: '失败' },
    ],
  },
  {
    field: 'keyword',
    label: '标题',
    type: 'input',
    span: 8,
    placeholder: '请输入标题关键字',
  },
])

// 状态
const loading = ref(false)
const generating = ref(false)
const contentLoading = ref(false)
const exporting = ref(false)
const tableData = ref<ReportRecord[]>([])
const selectedRecord = ref<ReportRecord | null>(null)

// 分页配置
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: 'title',
    width: 200,
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    slotName: 'status',
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    width: 180,
  },
  {
    title: '更新时间',
    dataIndex: 'updated_at',
    width: 180,
  },
  {
    title: '操作',
    dataIndex: 'operations',
    width: 180,
    slotName: 'operations',
    fixed: 'right' as const,
  },
])

// 生成报表弹窗
const generateModalVisible = ref(false)
const generateForm = ref<{
  fault_data_source: string
  group_by: string
  timeRange: string[]
  service_identities: string[]
  status: string
  keyword: string
  title: string
  detail_limit: number | undefined
  alert_severities: string[]
  include_raw_messages: boolean
}>({
  fault_data_source: 'collector_log',
  group_by: 'none',
  timeRange: [],
  service_identities: [],
  status: '',
  keyword: '',
  title: '',
  detail_limit: undefined,
  alert_severities: [],
  include_raw_messages: false,
})

// 查看内容弹窗
const contentModalVisible = ref(false)
const contentModalTitle = ref('')
const reportContent = ref<Record<string, any> | null>(null)

// 内容表格列配置
const contentTableColumns = computed(() => {
  if (!reportContent.value) return []

  const data = reportContent.value.items || []

  if (data.length === 0) return []

  const firstRecord = data[0]
  return Object.keys(firstRecord).map((key) => ({
    title: formatLabel(key),
    dataIndex: key,
    width: 150,
  }))
})

// 分组表格列配置
const groupTableColumns = computed(() => {
  if (!reportContent.value) return []

  const data = reportContent.value.groups || []

  if (data.length === 0) return []

  const firstRecord = data[0]
  return Object.keys(firstRecord).map((key) => ({
    title: formatLabel(key),
    dataIndex: key,
    width: 150,
  }))
})

// 获取报表列表
const fetchList = async () => {
  loading.value = true

  try {
    const params: any = {
      page: pagination.current,
      size: pagination.pageSize,
      report_type: ReportType.FAULT,
    }

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

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

    if (formModel.value.timeRange && formModel.value.timeRange.length === 2) {
      params.created_from = formModel.value.timeRange[0]
      params.created_to = formModel.value.timeRange[1]
    }

    const res = await fetchReportList(params)

    if (res.code === 0 && res.details) {
      tableData.value = res.details.data || []
      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: any) => {
  formModel.value = {
    ...formModel.value,
    ...value,
  }
}

// 查询
const handleSearch = () => {
  pagination.current = 1
  fetchList()
}

// 重置
const handleReset = () => {
  formModel.value = {
    report_type: ReportType.FAULT,
    status: '',
    keyword: '',
    timeRange: [],
  }
  pagination.current = 1
  fetchList()
}

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

// 打开生成报表弹窗
const handleOpenGenerateModal = () => {
  generateForm.value = {
    fault_data_source: 'collector_log',
    group_by: 'none',
    timeRange: [],
    service_identities: [],
    status: '',
    keyword: '',
    title: '',
    detail_limit: undefined,
    alert_severities: [],
    include_raw_messages: false,
  }
  generateModalVisible.value = true
}

// 关闭生成报表弹窗
const handleCloseGenerateModal = () => {
  generateModalVisible.value = false
}

// 生成报表
const handleGenerate = async () => {
  // 验证必填项
  if (!generateForm.value.timeRange || generateForm.value.timeRange.length !== 2) {
    Message.warning('请选择时间范围')
    return
  }

  generating.value = true

  try {
    const params: FaultReportParams = {
      start_time: generateForm.value.timeRange[0],
      end_time: generateForm.value.timeRange[1],
    }

    if (generateForm.value.fault_data_source) {
      params.fault_data_source = generateForm.value.fault_data_source as any
    }

    if (generateForm.value.group_by) {
      params.group_by = generateForm.value.group_by as any
    }

    if (generateForm.value.service_identities && generateForm.value.service_identities.length > 0) {
      params.service_identities = generateForm.value.service_identities
    }

    if (generateForm.value.status) {
      params.status = generateForm.value.status as any
    }

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

    if (generateForm.value.detail_limit) {
      params.detail_limit = generateForm.value.detail_limit
    }

    if (generateForm.value.alert_severities && generateForm.value.alert_severities.length > 0) {
      params.alert_severities = generateForm.value.alert_severities
    }

    if (generateForm.value.include_raw_messages) {
      params.include_raw_messages = generateForm.value.include_raw_messages
    }

    const res = await generateReport({
      report_type: ReportType.FAULT,
      title: generateForm.value.title || undefined,
      params,
    })

    if (res.code === 0 && res.details) {
      if (res.details.status === 'success') {
        Message.success('报表生成成功')
        generateModalVisible.value = false
        fetchList()
      } else if (res.details.status === 'failed') {
        Message.error(res.details.error_message || '报表生成失败')
      } else {
        Message.info('报表正在生成中，请稍后刷新查看')
        generateModalVisible.value = false
        fetchList()
      }
    } else {
      Message.error(res.message || '报表生成失败')
    }
  } catch (error: any) {
    console.error('生成报表失败:', error)
    Message.error(error.message || '生成报表失败')
  } finally {
    generating.value = false
  }
}

// 查看内容
const handleViewContent = async (record?: ReportRecord) => {
  const targetRecord = record || selectedRecord.value
  if (!targetRecord) return

  contentLoading.value = true
  contentModalVisible.value = true
  contentModalTitle.value = targetRecord.title
  reportContent.value = null

  try {
    const res = await fetchReportContent(targetRecord.id)

    if (res.code === 0 && res.details) {
      reportContent.value = res.details
    } else {
      Message.error(res.message || '获取报表内容失败')
    }
  } catch (error: any) {
    console.error('获取报表内容失败:', error)
    Message.error(error.message || '获取报表内容失败')
  } finally {
    contentLoading.value = false
  }
}

// 导出报表
const handleExport = async (format: 'csv' | 'xlsx', record?: ReportRecord) => {
  const targetRecord = record || selectedRecord.value
  if (!targetRecord) {
    Message.warning('请选择要导出的报表')
    return
  }

  if (targetRecord.status !== 'success') {
    Message.warning('只能导出生成成功的报表')
    return
  }

  exporting.value = true

  try {
    const blob = await exportReport(targetRecord.id, format)

    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `report_${targetRecord.id}.${format}`

    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    Message.success('导出成功')
  } catch (error: any) {
    console.error('导出失败:', error)
    Message.error(error.message || '导出失败')
  } finally {
    exporting.value = false
  }
}

// 格式化标签
const formatLabel = (key: string) => {
  const labelMap: Record<string, string> = {
    service_identity: '服务标识',
    total_count: '总次数',
    success_count: '成功次数',
    failed_count: '失败次数',
    timeout_count: '超时次数',
    success_rate: '成功率(%)',
    avg_duration: '平均耗时(ms)',
    max_duration: '最大耗时(ms)',
    min_duration: '最小耗时(ms)',
    timestamp: '时间',
    message: '消息',
    error_message: '错误信息',
    status: '状态',
    day: '日期',
    rank: '排名',
  }

  return labelMap[key] || key
}

// 格式化数值
const formatValue = (key: string, value: any) => {
  if (value === null || value === undefined) return '-'

  // 百分比
  if (key.includes('rate') && typeof value === 'number') {
    return value.toFixed(2) + '%'
  }

  // 数字类型保留两位小数
  if (typeof value === 'number') {
    return value.toFixed(2)
  }

  return value
}

// 初始化
fetchList()
</script>

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

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

  .summary-card {
    margin-bottom: 20px;

    :deep(.arco-card-body) {
      padding: 16px;
    }
  }

  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
  }
}
</style>