<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="handleAddSupplier"
              class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 flex items-center space-x-2"
            >
              <PlusIcon class="h-5 w-5" />
              <span>新增供应商</span>
            </button>
            <button 
              @click="handleExportSuppliers"
              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="supplierType"
            @change="handleTypeChange"
            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="manufacturer">生产商</option>
            <option value="distributor">经销商</option>
            <option value="wholesaler">批发商</option>
            <option value="retailer">零售商</option>
          </select>
          <select 
            v-model="supplierStatus"
            @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="active">正常合作</option>
            <option value="inactive">暂停合作</option>
            <option value="blacklisted">黑名单</option>
          </select>
          <select 
            v-model="supplierLevel"
            @change="handleLevelChange"
            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="A">A级</option>
            <option value="B">B级</option>
            <option value="C">C级</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">
              <BuildingIcon 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">{{ mockSuppliers.length }}</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">
              <Building2Icon 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">{{ mockSuppliers.filter(supplier => supplier.status === 'active').length }}</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">
              <BuildingIcon 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">{{ mockSuppliers.filter(supplier => supplier.status === 'inactive').length }}</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">
              <BuildingIcon 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">{{ mockSuppliers.filter(supplier => supplier.status === 'blacklisted').length }}</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="typeChartRef" 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="levelChartRef" 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="supplier in paginatedSuppliers" :key="supplier.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="supplier.logo" :alt="supplier.name">
                    </div>
                    <div class="ml-4">
                      <div class="text-sm font-medium text-gray-900 dark:text-white">{{ supplier.name }}</div>
                      <div class="text-sm text-gray-500 dark:text-gray-400">{{ supplier.code }}</div>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4">
                  <span :class="['type-tag', `type-${supplier.type}`]">
                    {{ supplier.type === 'manufacturer' ? '生产商' : 
                       supplier.type === 'distributor' ? '经销商' : 
                       supplier.type === 'wholesaler' ? '批发商' : '零售商' }}
                  </span>
                </td>
                <td class="px-6 py-4">
                  <span :class="['level-tag', `level-${supplier.level}`]">
                    {{ supplier.level }}级
                  </span>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-900 dark:text-white">{{ supplier.contact }}</div>
                  <div class="text-sm text-gray-500 dark:text-gray-400">{{ supplier.phone }}</div>
                </td>
                <td class="px-6 py-4">
                  <span :class="['status-tag', `status-${supplier.status}`]">
                    {{ supplier.status === 'active' ? '正常合作' : 
                       supplier.status === 'inactive' ? '暂停合作' : '黑名单' }}
                  </span>
                </td>
                <td class="px-6 py-4 text-sm font-medium">
                  <button 
                    @click="handleViewSupplier(supplier)"
                    class="action-button view-button"
                  >
                    <EyeIcon class="h-4 w-4 inline-block mr-1" />
                    查看
                  </button>
                  <button 
                    @click="handleEditSupplier(supplier)"
                    class="action-button edit-button"
                  >
                    <EditIcon class="h-4 w-4 inline-block mr-1" />
                    编辑
                  </button>
                  <button 
                    @click="handleDeleteSupplier(supplier)"
                    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, filteredSuppliers.length) }}</span> 条，共 
              <span class="font-medium">{{ filteredSuppliers.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, 
  ChevronLeftIcon, 
  ChevronRightIcon,
  BuildingIcon,
  Building2Icon,
  DownloadIcon,
  PlusIcon,
  EyeIcon,
  EditIcon,
  TrashIcon
} from 'lucide-vue-next'

// 默认图片配置
const defaultImages = {
  supplier: 'https://ui-avatars.com/api/?name=Supplier&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 supplierType = ref('')
const supplierStatus = ref('')
const supplierLevel = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalSuppliers = ref(100)

// 图表相关
const typeChartRef = ref(null)
const levelChartRef = ref(null)
let typeChart = null
let levelChart = null

// 模拟数据
const mockSuppliers = ref([
  {
    id: 'S1001',
    name: '电子科技公司',
    code: 'S1001',
    type: 'manufacturer',
    level: 'A',
    contact: '张经理',
    phone: '13800138001',
    status: 'active',
    logo: defaultImages.supplier
  },
  {
    id: 'S1002',
    name: '服装制造厂',
    code: 'S1002',
    type: 'manufacturer',
    level: 'B',
    contact: '李经理',
    phone: '13800138002',
    status: 'active',
    logo: defaultImages.supplier
  },
  {
    id: 'S1003',
    name: '箱包供应商',
    code: 'S1003',
    type: 'distributor',
    level: 'A',
    contact: '王经理',
    phone: '13800138003',
    status: 'inactive',
    logo: defaultImages.supplier
  },
  {
    id: 'S1004',
    name: '运动用品公司',
    code: 'S1004',
    type: 'wholesaler',
    level: 'C',
    contact: '赵经理',
    phone: '13800138004',
    status: 'blacklisted',
    logo: defaultImages.supplier
  },
  {
    id: 'S1005',
    name: '食品供应商',
    code: 'S1005',
    type: 'retailer',
    level: 'B',
    contact: '钱经理',
    phone: '13800138005',
    status: 'active',
    logo: defaultImages.supplier
  }
])

// 供应商统计数据
const supplierStats = ref({
  totalSuppliers: 1234,
  activeSuppliers: 1024,
  inactiveSuppliers: 56,
  blacklistedSuppliers: 12
})

// 计算属性
const filteredSuppliers = computed(() => {
  let result = [...mockSuppliers.value]
  
  // 搜索过滤
  if (searchText.value) {
    result = result.filter(supplier => 
      supplier.name.includes(searchText.value) ||
      supplier.code.includes(searchText.value)
    )
  }
  
  // 类型过滤
  if (supplierType.value) {
    result = result.filter(supplier => supplier.type === supplierType.value)
  }
  
  // 状态过滤
  if (supplierStatus.value) {
    result = result.filter(supplier => supplier.status === supplierStatus.value)
  }
  
  // 等级过滤
  if (supplierLevel.value) {
    result = result.filter(supplier => supplier.level === supplierLevel.value)
  }
  
  return result
})

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

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

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

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

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

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

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

const handleAddSupplier = () => {
  console.log('新增供应商')
}

const handleViewSupplier = (supplier) => {
  console.log('查看供应商:', supplier)
}

const handleEditSupplier = (supplier) => {
  console.log('编辑供应商:', supplier)
}

const handleDeleteSupplier = (supplier) => {
  console.log('删除供应商:', supplier)
}

const handleExportSuppliers = () => {
  console.log('导出供应商')
}

// Mock data
const mockTypeData = [
  { value: 40, name: '生产商' },
  { value: 30, name: '经销商' },
  { value: 20, name: '批发商' },
  { value: 10, name: '零售商' }
]

const mockLevelData = [
  { value: 50, name: 'A级' },
  { value: 30, name: 'B级' },
  { value: 20, name: 'C级' }
]

// 初始化类型图表
const initTypeChart = () => {
  if (!typeChartRef.value) return
  
  typeChart = echarts.init(typeChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '供应商类型',
        type: 'pie',
        radius: '50%',
        data: mockTypeData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  typeChart.setOption(option)
}

// 初始化等级图表
const initLevelChart = () => {
  if (!levelChartRef.value) return
  
  levelChart = echarts.init(levelChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '供应商等级',
        type: 'pie',
        radius: '50%',
        data: mockLevelData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  levelChart.setOption(option)
}

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

onMounted(() => {
  initTypeChart()
  initLevelChart()
  window.addEventListener('resize', handleResize)
})

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

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

/* 供应商类型标签样式 */
.type-tag {
  @apply px-2 inline-flex text-xs leading-5 font-semibold rounded-full;
}

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

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

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

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

/* 供应商等级标签样式 */
.level-tag {
  @apply px-2 inline-flex text-xs leading-5 font-semibold rounded-full;
}

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

.level-B {
  @apply bg-orange-100 dark:bg-orange-900 text-orange-800 dark:text-orange-400;
}

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

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

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

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

.status-blacklisted {
  @apply bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-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> 