<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900">
    <!-- 顶部导航栏 -->
    <nav class="bg-white dark:bg-gray-800 shadow-sm">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex items-center">
            <h1 class="text-xl font-bold text-gray-800 dark:text-white">数据分析</h1>
          </div>
          <div class="flex items-center space-x-4">
            <button 
              @click="refreshData"
              class="p-2 rounded-full text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
            >
              <RefreshCwIcon class="h-6 w-6" />
            </button>
            <div class="relative">
              <button 
                @click="exportData"
                class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 flex items-center space-x-2"
              >
                <DownloadIcon class="h-5 w-5" />
                <span>导出</span>
              </button>
              <select 
                v-model="exportFormat"
                class="absolute right-0 mt-1 w-32 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md shadow-lg py-1 px-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="csv">CSV</option>
                <option value="excel">Excel</option>
                <option value="json">JSON</option>
              </select>
            </div>
            <button 
              @click="shareData"
              class="p-2 rounded-full text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
            >
              <Share2Icon class="h-6 w-6" />
            </button>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主要内容区域 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 时间范围选择 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8">
        <div class="flex flex-wrap gap-4">
          <div class="flex items-center space-x-2">
            <label class="text-sm font-medium text-gray-700 dark:text-gray-300">时间范围：</label>
            <select 
              v-model="timeRange"
              class="border border-gray-300 dark:border-gray-600 rounded-md px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            >
              <option value="today">今天</option>
              <option value="week">本周</option>
              <option value="month">本月</option>
              <option value="quarter">本季度</option>
              <option value="year">本年</option>
            </select>
          </div>
          <div class="flex items-center space-x-2">
            <label class="text-sm font-medium text-gray-700 dark:text-gray-300">对比：</label>
            <select 
              v-model="comparison"
              class="border border-gray-300 dark:border-gray-600 rounded-md px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            >
              <option value="none">不对比</option>
              <option value="last_period">上期</option>
              <option value="last_year">去年同期</option>
            </select>
          </div>
          <div class="flex items-center space-x-2">
            <label class="text-sm font-medium text-gray-700 dark:text-gray-300">指标：</label>
            <div class="flex flex-wrap gap-2">
              <label class="inline-flex items-center">
                <input type="checkbox" v-model="selectedMetrics" value="sales" class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50">
                <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">销售额</span>
              </label>
              <label class="inline-flex items-center">
                <input type="checkbox" v-model="selectedMetrics" value="orders" class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50">
                <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">订单数</span>
              </label>
              <label class="inline-flex items-center">
                <input type="checkbox" v-model="selectedMetrics" value="visitors" class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50">
                <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">访客数</span>
              </label>
              <label class="inline-flex items-center">
                <input type="checkbox" v-model="selectedMetrics" value="conversion" class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50">
                <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">转化率</span>
              </label>
            </div>
          </div>
          <div class="flex items-center space-x-2">
            <label class="text-sm font-medium text-gray-700 dark:text-gray-300">预测：</label>
            <button 
              @click="showPrediction = !showPrediction"
              class="px-4 py-2 rounded-md flex items-center space-x-2"
              :class="showPrediction ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'"
            >
              <TrendingUpIcon class="h-5 w-5" />
              <span>{{ showPrediction ? '隐藏预测' : '显示预测' }}</span>
            </button>
          </div>
        </div>
      </div>

      <!-- 图表控制栏 -->
      <div class="mb-6 flex flex-wrap items-center justify-between gap-4">
        <div class="flex items-center space-x-4">
          <button 
            @click="updateChartType('line')"
            class="p-2 rounded-md"
            :class="chartType === 'line' ? 'bg-blue-100 dark:bg-blue-900' : 'hover:bg-gray-100 dark:hover:bg-gray-700'"
          >
            <LineChartIcon class="h-6 w-6" />
          </button>
          <button 
            @click="updateChartType('bar')"
            class="p-2 rounded-md"
            :class="chartType === 'bar' ? 'bg-blue-100 dark:bg-blue-900' : 'hover:bg-gray-100 dark:hover:bg-gray-700'"
          >
            <BarChartIcon class="h-6 w-6" />
          </button>
          <button 
            @click="updateChartType('pie')"
            class="p-2 rounded-md"
            :class="chartType === 'pie' ? 'bg-blue-100 dark:bg-blue-900' : 'hover:bg-gray-100 dark:hover:bg-gray-700'"
          >
            <PieChartIcon class="h-6 w-6" />
          </button>
        </div>
        <div class="flex items-center space-x-4">
          <button 
            @click="compareData"
            class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
          >
            数据对比
          </button>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
        <div ref="chartRef" class="h-96"></div>
      </div>

      <!-- 关键指标卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="p-3 rounded-full bg-blue-100">
              <DollarSignIcon class="h-6 w-6 text-blue-600" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600">总销售额</p>
              <p class="text-2xl font-semibold text-gray-900">¥123,456</p>
              <p class="text-sm text-green-600">↑ 12.5%</p>
            </div>
          </div>
        </div>
        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="p-3 rounded-full bg-green-100">
              <ShoppingCartIcon class="h-6 w-6 text-green-600" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600">订单数量</p>
              <p class="text-2xl font-semibold text-gray-900">1,234</p>
              <p class="text-sm text-green-600">↑ 8.3%</p>
            </div>
          </div>
        </div>
        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="p-3 rounded-full bg-yellow-100">
              <UsersIcon class="h-6 w-6 text-yellow-600" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600">访客数</p>
              <p class="text-2xl font-semibold text-gray-900">5,678</p>
              <p class="text-sm text-green-600">↑ 15.2%</p>
            </div>
          </div>
        </div>
        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="p-3 rounded-full bg-purple-100">
              <PercentIcon class="h-6 w-6 text-purple-600" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600">转化率</p>
              <p class="text-2xl font-semibold text-gray-900">21.7%</p>
              <p class="text-sm text-green-600">↑ 2.3%</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
          <h2 class="text-lg font-medium text-gray-900 dark:text-white">详细数据</h2>
          <div class="flex items-center space-x-4">
            <div class="relative">
              <input
                v-model="filterText"
                type="text"
                placeholder="搜索..."
                class="border border-gray-300 dark:border-gray-600 rounded-md px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              >
              <FilterIcon class="absolute right-3 top-2.5 h-5 w-5 text-gray-400" />
            </div>
          </div>
        </div>
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
            <thead class="bg-gray-50 dark:bg-gray-700">
              <tr>
                <th 
                  v-for="(header, index) in ['日期', '销售额', '订单数', '访客数', '转化率', '客单价']"
                  :key="index"
                  class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-600"
                  @click="toggleSort(['date', 'sales', 'orders', 'visitors', 'conversion', 'avgPrice'][index])"
                >
                  <div class="flex items-center space-x-1">
                    <span>{{ header }}</span>
                    <component 
                      :is="getSortIcon(['date', 'sales', 'orders', 'visitors', 'conversion', 'avgPrice'][index])"
                      v-if="getSortIcon(['date', 'sales', 'orders', 'visitors', 'conversion', 'avgPrice'][index])"
                      class="h-4 w-4"
                    />
                  </div>
                </th>
              </tr>
            </thead>
            <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
              <tr 
                v-for="item in filteredData" 
                :key="item.date"
                class="hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer"
                :class="{ 'bg-blue-50 dark:bg-blue-900': selectedDate === item.date }"
                @click="handleDateSelect(item.date)"
              >
                <td class="px-6 py-4 text-sm text-gray-900 dark:text-white">{{ item.date }}</td>
                <td class="px-6 py-4 text-sm text-gray-900 dark:text-white">¥{{ item.sales }}</td>
                <td class="px-6 py-4 text-sm text-gray-900 dark:text-white">{{ item.orders }}</td>
                <td class="px-6 py-4 text-sm text-gray-900 dark:text-white">{{ item.visitors }}</td>
                <td class="px-6 py-4 text-sm text-gray-900 dark:text-white">{{ item.conversion }}%</td>
                <td class="px-6 py-4 text-sm text-gray-900 dark:text-white">¥{{ item.avgPrice }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import { 
  RefreshCwIcon, 
  DownloadIcon, 
  Share2Icon,
  LineChartIcon,
  BarChartIcon,
  PieChartIcon,
  DollarSignIcon,
  ShoppingCartIcon,
  UsersIcon,
  PercentIcon,
  FilterIcon,
  ArrowUpIcon,
  ArrowDownIcon,
  ChevronUpIcon,
  ChevronDownIcon,
  TrendingUpIcon,
  TrendingDownIcon,
  AlertCircleIcon,
  CameraIcon,
  ClockIcon,
  XIcon,
  BrainIcon,
  LinkIcon,
  EyeIcon,
  FileSpreadsheetIcon,
  LayersIcon,
  FileTextIcon,
  LightbulbIcon,
  BookOpenIcon,
  SparklesIcon,
  CompassIcon,
  ActivityIcon
} from 'lucide-vue-next'

// 状态管理
const timeRange = ref('week')
const comparison = ref('none')
const selectedMetrics = ref(['sales', 'orders'])
const showPrediction = ref(false)
const chartType = ref('line')
const exportFormat = ref('csv')
const filterText = ref('')
const sortField = ref('date')
const sortOrder = ref('asc')
const selectedDate = ref(null)

// 图表相关
const chartRef = ref(null)
let chartInstance = null

// Mock data
const mockData = ref([
  { date: '2024-03-01', sales: 12345, orders: 123, visitors: 567, conversion: 21.7, avgPrice: 100.37 },
  { date: '2024-03-02', sales: 13456, orders: 134, visitors: 589, conversion: 22.7, avgPrice: 100.42 },
  { date: '2024-03-03', sales: 14567, orders: 145, visitors: 612, conversion: 23.7, avgPrice: 100.46 },
  { date: '2024-03-04', sales: 15678, orders: 156, visitors: 634, conversion: 24.6, avgPrice: 100.50 },
  { date: '2024-03-05', sales: 16789, orders: 167, visitors: 657, conversion: 25.4, avgPrice: 100.53 },
  { date: '2024-03-06', sales: 17890, orders: 178, visitors: 679, conversion: 26.2, avgPrice: 100.51 },
  { date: '2024-03-07', sales: 18901, orders: 189, visitors: 702, conversion: 26.9, avgPrice: 100.01 }
])

// 计算属性
const filteredData = computed(() => {
  let result = [...mockData.value]
  
  // 过滤
  if (filterText.value) {
    result = result.filter(item => 
      item.date.includes(filterText.value) ||
      item.sales.toString().includes(filterText.value) ||
      item.orders.toString().includes(filterText.value) ||
      item.visitors.toString().includes(filterText.value) ||
      item.conversion.toString().includes(filterText.value) ||
      item.avgPrice.toString().includes(filterText.value)
    )
  }
  
  // 排序
  if (sortField.value) {
    result.sort((a, b) => {
      const aValue = a[sortField.value]
      const bValue = b[sortField.value]
      return sortOrder.value === 'asc' ? aValue - bValue : bValue - aValue
    })
  }
  
  return result
})

// 方法
const refreshData = () => {
  // 模拟刷新数据
  updateChart()
}

const exportData = () => {
  // 模拟导出数据
  console.log('导出数据:', exportFormat.value)
}

const shareData = () => {
  // 模拟分享数据
  console.log('分享数据')
}

const compareData = () => {
  // 模拟数据对比
  console.log('数据对比')
}

const toggleSort = (field) => {
  if (sortField.value === field) {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortField.value = field
    sortOrder.value = 'asc'
  }
}

const getSortIcon = (field) => {
  if (sortField.value !== field) return null
  return sortOrder.value === 'asc' ? ChevronUpIcon : ChevronDownIcon
}

const handleDateSelect = (date) => {
  selectedDate.value = selectedDate.value === date ? null : date
}

// 初始化图表
const initChart = () => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  chartInstance = echarts.init(chartRef.value)
  updateChart()
}

// 更新图表
const updateChart = () => {
  if (!chartInstance) return

  const options = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['销售额', '订单数', '访客数', '转化率']
    },
    xAxis: {
      type: 'category',
      data: mockData.value.map(item => item.date)
    },
    yAxis: [
      {
        type: 'value',
        name: '金额/数量'
      },
      {
        type: 'value',
        name: '转化率',
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '销售额',
        type: chartType.value,
        data: mockData.value.map(item => item.sales)
      },
      {
        name: '订单数',
        type: chartType.value,
        data: mockData.value.map(item => item.orders)
      },
      {
        name: '访客数',
        type: chartType.value,
        data: mockData.value.map(item => item.visitors)
      },
      {
        name: '转化率',
        type: chartType.value,
        yAxisIndex: 1,
        data: mockData.value.map(item => item.conversion)
      }
    ]
  }

  if (chartType.value === 'pie') {
    options.series = [{
      type: 'pie',
      radius: '50%',
      data: [
        { value: mockData.value[mockData.value.length - 1].sales, name: '销售额' },
        { value: mockData.value[mockData.value.length - 1].orders, name: '订单数' },
        { value: mockData.value[mockData.value.length - 1].visitors, name: '访客数' },
        { value: mockData.value[mockData.value.length - 1].conversion, name: '转化率' }
      ]
    }]
  }

  chartInstance.setOption(options)
}

// 更新图表类型
const updateChartType = (type) => {
  chartType.value = type
  updateChart()
}

// 监听窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 生命周期钩子
onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (chartInstance) {
    chartInstance.dispose()
  }
})

// 监听数据变化
watch([timeRange, comparison, selectedMetrics, showPrediction], () => {
  updateChart()
})
</script>

<style scoped>
/* 响应式布局 */
@media (max-width: 475px) {
  .grid {
    @apply grid-cols-1;
  }
  table {
    @apply block overflow-x-auto whitespace-nowrap;
  }
}

/* 图表缩放动画 */
.chart-container {
  @apply transition-transform duration-300 ease-in-out;
}

/* 数据钻取动画 */
.drill-down {
  @apply animate-[drillDown_0.3s_ease];
}

@keyframes drillDown {
  from {
    @apply scale-95 opacity-0;
  }
  to {
    @apply scale-100 opacity-100;
  }
}

/* 预警动画 */
@keyframes pulse {
  0% {
    @apply scale-100;
  }
  50% {
    @apply scale-105;
  }
  100% {
    @apply scale-100;
  }
}

.alert-pulse {
  @apply animate-[pulse_2s_infinite];
}

/* 注释样式 */
.comment-bubble {
  @apply relative bg-gray-100 rounded-lg p-2 mt-2;
}

.comment-bubble::before {
  content: '';
  @apply absolute -top-2 left-4 border-2 border-transparent border-b-gray-100;
}

/* 趋势分析动画 */
@keyframes trendUp {
  from {
    @apply translate-y-2.5 opacity-0;
  }
  to {
    @apply translate-y-0 opacity-100;
  }
}

.trend-up {
  @apply animate-[trendUp_0.3s_ease-out];
}

@keyframes trendDown {
  from {
    @apply -translate-y-2.5 opacity-0;
  }
  to {
    @apply translate-y-0 opacity-100;
  }
}

.trend-down {
  @apply animate-[trendDown_0.3s_ease-out];
}

/* 异常检测样式 */
.anomaly-high {
  @apply border-l-4 border-red-500;
}

.anomaly-low {
  @apply border-l-4 border-yellow-500;
}

/* 快照样式 */
.snapshot-card {
  @apply transition-transform duration-200 ease-in-out;
}

.snapshot-card:hover {
  @apply -translate-y-0.5;
}

/* 预测模型样式 */
.prediction-error {
  @apply transition-colors duration-300 ease-in-out;
}

/* 关联分析样式 */
.correlation-cell {
  @apply transition-all duration-200 ease-in-out;
}

.correlation-cell:hover {
  @apply scale-105;
}

/* 可视化设置样式 */
.setting-item {
  @apply transition-all duration-200 ease-in-out;
}

.setting-item:hover {
  @apply bg-black/5;
}

/* 导出模板样式 */
.template-card {
  @apply transition-all duration-200 ease-in-out;
}

.template-card:hover {
  @apply -translate-y-0.5;
}

/* 聚类分析样式 */
.cluster-card {
  @apply transition-transform duration-200 ease-in-out;
}

.cluster-card:hover {
  @apply -translate-y-0.5;
}

/* 时间序列分析样式 */
.time-series-card {
  @apply transition-all duration-200 ease-in-out;
}

.time-series-card:hover {
  @apply bg-black/5;
}

/* 报告生成样式 */
.report-template {
  @apply transition-all duration-200 ease-in-out;
}

.report-template:hover {
  @apply translate-x-1;
}

/* 数据洞察样式 */
.insight-card {
  @apply transition-transform duration-200 ease-in-out;
}

.insight-card:hover {
  @apply -translate-y-0.5;
}

/* 数据故事样式 */
.story-section {
  @apply transition-all duration-200 ease-in-out;
}

.story-section:hover {
  @apply bg-black/5;
}

/* 协作样式 */
.collaborator-card {
  @apply transition-all duration-200 ease-in-out;
}

.collaborator-card:hover {
  @apply bg-black/5;
}

.comment-card {
  @apply transition-all duration-200 ease-in-out;
}

.comment-card:hover {
  @apply translate-x-1;
}

/* 智能推荐样式 */
.recommendation-card {
  @apply transition-transform duration-200 ease-in-out;
}

.recommendation-card:hover {
  @apply -translate-y-0.5;
}

/* 数据探索样式 */
.exploration-card {
  @apply transition-all duration-200 ease-in-out;
}

.exploration-card:hover {
  @apply bg-black/5;
}

/* 监控面板样式 */
.monitoring-card {
  @apply transition-all duration-200 ease-in-out;
}

.monitoring-card:hover {
  @apply scale-105;
}

.alert-card {
  @apply transition-all duration-200 ease-in-out;
}

.alert-card:hover {
  @apply translate-x-1;
}
</style> 