<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="搜索商品名称/编号..."
              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="stockStatus"
            @change="handleStockStatusChange"
            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="normal">正常</option>
            <option value="low">库存不足</option>
            <option value="overstock">库存过多</option>
            <option value="out">缺货</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">{{ mockInventory.reduce((sum, item) => sum + item.stock, 0) }}</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">
              <TrendingUpIcon 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">{{ inventoryStats.turnoverRate.toFixed(2) }}</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">
              <AlertTriangleIcon 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">{{ inventoryStats.lowStockItems }}</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-red-100 dark:bg-red-900">
              <XCircleIcon class="h-6 w-6 text-red-600 dark:text-red-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">{{ inventoryStats.outOfStockItems }}</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="statusChartRef" 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="item in paginatedInventory" :key="item.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-md object-cover" :src="item.image" :alt="item.name">
                    </div>
                    <div class="ml-4">
                      <div class="text-sm font-medium text-gray-900 dark:text-white">{{ item.name }}</div>
                      <div class="text-sm text-gray-500 dark:text-gray-400">{{ item.code }}</div>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4">
                  <span :class="['category-tag', `category-${item.category}`]">
                    {{ item.category === 'electronics' ? '电子产品' : 
                       item.category === 'clothing' ? '服装' : 
                       item.category === 'food' ? '食品' : '图书' }}
                  </span>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-900 dark:text-white">{{ item.stock }}</div>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-900 dark:text-white">{{ item.minStock }} - {{ item.maxStock }}</div>
                </td>
                <td class="px-6 py-4">
                  <span :class="['status-tag', `status-${item.status}`]">
                    {{ item.status === 'normal' ? '正常' : 
                       item.status === 'low' ? '库存不足' : 
                       item.status === 'overstock' ? '库存过多' : '缺货' }}
                  </span>
                </td>
                <td class="px-6 py-4 text-sm font-medium">
                  <button 
                    @click="handleViewItem(item)"
                    class="action-button view-button"
                  >
                    <EyeIcon class="h-4 w-4 inline-block mr-1" />
                    查看
                  </button>
                  <button 
                    @click="handleAdjustStock(item)"
                    class="action-button edit-button"
                  >
                    <EditIcon class="h-4 w-4 inline-block mr-1" />
                    调整
                  </button>
                  <button 
                    @click="handleDeleteItem(item)"
                    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, filteredInventory.length) }}</span> 条，共 
              <span class="font-medium">{{ filteredInventory.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, 
  ChevronLeftIcon, 
  ChevronRightIcon,
  PackageIcon,
  TrendingUpIcon,
  AlertTriangleIcon,
  XCircleIcon,
  EyeIcon,
  EditIcon,
  TrashIcon,
  ChevronUpIcon,
  ChevronDownIcon
} from 'lucide-vue-next'

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

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

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

// 图表相关
const trendChartRef = ref(null)
const statusChartRef = ref(null)
let trendChart = null
let statusChart = null

// 模拟数据
const mockInventory = ref([
  {
    id: 'I1001',
    productId: 'P1001',
    name: '智能手表 Pro',
    category: 'electronics',
    stock: 150,
    minStock: 50,
    maxStock: 300,
    status: 'in_stock',
    turnoverRate: 0.85,
    lastRestock: '2024-03-15',
    nextRestock: '2024-04-01',
    value: 194850,
    image: defaultImages.product
  },
  {
    id: 'I1002',
    productId: 'P1002',
    name: '无线蓝牙耳机',
    category: 'electronics',
    stock: 0,
    minStock: 100,
    maxStock: 500,
    status: 'out_of_stock',
    turnoverRate: 1.2,
    lastRestock: '2024-03-10',
    nextRestock: '2024-03-25',
    value: 0,
    image: defaultImages.product
  },
  {
    id: 'I1003',
    productId: 'P1003',
    name: '运动鞋',
    category: 'sports',
    stock: 80,
    minStock: 100,
    maxStock: 400,
    status: 'low_stock',
    turnoverRate: 0.65,
    lastRestock: '2024-03-01',
    nextRestock: '2024-03-20',
    value: 47920,
    image: defaultImages.product
  },
  {
    id: 'I1004',
    productId: 'P1004',
    name: '男士衬衫',
    category: 'clothing',
    stock: 200,
    minStock: 50,
    maxStock: 300,
    status: 'in_stock',
    turnoverRate: 0.45,
    lastRestock: '2024-02-15',
    nextRestock: '2024-04-01',
    value: 39800,
    image: defaultImages.product
  },
  {
    id: 'I1005',
    productId: 'P1005',
    name: '女士手提包',
    category: 'accessories',
    stock: 30,
    minStock: 20,
    maxStock: 100,
    status: 'low_stock',
    turnoverRate: 0.75,
    lastRestock: '2024-03-05',
    nextRestock: '2024-03-25',
    value: 26970,
    image: defaultImages.product
  }
])

// 库存统计数据
const inventoryStats = ref({
  totalInventory: 1234,
  turnoverRate: 0.85,
  lowStockItems: 56,
  outOfStockItems: 12
})

// 库存趋势数据
const inventoryTrends = ref([
  { date: '2024-03-01', value: 1200 },
  { date: '2024-03-02', value: 1250 },
  { date: '2024-03-03', value: 1300 },
  { date: '2024-03-04', value: 1280 },
  { date: '2024-03-05', value: 1350 },
  { date: '2024-03-06', value: 1400 },
  { date: '2024-03-07', value: 1380 }
])

// 库存分布数据
const inventoryDistribution = ref([
  { category: 'electronics', value: 450 },
  { category: 'clothing', value: 300 },
  { category: 'sports', value: 250 },
  { category: 'accessories', value: 150 },
  { category: 'food', value: 84 }
])

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

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

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

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

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

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

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

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

const handleViewItem = (item) => {
  console.log('查看商品:', item)
}

const handleAdjustStock = (item) => {
  console.log('调整库存:', item)
}

const handleDeleteItem = (item) => {
  console.log('删除商品:', item)
}

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

// Mock data
const mockTrendData = {
  dates: ['1月', '2月', '3月', '4月', '5月', '6月'],
  values: {
    electronics: [1200, 1400, 1800, 2200, 2600, 3000],
    clothing: [800, 1000, 1200, 1400, 1600, 1800],
    food: [1500, 1700, 1900, 2100, 2300, 2500],
    books: [600, 700, 800, 900, 1000, 1100]
  }
}

const mockStatusData = [
  { value: 40, name: '正常' },
  { value: 25, name: '库存不足' },
  { value: 20, name: '库存过多' },
  { value: 15, name: '缺货' }
]

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  
  trendChart = echarts.init(trendChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['电子产品', '服装', '食品', '图书']
    },
    xAxis: {
      type: 'category',
      data: mockTrendData.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '电子产品',
        type: 'line',
        data: mockTrendData.values.electronics
      },
      {
        name: '服装',
        type: 'line',
        data: mockTrendData.values.clothing
      },
      {
        name: '食品',
        type: 'line',
        data: mockTrendData.values.food
      },
      {
        name: '图书',
        type: 'line',
        data: mockTrendData.values.books
      }
    ]
  }
  trendChart.setOption(option)
}

// 初始化状态图表
const initStatusChart = () => {
  if (!statusChartRef.value) return
  
  statusChart = echarts.init(statusChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '库存状态',
        type: 'pie',
        radius: '50%',
        data: mockStatusData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  statusChart.setOption(option)
}

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

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

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  statusChart?.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-purple-100 dark:bg-purple-900 text-purple-800 dark:text-purple-400;
}

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

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

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

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

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

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

.status-out {
  @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> 