<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>
              <a-doption @click="handleExport('pdf')">导出 PDF</a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </template>

      <template #status="{ record }">
        <a-tag :color="reportStatusColor(record.status)">
          {{ reportStatusLabel[record.status] || record.status || '—' }}
        </a-tag>
      </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-button v-if="record.status === 'success'" type="text" size="small" @click="handleExport('pdf', record)">PDF</a-button>
        </a-space>
      </template>
    </search-table>

    <!-- 生成报表弹窗（与后端 network_device 参数一致：service_identities 或 network_device_service_ids） -->
    <a-modal
      v-model:visible="generateModalVisible"
      title="生成网络设备报表"
      :width="640"
      :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="network_device_service_ids">
              <a-select
                v-model="generateForm.network_device_service_ids"
                multiple
                allow-clear
                allow-search
                :loading="networkDeviceOptionsLoading"
                :options="networkDeviceIdOptions"
                placeholder="按库表主键选择"
                :max-tag-count="3"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="服务标识 service_identity" field="service_identities">
              <a-select
                v-model="generateForm.service_identities"
                multiple
                allow-clear
                allow-search
                :loading="networkDeviceOptionsLoading"
                :options="networkDeviceIdentityOptions"
                placeholder="按采集标识选择"
                :max-tag-count="3"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="包含每日告警统计" field="include_daily_alerts">
          <a-switch v-model="generateForm.include_daily_alerts" />
        </a-form-item>

        <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">
        <!-- 网络设备 / 通用行表（与引擎 payload.rows 一致） -->
        <template v-if="reportContentType === 'rows'">
          <a-card
            v-if="reportContent.result_meta && Object.keys(reportContent.result_meta).length"
            title="说明"
            :bordered="false"
            class="summary-card"
          >
            <a-descriptions :column="1" bordered size="small">
              <a-descriptions-item
                v-for="(value, key) in reportContent.result_meta"
                :key="String(key)"
                :label="formatLabel(String(key))"
              >
                {{ formatValue(String(key), value) }}
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
          <a-table
            :data="reportContent.rows || []"
            :columns="contentTableColumns"
            :pagination="{ pageSize: 10 }"
            stripe
          />
        </template>

        <!-- 汇总数据（旧流量形态占位） -->
        <template v-else-if="reportContentType === 'summary'">
          <a-card v-if="reportContent.totals" title="设备汇总" :bordered="false" class="summary-card">
            <a-descriptions :column="3" bordered>
              <a-descriptions-item v-for="(value, key) in reportContent.totals" :key="key" :label="formatLabel(String(key))">
                {{ formatValue(String(key), value) }}
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
          <a-table :data="reportContent.by_node || []" :columns="contentTableColumns" :pagination="{ pageSize: 10 }" stripe />
        </template>

        <!-- 明细数据 -->
        <template v-else-if="reportContentType === 'detail'">
          <a-table :data="reportContent.items || []" :columns="contentTableColumns" :pagination="{ pageSize: 10 }" stripe />
        </template>

        <!-- 趋势数据 -->
        <template v-else-if="reportContentType === 'trend'">
          <div ref="chartRef" class="chart-container"></div>
        </template>

        <!-- Top 排名数据 -->
        <template v-else-if="reportContentType === 'top'">
          <a-table :data="reportContent.ranking || []" :columns="contentTableColumns" :pagination="false" stripe />
        </template>
      </div>
      <a-empty v-else description="暂无数据" />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, nextTick } 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,
  ReportType,
  type ReportRecord,
  type NetworkDeviceReportParams,
} from '@/api/ops/report'
import * as echarts from 'echarts'
import { downloadReportFile } from '../useReportExport'
import type { ReportExportFormat } from '@/api/ops/report'
import { normalizeReportRows, reportStatusColor, reportStatusLabel } from '../useReportListRow'
import { useReportNetworkDevicePickOptions } from '../useReportNetworkDevicePickOptions'

const {
  networkDeviceIdOptions,
  networkDeviceIdentityOptions,
  networkDeviceOptionsLoading,
  loadNetworkDevicePickOptions,
} = useReportNetworkDevicePickOptions()

// 页面标题
const pageTitle = '网络设备报表'

// 列表筛选表单模型
const formModel = ref<{
  report_type: string
  status: string
  keyword: string
  timeRange: string[]
}>({
  report_type: ReportType.NETWORK_DEVICE,
  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<{
  network_device_service_ids: number[]
  service_identities: string[]
  timeRange: string[]
  include_daily_alerts: boolean
  title: string
}>({
  network_device_service_ids: [],
  service_identities: [],
  timeRange: [],
  include_daily_alerts: false,
  title: '',
})

// 查看内容弹窗
const contentModalVisible = ref(false)
const contentModalTitle = ref('')
const reportContent = ref<Record<string, any> | null>(null)
const reportContentType = ref<string>('')
const chartRef = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

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

  const data =
    reportContent.value.rows ||
    reportContent.value.by_node ||
    reportContent.value.items ||
    reportContent.value.ranking ||
    []

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

    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 = normalizeReportRows(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.NETWORK_DEVICE,
    status: '',
    keyword: '',
    timeRange: [],
  }
  pagination.current = 1
  fetchList()
}

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

// 打开生成报表弹窗
const handleOpenGenerateModal = () => {
  generateForm.value = {
    network_device_service_ids: [],
    service_identities: [],
    timeRange: [],
    include_daily_alerts: false,
    title: '',
  }
  void loadNetworkDevicePickOptions()
  generateModalVisible.value = true
}

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

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

  const ids = generateForm.value.network_device_service_ids || []
  const idents = generateForm.value.service_identities || []
  if (ids.length === 0 && idents.length === 0) {
    Message.warning('请选择网络设备（服务 ID 或 service_identity）')
    return
  }
  if (ids.length > 0 && idents.length > 0) {
    Message.warning('服务 ID 与 service_identity 请勿同时选择')
    return
  }

  generating.value = true

  try {
    const params: NetworkDeviceReportParams = {
      start_time: generateForm.value.timeRange[0],
      end_time: generateForm.value.timeRange[1],
    }
    if (ids.length > 0) {
      params.network_device_service_ids = ids
    }
    if (idents.length > 0) {
      params.service_identities = idents
    }
    if (generateForm.value.include_daily_alerts) {
      params.include_daily_alerts = true
    }

    const res = await generateReport({
      report_type: ReportType.NETWORK_DEVICE,
      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
      const rows = res.details?.rows
      if (Array.isArray(rows) && rows.length > 0) {
        reportContentType.value = 'rows'
      } else {
        reportContentType.value = targetRecord.params_json?.report_shape || 'summary'
      }

      if (reportContentType.value === 'trend' && res.details.series) {
        await nextTick()
        renderChart(res.details.series)
      }
    } else {
      Message.error(res.message || '获取报表内容失败')
    }
  } catch (error: any) {
    console.error('获取报表内容失败:', error)
    Message.error(error.message || '获取报表内容失败')
  } finally {
    contentLoading.value = false
  }
}

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

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

  exporting.value = true

  try {
    await downloadReportFile(targetRecord, format)

    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: '服务标识',
    availability: '可用性',
    cpu_avg: 'CPU 均值',
    memory_avg: '内存均值',
    success_rate: '接口 up 占比(%)',
    jitter_bps_stddev: '速率抖动(标准差)',
    daily_alerts: '当日告警数',
    avg_response_time_ms: '平均响应(ms)',
    uptime_seconds: '运行时长(秒)',
    node_id: '节点 ID',
    total_in_bytes: '总入流量',
    total_out_bytes: '总出流量',
    total_bytes: '总流量',
    avg_latency: '平均延迟(ms)',
    max_latency: '最大延迟(ms)',
    min_latency: '最小延迟(ms)',
    peak_bandwidth: '峰值带宽(Mbps)',
    avg_bandwidth: '平均带宽(Mbps)',
    total_packets: '总包数',
    packet_loss_rate: '丢包率(%)',
    total_connections: '总连接数',
    avg_connections: '平均连接数',
    peak_connections: '峰值连接数',
    rank: '排名',
    timestamp: '时间',
    value: '值',
  }

  return labelMap[key] || key
}

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

  // 带宽转换为 Mbps
  if (key.includes('bandwidth') && typeof value === 'number') {
    return (value / 1024 / 1024).toFixed(2)
  }

  // 丢包率转换为百分比
  if (key === 'packet_loss_rate' && typeof value === 'number') {
    return (value * 100).toFixed(2) + '%'
  }

  // 字节数转换为更易读的单位
  if (key.includes('bytes') && typeof value === 'number') {
    if (value > 1024 * 1024 * 1024) {
      return (value / 1024 / 1024 / 1024).toFixed(2) + ' GB'
    } else if (value > 1024 * 1024) {
      return (value / 1024 / 1024).toFixed(2) + ' MB'
    } else if (value > 1024) {
      return (value / 1024).toFixed(2) + ' KB'
    }
    return value + ' B'
  }

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

  return value
}

// 渲染图表
const renderChart = (series: any[]) => {
  if (!chartRef.value || series.length === 0) return

  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartRef.value)

  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: series.map((s) => s.name),
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: series[0]?.data?.map((item: any) => item.timestamp) || [],
    },
    yAxis: {
      type: 'value',
    },
    series: series.map((s) => ({
      name: s.name,
      type: 'line',
      smooth: true,
      data: s.data?.map((item: any) => item.value) || [],
    })),
  }

  chartInstance.setOption(option)
}

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

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

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

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

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

  .chart-container {
    height: 400px;
    width: 100%;
  }

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