<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="handleExportReport"
              class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 flex items-center space-x-2"
            >
              <DownloadIcon class="h-5 w-5" />
              <span>导出报表</span>
            </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="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div class="relative">
            <input
              v-model="searchText"
              @input="handleSearch"
              type="text"
              placeholder="搜索产品名称/ID..."
              class="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            />
            <SearchIcon class="absolute left-3 top-2.5 h-5 w-5 text-gray-400 dark:text-gray-500" />
          </div>
          <select 
            v-model="category"
            @change="handleCategoryChange"
            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="">所有类别</option>
            <option value="electronics">电子产品</option>
            <option value="clothing">服装</option>
            <option value="food">食品</option>
            <option value="books">图书</option>
          </select>
          <select 
            v-model="status"
            @change="handleStatusChange"
            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="">所有状态</option>
            <option value="in_stock">在售</option>
            <option value="out_of_stock">缺货</option>
            <option value="discontinued">已下架</option>
          </select>
          <select 
            v-model="timeRange"
            @change="handleTimeRangeChange"
            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="">所有时间</option>
            <option value="today">今天</option>
            <option value="week">本周</option>
            <option value="month">本月</option>
            <option value="quarter">本季度</option>
          </select>
        </div>
      </div>

      <!-- 产品统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="p-3 rounded-full bg-blue-100 dark:bg-blue-900">
              <PackageIcon class="h-6 w-6 text-blue-600 dark:text-blue-400" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600 dark:text-gray-400">总产品数</p>
              <p class="text-2xl font-semibold text-gray-900 dark:text-white">1,234</p>
            </div>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="p-3 rounded-full bg-green-100 dark:bg-green-900">
              <ShoppingCartIcon class="h-6 w-6 text-green-600 dark:text-green-400" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600 dark:text-gray-400">总销量</p>
              <p class="text-2xl font-semibold text-gray-900 dark:text-white">56,789</p>
            </div>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="p-3 rounded-full bg-yellow-100 dark:bg-yellow-900">
              <DollarSignIcon class="h-6 w-6 text-yellow-600 dark:text-yellow-400" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600 dark:text-gray-400">总销售额</p>
              <p class="text-2xl font-semibold text-gray-900 dark:text-white">¥1,234,567</p>
            </div>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="p-3 rounded-full bg-purple-100 dark:bg-purple-900">
              <StarIcon class="h-6 w-6 text-purple-600 dark:text-purple-400" />
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600 dark:text-gray-400">平均评分</p>
              <p class="text-2xl font-semibold text-gray-900 dark:text-white">4.8</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 产品分析图表 -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">产品销量趋势</h3>
          <div ref="trendChartRef" class="h-64"></div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">产品类别分布</h3>
          <div ref="categoryChartRef" class="h-64"></div>
        </div>
      </div>

      <!-- 产品列表 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        <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 class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">产品信息</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">类别</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">价格</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">库存</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">状态</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
              <tr v-for="product in paginatedProducts" :key="product.id" class="hover:bg-gray-50 dark:hover:bg-gray-700">
                <td class="px-6 py-4">
                  <div class="flex items-center">
                    <div class="flex-shrink-0 h-10 w-10">
                      <img class="h-10 w-10 rounded-full object-cover" :src="product.image" :alt="product.name">
                    </div>
                    <div class="ml-4">
                      <div class="text-sm font-medium text-gray-900 dark:text-white">{{ product.name }}</div>
                      <div class="text-sm text-gray-500 dark:text-gray-400">{{ product.description }}</div>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4">
                  <span :class="['category-tag', `category-${product.category}`]">
                    {{ product.category === 'electronics' ? '电子产品' : 
                       product.category === 'clothing' ? '服装' : 
                       product.category === 'food' ? '食品' : '图书' }}
                  </span>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-900 dark:text-white">¥{{ product.price }}</div>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-900 dark:text-white">{{ product.stock }}</div>
                </td>
                <td class="px-6 py-4">
                  <span :class="['status-tag', `status-${product.status}`]">
                    {{ product.status === 'in_stock' ? '在售' : 
                       product.status === 'out_of_stock' ? '缺货' : '已下架' }}
                  </span>
                </td>
                <td class="px-6 py-4 text-sm font-medium">
                  <button 
                    @click="handleViewProduct(product)"
                    class="action-button view-button"
                  >
                    <EyeIcon class="h-4 w-4 inline-block mr-1" />
                    查看
                  </button>
                  <button 
                    @click="handleEditProduct(product)"
                    class="action-button edit-button"
                  >
                    <EditIcon class="h-4 w-4 inline-block mr-1" />
                    编辑
                  </button>
                  <button 
                    @click="handleDeleteProduct(product)"
                    class="action-button delete-button"
                  >
                    <TrashIcon class="h-4 w-4 inline-block mr-1" />
                    删除
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 分页 -->
      <div class="bg-white dark:bg-gray-800 px-4 py-3 flex items-center justify-between border-t border-gray-200 dark:border-gray-700 sm:px-6 mt-4">
        <div class="flex-1 flex justify-between sm:hidden">
          <button 
            @click="handlePageChange(currentPage - 1)"
            :disabled="currentPage === 1"
            class="pagination-button"
          >
            上一页
          </button>
          <button 
            @click="handlePageChange(currentPage + 1)"
            :disabled="currentPage === totalPages"
            class="pagination-button"
          >
            下一页
          </button>
        </div>
        <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
          <div>
            <p class="text-sm text-gray-700 dark:text-gray-300">
              显示 <span class="font-medium">{{ (currentPage - 1) * pageSize + 1 }}</span> 到 
              <span class="font-medium">{{ Math.min(currentPage * pageSize, filteredProducts.length) }}</span> 条，共 
              <span class="font-medium">{{ filteredProducts.length }}</span> 条
            </p>
          </div>
          <div>
            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
              <button 
                @click="handlePageChange(currentPage - 1)"
                :disabled="currentPage === 1"
                class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-600"
              >
                <ChevronLeftIcon class="h-5 w-5" />
              </button>
              <button 
                v-for="page in totalPages"
                :key="page"
                @click="handlePageChange(page)"
                :class="[
                  'relative inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 text-sm font-medium',
                  currentPage === page ? 'bg-blue-600 text-white border-blue-600' : 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600'
                ]"
              >
                {{ page }}
              </button>
              <button 
                @click="handlePageChange(currentPage + 1)"
                :disabled="currentPage === totalPages"
                class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-600"
              >
                <ChevronRightIcon class="h-5 w-5" />
              </button>
            </nav>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { 
  LineChart,
  BarChart,
  PieChart,
  ScatterChart
} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { 
  SearchIcon, 
  DownloadIcon, 
  EyeIcon,
  EditIcon,
  TrashIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
  PackageIcon,
  ShoppingCartIcon,
  DollarSignIcon,
  StarIcon
} from 'lucide-vue-next'

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  LineChart,
  BarChart,
  PieChart,
  ScatterChart,
  CanvasRenderer
])

// 状态管理
const isLoading = ref(false)
const searchText = ref('')
const category = ref('')
const status = ref('')
const timeRange = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalProducts = ref(100)

// 图表相关
const trendChartRef = ref(null)
const categoryChartRef = ref(null)
let trendChart = null
let categoryChart = null

// 默认图片配置
const defaultImages = {
  product: 'https://ui-avatars.com/api/?name=Product&background=random&color=fff&size=150'
}

// Mock data
const mockProducts = ref([
  {
    id: 'P1001',
    name: '智能手表 Pro',
    category: '电子产品',
    price: 1999,
    stock: 150,
    sales: 1200,
    status: 'in_stock',
    image: defaultImages.product,
    description: '最新款智能手表，支持心率监测和运动追踪',
    createdAt: '2024-01-15 10:00:00',
    updatedAt: '2024-03-20 15:30:00'
  },
  {
    id: 'P1002',
    name: '无线耳机 Air',
    category: '电子产品',
    price: 999,
    stock: 200,
    sales: 800,
    status: 'in_stock',
    image: defaultImages.product,
    description: '真无线蓝牙耳机，支持主动降噪',
    createdAt: '2024-02-01 09:00:00',
    updatedAt: '2024-03-19 14:20:00'
  },
  {
    id: 'P1003',
    name: '智能音箱 Mini',
    category: '电子产品',
    price: 299,
    stock: 50,
    sales: 1500,
    status: 'low_stock',
    image: defaultImages.product,
    description: '便携式智能音箱，支持语音助手',
    createdAt: '2024-01-20 11:00:00',
    updatedAt: '2024-03-18 16:45:00'
  },
  {
    id: 'P1004',
    name: '运动相机 4K',
    category: '电子产品',
    price: 2499,
    stock: 0,
    sales: 500,
    status: 'out_of_stock',
    image: defaultImages.product,
    description: '4K高清运动相机，防水防抖',
    createdAt: '2024-02-15 14:00:00',
    updatedAt: '2024-03-17 10:30:00'
  },
  {
    id: 'P1005',
    name: '智能门锁 Pro',
    category: '智能家居',
    price: 1299,
    stock: 100,
    sales: 300,
    status: 'in_stock',
    image: defaultImages.product,
    description: '指纹识别智能门锁，支持远程控制',
    createdAt: '2024-03-01 09:30:00',
    updatedAt: '2024-03-16 11:15:00'
  }
])

// 产品统计数据
const productStats = ref({
  totalProducts: 1234,
  inStockProducts: 1024,
  outOfStockProducts: 56,
  lowStockProducts: 154
})

// 产品类别分布
const categoryDistribution = ref([
  { category: '电子产品', value: 450 },
  { category: '智能家居', value: 300 },
  { category: '办公用品', value: 250 },
  { category: '生活用品', value: 150 },
  { category: '其他', value: 84 }
])

// 产品销售趋势
const salesTrends = ref([
  { date: '2024-03-01', sales: 120, revenue: 120000 },
  { date: '2024-03-02', sales: 150, revenue: 150000 },
  { date: '2024-03-03', sales: 180, revenue: 180000 },
  { date: '2024-03-04', sales: 200, revenue: 200000 },
  { date: '2024-03-05', sales: 220, revenue: 220000 },
  { date: '2024-03-06', sales: 250, revenue: 250000 },
  { date: '2024-03-07', sales: 280, revenue: 280000 }
])

// 产品库存预警
const stockAlerts = ref([
  {
    id: 'P1003',
    name: '智能音箱 Mini',
    currentStock: 50,
    minStock: 100,
    daysToOutOfStock: 5
  },
  {
    id: 'P1006',
    name: '智能灯泡',
    currentStock: 30,
    minStock: 50,
    daysToOutOfStock: 3
  },
  {
    id: 'P1007',
    name: '智能插座',
    currentStock: 20,
    minStock: 30,
    daysToOutOfStock: 2
  }
])

// 计算属性
const filteredProducts = computed(() => {
  let result = [...mockProducts.value]
  
  // 搜索过滤
  if (searchText.value) {
    result = result.filter(product => 
      product.name.includes(searchText.value) ||
      product.description.includes(searchText.value)
    )
  }
  
  // 类别过滤
  if (category.value) {
    result = result.filter(product => product.category === category.value)
  }
  
  // 状态过滤
  if (status.value) {
    result = result.filter(product => product.status === status.value)
  }
  
  // 时间范围过滤
  if (timeRange.value) {
    const now = new Date()
    result = result.filter(product => {
      // 这里可以根据实际需求添加时间过滤逻辑
      return true
    })
  }
  
  return result
})

const paginatedProducts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredProducts.value.slice(start, end)
})

const totalPages = computed(() => {
  return Math.ceil(filteredProducts.value.length / pageSize.value)
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleCategoryChange = () => {
  currentPage.value = 1
}

const handleStatusChange = () => {
  currentPage.value = 1
}

const handleTimeRangeChange = () => {
  currentPage.value = 1
}

const handlePageChange = (page) => {
  currentPage.value = page
}

const handleViewProduct = (product) => {
  console.log('查看产品:', product)
}

const handleEditProduct = (product) => {
  console.log('编辑产品:', product)
}

const handleDeleteProduct = (product) => {
  console.log('删除产品:', product)
}

const handleExportReport = () => {
  console.log('导出报表')
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  
  trendChart = echarts.init(trendChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['电子产品', '服装', '食品', '图书']
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '电子产品',
        type: 'line',
        data: [1200, 1400, 1800, 2200, 2600, 3000]
      },
      {
        name: '服装',
        type: 'line',
        data: [800, 1000, 1200, 1400, 1600, 1800]
      },
      {
        name: '食品',
        type: 'line',
        data: [1500, 1700, 1900, 2100, 2300, 2500]
      },
      {
        name: '图书',
        type: 'line',
        data: [600, 700, 800, 900, 1000, 1100]
      }
    ]
  }
  trendChart.setOption(option)
}

// 初始化类别图表
const initCategoryChart = () => {
  if (!categoryChartRef.value) return
  
  categoryChart = echarts.init(categoryChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '产品类别',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 40, name: '电子产品' },
          { value: 25, name: '服装' },
          { value: 20, name: '食品' },
          { value: 15, name: '图书' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  categoryChart.setOption(option)
}

// 处理窗口大小变化
const handleResize = () => {
  trendChart?.resize()
  categoryChart?.resize()
}

onMounted(() => {
  initTrendChart()
  initCategoryChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  categoryChart?.dispose()
})
</script>

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

/* 产品类别标签样式 */
.category-tag {
  @apply px-2 inline-flex text-xs leading-5 font-semibold rounded-full;
}

.category-electronics {
  @apply bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-400;
}

.category-clothing {
  @apply bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-400;
}

.category-food {
  @apply bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-400;
}

.category-books {
  @apply bg-purple-100 dark:bg-purple-900 text-purple-800 dark:text-purple-400;
}

/* 产品状态标签样式 */
.status-tag {
  @apply px-2 inline-flex text-xs leading-5 font-semibold rounded-full;
}

.status-in_stock {
  @apply bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-400;
}

.status-out_of_stock {
  @apply bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-400;
}

.status-discontinued {
  @apply bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-400;
}

/* 操作按钮样式 */
.action-button {
  @apply text-sm font-medium mr-3;
}

.view-button {
  @apply text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300;
}

.edit-button {
  @apply text-green-600 dark:text-green-400 hover:text-green-900 dark:hover:text-green-300;
}

.delete-button {
  @apply text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300;
}

/* 分页样式 */
.pagination-button {
  @apply relative inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 text-sm font-medium rounded-md text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600;
}

.pagination-button-active {
  @apply bg-blue-600 text-white border-blue-600;
}

/* 加载动画 */
.loading-spinner {
  @apply animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600;
}
</style> 