<template>
  <div class="analytics-page">
    <div class="page-header flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-[#d4b383]">数据分析</h1>
      <div class="date-filter flex gap-2">
        <div class="quick-select flex bg-white/5 rounded-lg p-1 border border-white/10">
          <button 
            v-for="range in dateRanges" 
            :key="range.value"
            @click="selectRange(range.value)"
            class="px-3 py-1 text-sm rounded transition-colors"
            :class="selectedRange === range.value ? 'bg-[#d4b383] text-black' : 'text-white/60 hover:text-white'"
          >
            {{ range.label }}
          </button>
        </div>
        <div class="custom-date flex gap-2 items-center">
           <!-- 使用datetime-local以支持精确到分钟，虽然这里主要用日期，但预留接口 -->
           <input type="datetime-local" v-model="startDateTime" class="bg-white/5 border border-white/10 rounded px-2 py-1 text-white text-sm outline-none focus:border-[#d4b383]" @change="validateDates">
           <span class="text-white/40">-</span>
           <input type="datetime-local" v-model="endDateTime" class="bg-white/5 border border-white/10 rounded px-2 py-1 text-white text-sm outline-none focus:border-[#d4b383]" @change="validateDates">
           
           <button @click="clearDates" class="px-2 py-1 text-white/40 hover:text-white text-sm" title="清空">✕</button>
           <button @click="handleSearch" class="px-3 py-1 bg-[#d4b383]/20 text-[#d4b383] border border-[#d4b383]/50 rounded text-sm hover:bg-[#d4b383]/30 transition-colors" :disabled="loading">
             {{ loading ? '加载中...' : '查询' }}
           </button>
        </div>
      </div>
    </div>

    <div v-if="dateError" class="mb-4 p-3 bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg text-sm">
      {{ dateError }}
    </div>

    <!-- Charts Row 1 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
      <!-- New Posts Trend -->
      <div class="chart-card relative">
        <h3 class="chart-title">新增博文趋势</h3>
        <div class="h-80" v-if="!loading && hasData(stats.postsTrend)">
          <v-chart class="chart" :option="postsTrendOption" autoresize />
        </div>
        <div v-else-if="loading" class="h-80 flex items-center justify-center text-white/20">
          加载中...
        </div>
        <div v-else class="h-80 flex items-center justify-center text-white/20">
          暂无数据
        </div>
      </div>

      <!-- UV Trend -->
      <div class="chart-card relative">
        <h3 class="chart-title">访客趋势 (UV)</h3>
        <div class="h-80" v-if="!loading && hasData(stats.uvTrend)">
          <v-chart class="chart" :option="uvTrendOption" autoresize />
        </div>
        <div v-else-if="loading" class="h-80 flex items-center justify-center text-white/20">
          加载中...
        </div>
        <div v-else class="h-80 flex items-center justify-center text-white/20">
          暂无数据
        </div>
      </div>
    </div>

    <!-- Charts Row 2 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
      <!-- Operation Trend -->
      <div class="chart-card relative">
        <h3 class="chart-title">管理员操作统计</h3>
        <div class="h-80" v-if="!loading && hasData(stats.operationTrend)">
          <v-chart class="chart" :option="operationTrendOption" autoresize />
        </div>
        <div v-else-if="loading" class="h-80 flex items-center justify-center text-white/20">
          加载中...
        </div>
        <div v-else class="h-80 flex items-center justify-center text-white/20">
          暂无数据
        </div>
      </div>

      <!-- Top Posts -->
      <div class="chart-card relative">
        <h3 class="chart-title">热门文章 Top 5</h3>
        <div class="h-80" v-if="!loading && hasData(stats.topPosts)">
          <v-chart class="chart" :option="topPostsOption" autoresize />
        </div>
        <div v-else-if="loading" class="h-80 flex items-center justify-center text-white/20">
          加载中...
        </div>
        <div v-else class="h-80 flex items-center justify-center text-white/20">
          暂无数据
        </div>
      </div>
    </div>

    <!-- User Regions - Full Width -->
    <div class="chart-card relative">
      <h3 class="chart-title">用户地域分布</h3>
      <div class="h-[800px]" v-if="!loading && hasData(stats.userRegions) && mapDataLoaded">
        <v-chart class="chart" :option="regionOption" autoresize />
      </div>
      <div v-else-if="loading" class="h-[800px] flex items-center justify-center text-white/20">
        加载中...
      </div>
      <div v-else-if="!mapDataLoaded" class="h-[800px] flex items-center justify-center text-white/40">
        <div class="text-center">
          <p class="mb-2">地图数据加载失败</p>
          <p class="text-sm text-white/60">请检查网络连接或稍后重试</p>
        </div>
      </div>
      <div v-else class="h-[800px] flex items-center justify-center text-white/20">
        暂无数据
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart, PieChart, MapChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  GeoComponent,
  VisualMapComponent
} from 'echarts/components'
import * as echarts from 'echarts/core'
import VChart from 'vue-echarts'
import { getDashboardStats } from '../../../services/api'
import { useToast } from '../../../composables/useToast'
import chinaMapData from '../../../composables/full.json'

use([
  CanvasRenderer,
  BarChart,
  LineChart,
  PieChart,
  MapChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  GeoComponent,
  VisualMapComponent
])

const toast = useToast()
const stats = ref<any>({})
const loading = ref(false)
const selectedRange = ref('7d')
const startDateTime = ref('')
const endDateTime = ref('')
const dateError = ref('')

const dateRanges = [
  { label: '今日', value: 'today' },
  { label: '本周', value: 'week' },
  { label: '本月', value: 'month' },
  { label: '近7天', value: '7d' },
  { label: '近30天', value: '30d' },
  { label: '近一年', value: '1y' }
]

const hasData = (data: any[]) => {
  return data && data.length > 0
}

const selectRange = (value: string) => {
  selectedRange.value = value
  const end = new Date()
  const start = new Date()
  
  if (value === 'today') {
    start.setHours(0, 0, 0, 0)
    end.setHours(23, 59, 59, 999)
  } else if (value === 'week') {
    const day = start.getDay() || 7 // Get current day number, make Sunday 7
    if (day !== 1) start.setHours(-24 * (day - 1)) // Set to Monday
    else start.setHours(0,0,0,0)
  } else if (value === 'month') {
    start.setDate(1)
    start.setHours(0,0,0,0)
  } else if (value === '7d') {
    start.setDate(end.getDate() - 6)
  } else if (value === '30d') {
    start.setDate(end.getDate() - 29)
  } else if (value === '1y') {
    start.setFullYear(end.getFullYear() - 1)
  }
  
  startDateTime.value = formatDateTime(start)
  endDateTime.value = formatDateTime(end)
  dateError.value = ''
  loadData()
}

const formatDateTime = (date: Date) => {
  // YYYY-MM-DDTHH:mm
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day}T${hours}:${minutes}`
}

const validateDates = () => {
  if (startDateTime.value && endDateTime.value) {
    if (new Date(startDateTime.value) > new Date(endDateTime.value)) {
      dateError.value = '开始时间不能晚于结束时间'
      return false
    }
  }
  dateError.value = ''
  return true
}

const clearDates = () => {
  startDateTime.value = ''
  endDateTime.value = ''
  selectedRange.value = ''
  loadData()
}

const handleSearch = () => {
  if (validateDates()) {
    selectedRange.value = '' // Clear preset selection when manual search
    loadData()
  }
}

// Chart Options
const postsTrendOption = computed(() => ({
  tooltip: { 
    trigger: 'axis',
    backgroundColor: 'rgba(0,0,0,0.8)',
    borderColor: '#333',
    textStyle: { color: '#fff' },
    formatter: function(params: any) {
      let result = params[0].name + '<br/>';
      params.forEach((item: any) => {
        result += item.marker + item.seriesName + ': ' + item.value + ' 篇<br/>';
        // if (data.yoy) result += '同比: ' + data.yoy + '%<br/>';
        // if (data.mom) result += '环比: ' + data.mom + '%<br/>';
      });
      return result;
    }
  },
  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
  xAxis: {
    type: 'category',
    data: stats.value.postsTrend?.map((i: any) => i.date) || [],
    axisLabel: { color: '#ccc' }
  },
  yAxis: {
    type: 'value',
    axisLabel: { color: '#ccc' },
    splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
  },
  series: [{
    name: '新增文章',
    data: stats.value.postsTrend?.map((i: any) => i.value) || [],
    type: 'line',
    smooth: true,
    itemStyle: { color: '#3b82f6' },
    areaStyle: { color: 'rgba(59, 130, 246, 0.1)' }
  }]
}))

const uvTrendOption = computed(() => ({
  tooltip: { 
    trigger: 'axis',
    backgroundColor: 'rgba(0,0,0,0.8)',
    borderColor: '#333',
    textStyle: { color: '#fff' }
  },
  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
  xAxis: {
    type: 'category',
    data: stats.value.uvTrend?.map((i: any) => i.date) || [],
    axisLabel: { color: '#ccc' }
  },
  yAxis: {
    type: 'value',
    axisLabel: { color: '#ccc' },
    splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
  },
  series: [{
    name: '访客数 (UV)',
    data: stats.value.uvTrend?.map((i: any) => i.value) || [],
    type: 'bar',
    itemStyle: { color: '#10b981' },
    barWidth: '40%'
  }]
}))

// 所有省份完整名称列表（用于匹配地图数据）
const allProvincesFullNames = [
  '北京市', '天津市', '河北省', '山西省', '内蒙古自治区', '辽宁省', '吉林省', '黑龙江省',
  '上海市', '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省', '河南省',
  '湖北省', '湖南省', '广东省', '广西壮族自治区', '海南省', '重庆市', '四川省', '贵州省',
  '云南省', '西藏自治区', '陕西省', '甘肃省', '青海省', '宁夏回族自治区', '新疆维吾尔自治区', '台湾省', '香港特别行政区', '澳门特别行政区'
]

// 将数据转换为地图需要的格式，没有值的省份默认为0
const getMapData = () => {
  // 创建省份数据映射
  const dataMap = new Map<string, number>()
  
  // 如果有数据，先填充实际数据
  // 后端现在直接返回完整的省份名称（如"浙江省"、"北京市"等）
  if (stats.value.userRegions && stats.value.userRegions.length > 0) {
    stats.value.userRegions.forEach((item: any) => {
      // 后端返回的字段名是 Region 和 Count（首字母大写）
      const provinceName = item.Region || item.region
      const count = Number(item.Count || item.count || 0)
      
      if (!provinceName) {
        console.warn('Missing province name in item:', item)
        return
      }
      
      // 直接使用后端返回的完整省份名称，不需要任何处理
      dataMap.set(provinceName, count)
      console.log(`Set province data: ${provinceName} = ${count}`)
    })
  }
  
  // 为所有省份生成数据，没有值的默认为0
  // ECharts map 类型需要对象数组格式: [{name: '浙江省', value: 1}]
  const result = allProvincesFullNames.map(province => {
    const count = dataMap.get(province) ?? 0
    return {
      name: province,
      value: count
    }
  })
  
  console.log('Map data result:', result)
  return result
}

const regionOption = computed(() => {
  // 如果地图数据未加载，返回空配置
  if (!mapDataLoaded.value) {
    return {
      title: {
        text: '地图数据加载中...',
        left: 'center',
        top: 'middle',
        textStyle: {
          color: '#fff'
        }
      }
    }
  }

  const mapData = getMapData()
  // 计算最大值，支持对象格式 {name, value} 和数组格式 [name, value]
  const maxValue = mapData.length > 0 ? Math.max(...mapData.map((d: any) => {
    if (typeof d === 'object' && 'value' in d) {
      return d.value || 0
    } else if (Array.isArray(d)) {
      return d[1] || 0
    }
    return 0
  })) : 1
  
  return {
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0,0,0,0.8)',
      borderColor: '#333',
      textStyle: { color: '#fff' },
      formatter: (params: any) => {
        const value = params.value ? (Array.isArray(params.value) ? params.value[1] : params.value) : 0
        return `${params.name}<br/>访问量: ${value}`
      }
    },
    visualMap: {
      min: 0,
      max: maxValue || 100,
      left: 'left',
      top: 'middle',
      text: ['高', '低'],
      inRange: {
        color: ['#1a1a1a', '#d4b383']
      },
      textStyle: {
        color: '#fff'
      },
      calculable: true,
      itemWidth: 12,
      itemHeight: 200
    },
    geo: {
      map: 'china',
      roam: false,
      layoutCenter: ['55%', '50%'],
      layoutSize: '95%',
      itemStyle: {
        areaColor: 'rgba(255, 255, 255, 0.05)',
        borderColor: 'rgba(255, 255, 255, 0.2)',
        borderWidth: 1
      },
      emphasis: {
        itemStyle: {
          areaColor: 'rgba(212, 179, 131, 0.3)'
        }
      },
      label: {
        show: true,
        color: 'rgba(255, 255, 255, 0.8)',
        fontSize: 14
      }
    },
    series: [
      {
        name: '访问量',
        type: 'map',
        map: 'china',
        geoIndex: 0,
        data: mapData,
        itemStyle: {
          areaColor: 'rgba(255, 255, 255, 0.05)',
          borderColor: 'rgba(255, 255, 255, 0.2)',
          borderWidth: 1
        },
        emphasis: {
          itemStyle: {
            areaColor: 'rgba(212, 179, 131, 0.5)',
            borderColor: '#d4b383',
            borderWidth: 2
          },
          label: {
            color: '#fff',
            fontSize: 16
          }
        }
      }
    ]
  }
})

const operationTrendOption = computed(() => ({
  tooltip: { 
    trigger: 'axis',
    backgroundColor: 'rgba(0,0,0,0.8)',
    borderColor: '#333',
    textStyle: { color: '#fff' }
  },
  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
  xAxis: {
    type: 'category',
    data: stats.value.operationTrend?.map((i: any) => i.date) || [],
    axisLabel: { color: '#ccc' }
  },
  yAxis: {
    type: 'value',
    axisLabel: { color: '#ccc' },
    splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
  },
  series: [{
    name: '操作次数',
    data: stats.value.operationTrend?.map((i: any) => i.value) || [],
    type: 'bar',
    itemStyle: { color: '#f59e0b' },
    barWidth: '40%'
  }]
}))

const topPostsOption = computed(() => ({
  tooltip: { 
    trigger: 'axis', 
    axisPointer: { type: 'shadow' },
    backgroundColor: 'rgba(0,0,0,0.8)',
    borderColor: '#333',
    textStyle: { color: '#fff' }
  },
  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
  xAxis: {
    type: 'value',
    axisLabel: { color: '#ccc' },
    splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
  },
  yAxis: {
    type: 'category',
    inverse: true,
    data: stats.value.topPosts?.map((i: any) => i.title.length > 10 ? i.title.substring(0, 10) + '...' : i.title) || [],
    axisLabel: { color: '#ccc' }
  },
  series: [
    {
      name: '阅读量',
      type: 'bar',
      data: stats.value.topPosts?.map((i: any) => i.count) || [],
      itemStyle: { color: '#d4b383' }
    }
  ]
}))

const loadData = async () => {
  loading.value = true
  try {
    // Convert datetime-local format to API expected format if needed
    // Assuming API accepts YYYY-MM-DD or YYYY-MM-DD HH:mm:ss
    const start = startDateTime.value.replace('T', ' ')
    const end = endDateTime.value.replace('T', ' ')
    stats.value = await getDashboardStats(start, end)
  } catch (error) {
    console.error(error)
    toast.showToast('加载数据失败', 'error')
  } finally {
    loading.value = false
  }
}

// 地图数据加载状态
const mapDataLoaded = ref(false)

// 加载中国地图数据
const loadChinaMap = async () => {
  try {
    // 优先使用本地地图数据
    if (chinaMapData && chinaMapData.type === 'FeatureCollection') {
      echarts.registerMap('china', chinaMapData as any)
      mapDataLoaded.value = true
      console.log('China map data loaded successfully from local file')
      return
    }
  } catch (error) {
    console.warn('Failed to load local map data:', error)
  }

  // 如果本地数据加载失败，尝试备用数据源
  const mapDataSources = [
    'https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json',
    'https://cdn.jsdelivr.net/npm/echarts@5/map/json/china.json',
    'https://unpkg.com/echarts@5/map/json/china.json'
  ]

  for (const url of mapDataSources) {
    try {
      const controller = new AbortController()
      const timeoutId = setTimeout(() => controller.abort(), 10000) // 10秒超时
      
      const response = await fetch(url, {
        mode: 'cors',
        credentials: 'omit',
        signal: controller.signal
      })
      
      clearTimeout(timeoutId)
      
      if (response.ok) {
        const geoJson = await response.json()
        // 验证数据格式
        if (geoJson && geoJson.type === 'FeatureCollection') {
          // 注册地图数据
          echarts.registerMap('china', geoJson)
          mapDataLoaded.value = true
          console.log('China map data loaded successfully from:', url)
          return
        } else {
          console.warn(`Invalid map data format from ${url}`)
        }
      }
    } catch (error: any) {
      if (error.name === 'AbortError') {
        console.warn(`Timeout loading map data from ${url}`)
      } else {
        console.warn(`Failed to load map data from ${url}:`, error)
      }
      continue
    }
  }
  
  // 所有数据源都失败
  console.error('All map data sources failed, map will not be displayed')
  mapDataLoaded.value = false
}

onMounted(async () => {
  // 加载地图数据
  await loadChinaMap()
  // Default to 7 days
  selectRange('7d')
})
</script>

<style scoped>
.analytics-page {
  width: 100%;
}

.chart-card {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 0.75rem;
  padding: 1.5rem;
}

.chart-title {
  font-size: 1.1rem;
  color: #d4b383;
  margin: 0 0 1rem 0;
  font-weight: 500;
}

.chart {
  height: 100%;
  width: 100%;
}
</style>
