<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-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-divider orientation="left">服务器选择（二选一）</a-divider>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="服务器 ID" field="server_ids">
              <a-input-tag
                v-model="generateForm.server_ids_str"
                placeholder="输入ID后按回车"
                style="width: 100%"
                @change="handleServerIdsChange"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="服务器标识" field="server_identities">
              <a-input-tag
                v-model="generateForm.server_identities"
                placeholder="输入标识后按回车"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-divider orientation="left">报表配置</a-divider>

        <a-form-item label="报表列" field="columns">
          <a-checkbox-group v-model="generateForm.columns" style="width: 100%">
            <a-row>
              <a-col :span="8">
                <a-checkbox value="availability">可用性</a-checkbox>
              </a-col>
              <a-col :span="8">
                <a-checkbox value="last_check_time">最后检查时间</a-checkbox>
              </a-col>
              <a-col :span="8">
                <a-checkbox value="cpu">CPU</a-checkbox>
              </a-col>
              <a-col :span="8">
                <a-checkbox value="memory_phys">物理内存</a-checkbox>
              </a-col>
              <a-col :span="8">
                <a-checkbox value="memory_virt">虚拟内存</a-checkbox>
              </a-col>
              <a-col :span="8">
                <a-checkbox value="disk_io">磁盘 IO</a-checkbox>
              </a-col>
              <a-col :span="8">
                <a-checkbox value="disk_usage">磁盘使用率</a-checkbox>
              </a-col>
              <a-col :span="8">
                <a-checkbox value="daily_alerts">每日告警</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="可用性规则" field="availability_rule">
              <a-select v-model="generateForm.availability_rule" placeholder="请选择" style="width: 100%">
                <a-option value="metrics_presence">指标存在</a-option>
                <a-option value="server_status">服务器状态</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="包含每日告警" field="include_daily_alerts">
              <a-switch v-model="generateForm.include_daily_alerts" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="报表标题" field="title">
          <a-input v-model="generateForm.title" placeholder="可选，不填自动生成" style="width: 100%" />
        </a-form-item>
      </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">
        <!-- 汇总信息 -->
        <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.servers || []"
          :columns="contentTableColumns"
          :pagination="{ pageSize: 10 }"
          stripe
        />
      </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 ServerReportParams,
} from '@/api/ops/report'

// 页面标题
const pageTitle = '服务器报表'

// 列表筛选表单模型
const formModel = ref<{
  report_type: string
  status: string
  keyword: string
  timeRange: string[]
}>({
  report_type: ReportType.SERVER,
  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<{
  timeRange: string[]
  server_ids_str: string[]
  server_ids: number[]
  server_identities: string[]
  columns: string[]
  availability_rule: string
  include_daily_alerts: boolean
  title: string
}>({
  timeRange: [],
  server_ids_str: [],
  server_ids: [],
  server_identities: [],
  columns: ['availability', 'cpu', 'memory_phys', 'disk_usage'],
  availability_rule: 'metrics_presence',
  include_daily_alerts: false,
  title: '',
})

// 查看内容弹窗
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.servers || []

  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.SERVER,
    }

    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,
  }
}

// 处理服务器 ID 输入变化
const handleServerIdsChange = (value: string[]) => {
  generateForm.value.server_ids = value
    .map((v) => parseInt(v, 10))
    .filter((n) => !isNaN(n))
}

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

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

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

// 打开生成报表弹窗
const handleOpenGenerateModal = () => {
  generateForm.value = {
    timeRange: [],
    server_ids_str: [],
    server_ids: [],
    server_identities: [],
    columns: ['availability', 'cpu', 'memory_phys', 'disk_usage'],
    availability_rule: 'metrics_presence',
    include_daily_alerts: false,
    title: '',
  }
  generateModalVisible.value = true
}

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

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

  // 验证服务器选择
  if (
    generateForm.value.server_ids.length === 0 &&
    generateForm.value.server_identities.length === 0
  ) {
    Message.warning('请选择服务器（ID 或标识）')
    return
  }

  // 验证不能同时选择
  if (generateForm.value.server_ids.length > 0 && generateForm.value.server_identities.length > 0) {
    Message.warning('服务器 ID 和标识不能同时填写')
    return
  }

  generating.value = true

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

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

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

    if (generateForm.value.columns.length > 0) {
      params.columns = generateForm.value.columns as any
    }

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

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

    const res = await generateReport({
      report_type: ReportType.SERVER,
      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> = {
    server_id: '服务器 ID',
    server_identity: '服务器标识',
    server_name: '服务器名称',
    ip_address: 'IP 地址',
    availability: '可用性(%)',
    last_check_time: '最后检查时间',
    cpu: 'CPU使用率(%)',
    memory_phys: '物理内存(%)',
    memory_virt: '虚拟内存(%)',
    disk_io: '磁盘IO',
    disk_usage: '磁盘使用率(%)',
    daily_alerts: '每日告警数',
    avg_cpu: '平均CPU(%)',
    max_cpu: '最大CPU(%)',
    avg_memory: '平均内存(%)',
    max_memory: '最大内存(%)',
    total_servers: '服务器总数',
    available_servers: '可用服务器数',
    avg_availability: '平均可用性(%)',
  }

  return labelMap[key] || key
}

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

  // 百分比
  if (
    key.includes('rate') ||
    key.includes('usage') ||
    key.includes('cpu') ||
    key.includes('memory') ||
    key.includes('availability')
  ) {
    if (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: 'ServerReport',
}
</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>