<template>
  <div>
    <h2 style="margin-bottom: 24px">高危排行</h2>

    <!-- App selector bar -->
    <div class="app-selector-bar">
      <span class="selector-label">选择应用</span>
      <el-select
        :model-value="appKey"
        placeholder="请选择应用"
        style="width:220px"
        :loading="loadingApps"
        @change="setApp"
      >
        <el-option v-for="a in apps" :key="a.appKey" :label="a.name" :value="a.appKey" />
      </el-select>
    </div>
    <el-empty v-if="gateStatus === 'no-app'" description="请选择一个应用" style="margin-top:80px" />
    <div v-else-if="gateStatus === 'loading'" v-loading="true" style="min-height:200px" />
    <div v-else-if="gateStatus === 'not-enabled'" style="margin-top:60px;text-align:center">
      <el-empty description="当前应用未开通崩溃收集服务">
        <el-button type="primary" @click="applyDialogVisible = true">申请开通</el-button>
      </el-empty>
    </div>
    <template v-else>

    <!-- Bar Chart -->
    <el-card shadow="never" style="margin-bottom:16px">
      <template #header>高危错误 Top 20（风险分 = 次数 × 影响用户 × 级别权重）</template>
      <div ref="chartRef" class="chart-container"></div>
    </el-card>

    <el-card shadow="never">
      <el-table :data="rankings" v-loading="loading" border stripe>
        <el-table-column type="index" label="#" width="60" />
        <el-table-column prop="title" label="错误标题" min-width="280" show-overflow-tooltip>
          <template #default="{ row }">
            <el-button link type="primary" @click="$router.push(`/bugcollect/issues/${row.id}`)">
              {{ row.title }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="级别" width="110">
          <template #default="{ row }">
            <el-tag size="small" :type="levelTag(row.level)">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="platform" label="平台" width="110" />
        <el-table-column prop="riskScore" label="风险分" width="100" sortable>
          <template #default="{ row }">
            <el-tag :type="riskTagType(row.riskScore)" size="small">{{ row.riskScore }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="count" label="次数" width="100" sortable />
        <el-table-column prop="status" label="状态" width="90"><template #default="{ row }"><el-tag size="small" :type="statusTag(row.status)">{{ statusLabel(row.status) }}</el-tag></template></el-table-column>
        <el-table-column prop="lastSeenAt" label="最后出现" width="170">
          <template #default="{ row }">
            <span class="time-text">{{ formatTime(row.lastSeenAt) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    </template>
    <el-dialog v-model="applyDialogVisible" title="申请开通崩溃收集" width="400px" :close-on-click-modal="false">
      <el-input v-model="applyReason" type="textarea" placeholder="请说明申请原因（选填）" :rows="3" />
      <template #footer>
        <el-button @click="applyDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="applyLoading" @click="submitActivation">提交申请</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { bugCollectApi, type BugCollectIssueRanking } from '@/api/bugcollect'
import { useBugCollectApp } from '@/composables/useBugCollectApp'
import { levelTag, statusTag, statusLabel, formatTime } from '@/utils/bugCollect'
import * as echarts from 'echarts'

const { apps, loadingApps, appKey, setApp, gateStatus, applyDialogVisible, applyReason, applyLoading, submitActivation } = useBugCollectApp()

const rankings = ref<BugCollectIssueRanking[]>([])
const loading = ref(false)
const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

const LEVEL_COLORS: Record<string, string> = {
  fatal: '#F56C6C',
  error: '#E6A23C',
  warning: '#409EFF',
}




function riskTagType(score?: number) {
  if (!score) return 'info'
  if (score >= 80) return 'danger'
  if (score >= 50) return 'warning'
  return 'success'
}


function truncateTitle(title: string, maxLen = 30): string {
  if (!title) return ''
  return title.length > maxLen ? title.slice(0, maxLen) + '...' : title
}

async function loadData() {
  if (!appKey.value || gateStatus.value !== 'enabled') return
  loading.value = true
  try {
    const res = await bugCollectApi.riskRanking(appKey.value, { limit: 20 })
    rankings.value = res.data.data ?? []
    await nextTick()
    renderChart()
  } catch {
    ElMessage.error('加载高危排行失败')
    rankings.value = []
  } finally {
    loading.value = false
  }
}

function renderChart() {
  if (!chartRef.value || rankings.value.length === 0) return
  if (!chart) chart = echarts.init(chartRef.value)

  const data = [...rankings.value].reverse()
  chart.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    grid: { left: 200, right: 40, top: 10, bottom: 30 },
    xAxis: { type: 'value' },
    yAxis: {
      type: 'category',
      data: data.map(d => truncateTitle(d.title, 25)),
      axisLabel: { width: 180, overflow: 'truncate', fontSize: 12 },
    },
    series: [{
      type: 'bar',
      data: data.map(d => ({
        value: d.riskScore ?? 0,
        itemStyle: { color: LEVEL_COLORS[d.level] ?? '#409EFF' },
      })),
      label: { show: true, position: 'right', formatter: '{c}' },
    }],
  })
}

function handleChartResize() {
  chart?.resize()
}

watch(gateStatus, (s) => { if (s === 'enabled') loadData() })
onMounted(() => {
  loadData()
  window.addEventListener('resize', handleChartResize)
})
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleChartResize)
  chart?.dispose()
})
</script>

<style scoped>
.app-selector-bar { display:flex; align-items:center; gap:12px; margin-bottom:20px; }
.selector-label { font-size:14px; color:#606266; }
.time-text {
  font-size: 13px;
  color: #666;
}
.chart-container {
  width: 100%;
  height: 400px;
}
</style>
