<template>
  <AppPage :show-footer="false">
    <div flex-1>
      <!-- 筛选栏 -->
      <n-card rounded-10 mb-15>
        <n-space align="center">
          <n-select
            v-model:value="query.preset"
            :options="rangeOptions"
            placeholder="时间范围"
            style="width: 150px"
            @update:value="handlePresetChange"
          />
          <n-date-picker
            v-model:value="dateRange"
            type="daterange"
            clearable
            @update:value="handleQueryChange"
          />
          <n-button type="primary" @click="handleRefresh">
            <template #icon>
              <TheIcon icon="mdi:refresh" />
            </template>
            刷新
          </n-button>
        </n-space>
      </n-card>

      <!-- 概览数据 -->
  <n-grid :x-gap="15" :y-gap="15" :cols="4" mb-15>
    <n-gi>
      <n-card rounded-10 size="small">
        <n-statistic label="近选定时间段总量" :value="totalFromSources">
          <template #prefix>
            <TheIcon icon="mdi:database" color="#2080f0" :size="24" />
          </template>
        </n-statistic>
      </n-card>
    </n-gi>
        <n-gi>
          <n-card rounded-10 size="small">
            <n-statistic label="Boss直聘" :value="getSourceCount('boss')">
              <template #prefix>
                <TheIcon icon="mdi:alpha-b-box" color="#00bebd" :size="24" />
              </template>
            </n-statistic>
          </n-card>
        </n-gi>
        <n-gi>
          <n-card rounded-10 size="small">
            <n-statistic label="前程无忧" :value="getSourceCount('qcwy')">
              <template #prefix>
                <TheIcon icon="mdi:alpha-q-box" color="#ff6000" :size="24" />
              </template>
            </n-statistic>
          </n-card>
        </n-gi>
        <n-gi>
          <n-card rounded-10 size="small">
            <n-statistic label="智联招聘" :value="getSourceCount('zhilian')">
              <template #prefix>
                <TheIcon icon="mdi:alpha-z-box" color="#303a40" :size="24" />
              </template>
            </n-statistic>
          </n-card>
        </n-gi>
      </n-grid>

      <!-- 图表区域 -->
      <n-grid :x-gap="15" :y-gap="15" :cols="1" mb-15>
        <n-gi>
          <n-card title="数据采集趋势" rounded-10>
            <div ref="trendChartRef" style="height: 400px"></div>
          </n-card>
        </n-gi>
      </n-grid>

      <n-grid :x-gap="15" :y-gap="15" :cols="2">
        <n-gi>
           <n-card title="数据来源占比" rounded-10>
             <div ref="sourceChartRef" style="height: 300px"></div>
          </n-card>
        </n-gi>
         <n-gi>
          <n-card title="系统状态" rounded-10>
            <div flex items-center justify-center style="height: 300px; color: #999">
              <n-result status="success" title="系统运行正常">
                <template #footer>
                  <n-p>数据采集服务正在后台稳定运行中</n-p>
                </template>
              </n-result>
            </div>
          </n-card>
        </n-gi>
      </n-grid>

    </div>
  </AppPage>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import api from '@/api/analytics'
import { useMessage } from 'naive-ui'

const message = useMessage()

const query = ref({
  interval: 'day',
  preset: 'last_24h',
})
const dateRange = ref(null)

const overview = ref({
  total_jobs: 0,
  period: {}
})

const trendData = ref([])
const sourceDistribution = ref([])
const totalFromSources = computed(() => sourceDistribution.value.reduce((sum, i) => sum + (i.job_count || 0), 0))

// Charts refs
const trendChartRef = ref(null)
const sourceChartRef = ref(null)
let trendChart = null
let sourceChart = null

// Options
const intervalOptions = [
  { label: '按天', value: 'day' },
  { label: '按小时', value: 'hour' },
  { label: '按周', value: 'week' },
  { label: '按月', value: 'month' },
]

const rangeOptions = [
  { label: '近24小时', value: 'last_24h' },
  { label: '近7天', value: 'last_7d' },
  { label: '近30天', value: 'last_30d' },
  { label: '近90天', value: 'last_90d' },
  { label: '近6个月', value: 'last_6m' },
  { label: '近12个月', value: 'last_12m' },
  { label: '全部时间', value: 'all' },
  { label: '自定义', value: 'custom' },
]

const getSourceCount = (source) => {
  const item = sourceDistribution.value.find(i => i.category === source)
  return item ? item.job_count : 0
}

const getParams = () => {
  const params = { interval: query.value.interval }
  if (dateRange.value) {
    const start = new Date(dateRange.value[0])
    const end = new Date(dateRange.value[1])
    // 始终提供按“日”的边界，保障 overview/source 分布能过滤
    params.from_date = start.toISOString().split('T')[0]
    params.to_date = end.toISOString().split('T')[0]
    // 小时粒度额外提供精确时间窗口，供趋势/分布按小时筛选
    if (query.value.interval === 'hour') {
      params.from_datetime = start.toISOString()
      params.to_datetime = end.toISOString()
    }
  }
  return params
}

const handleIntervalChange = () => {
  if (query.value.preset !== 'custom') handlePresetChange(query.value.preset)
  fetchData()
}

const handlePresetChange = (val) => {
  query.value.preset = val
  const now = new Date()
  const end = now
  let start = new Date(now)
  if (val === 'last_24h') {
    query.value.interval = 'hour'
    start.setHours(now.getHours() - 24)
  } else if (val === 'last_7d') {
    query.value.interval = 'day'
    start.setDate(now.getDate() - 7)
  } else if (val === 'last_30d') {
    query.value.interval = 'day'
    start.setDate(now.getDate() - 30)
  } else if (val === 'last_90d') {
    query.value.interval = 'day'
    start.setDate(now.getDate() - 90)
  } else if (val === 'last_6m') {
    query.value.interval = 'week'
    start.setMonth(now.getMonth() - 6)
  } else if (val === 'last_12m') {
    query.value.interval = 'month'
    start.setFullYear(now.getFullYear() - 1)
  } else if (val === 'all') {
    query.value.interval = 'month'
    dateRange.value = null
  }
  if (val !== 'custom' && val !== 'all') {
    dateRange.value = [start.getTime(), end.getTime()]
  }
  fetchData()
}

const handleRefresh = () => {
  if (query.value.preset && query.value.preset !== 'custom') {
    handlePresetChange(query.value.preset)
  } else {
    fetchData()
  }
}

const fetchData = async () => {
  try {
    const params = getParams()
    
    // Parallel requests
    const [overviewRes, trendRes, sourceRes] = await Promise.all([
      api.getOverview(params),
      api.getVolumeTrend(params),
      api.getSourceDistribution(params)
    ])

    const unwrap = (res) => (res && res.data) ? res.data : res
    overview.value = unwrap(overviewRes) || { total_jobs: 0, period: {} }
    trendData.value = unwrap(trendRes) || []
    sourceDistribution.value = unwrap(sourceRes) || []
    
    renderCharts()
    
  } catch (error) {
    console.error(error)
    message.error('获取数据失败')
  }
}

const renderCharts = () => {
  renderTrendChart()
  renderSourceChart()
}

const renderTrendChart = () => {
  if (!trendChartRef.value) return
  if (!trendChart) trendChart = echarts.init(trendChartRef.value)
  
  // Process data for multi-series line chart
  const sources = ['boss', 'qcwy', 'zhilian']
  // Get all unique timestamps
  const times = [...new Set(trendData.value.map(d => d.time))].sort()
  
  const series = sources.map(source => {
    return {
      name: source === 'boss' ? 'Boss直聘' : source === 'qcwy' ? '前程无忧' : '智联招聘',
      type: 'line',
      smooth: true,
      data: times.map(t => {
        const item = trendData.value.find(d => d.time === t && d.source === source)
        return item ? item.count : 0
      })
    }
  })

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['Boss直聘', '前程无忧', '智联招聘']
    },
    dataZoom: [
      { type: 'slider', realtime: true },
      { type: 'inside' }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: times.map(t => {
         const d = new Date(t)
         if (query.value.interval === 'hour') {
             return `${d.getMonth()+1}-${d.getDate()} ${d.getHours()}:00`
         }
         if (query.value.interval === 'week') {
             const m = d.getMonth()+1
             const day = d.getDate()
             return `${d.getFullYear()}-${m}-${day}`
         }
         if (query.value.interval === 'month') {
             const m = d.getMonth()+1
             return `${d.getFullYear()}-${m}`
         }
         return d.toISOString().split('T')[0]
      })
    },
    yAxis: {
      type: 'value'
    },
    series: series
  }
  
  trendChart.setOption(option)
}

const renderSourceChart = () => {
  if (!sourceChartRef.value) return
  if (!sourceChart) sourceChart = echarts.init(sourceChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: '数据来源',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: sourceDistribution.value.map(item => ({
          value: item.job_count,
          name: item.category === 'boss' ? 'Boss直聘' : item.category === 'qcwy' ? '前程无忧' : '智联招聘'
        }))
      }
    ]
  }
  
  sourceChart.setOption(option)
}

const handleQueryChange = () => {
  fetchData()
}

// Lifecycle
onMounted(() => {
  handlePresetChange(query.value.preset)
  fetchData()
  window.addEventListener('resize', () => {
    trendChart?.resize()
    sourceChart?.resize()
  })
})
</script>
