<template>
  <div class="min-h-screen bg-gray-100 dark:bg-gray-900">
    <!-- 顶部导航 -->
    <div class="bg-white dark:bg-gray-800 shadow">
      <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">
            <div class="flex-shrink-0 flex items-center">
              <h1 class="text-xl font-bold text-gray-900 dark:text-white">库存管理</h1>
            </div>
          </div>
          <div class="flex items-center space-x-4">
            <button @click="showAddModal = true" class="btn-primary">
              新增库存
            </button>
            <button @click="exportInventory" class="btn-secondary">
              导出数据
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 库存统计 -->
      <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">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white">总库存量</h3>
          <p class="mt-2 text-3xl font-bold text-blue-600 dark:text-blue-400">
            {{ totalInventory }}
          </p>
        </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">库存价值</h3>
          <p class="mt-2 text-3xl font-bold text-green-600 dark:text-green-400">
            ¥{{ formatNumber(totalValue) }}
          </p>
        </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">低库存预警</h3>
          <p class="mt-2 text-3xl font-bold text-red-600 dark:text-red-400">
            {{ lowStockCount }}
          </p>
        </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">库存周转率</h3>
          <p class="mt-2 text-3xl font-bold text-purple-600 dark:text-purple-400">
            {{ turnoverRate }}%
          </p>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow mb-8">
        <div class="p-6">
          <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">商品类型</label>
              <select v-model="selectedType" class="mt-1 form-select">
                <option value="">全部</option>
                <option v-for="type in types" :key="type" :value="type">{{ type }}</option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">库存状态</label>
              <select v-model="selectedStatus" class="mt-1 form-select">
                <option value="">全部</option>
                <option v-for="status in statuses" :key="status" :value="status">{{ status }}</option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">仓库</label>
              <select v-model="selectedWarehouse" class="mt-1 form-select">
                <option value="">全部</option>
                <option v-for="warehouse in warehouses" :key="warehouse" :value="warehouse">{{ warehouse }}</option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">搜索</label>
              <input
                v-model="searchText"
                type="text"
                placeholder="商品名称/编号"
                class="mt-1 form-input"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 库存列表 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow">
        <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 filteredInventory" :key="item.id">
                <td class="px-6 py-4 whitespace-nowrap">
                  <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>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm text-gray-900 dark:text-white">{{ item.quantity }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm text-gray-900 dark:text-white">{{ item.unit }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm text-gray-900 dark:text-white">{{ item.warehouse }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span :class="getStatusClass(item.status)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                    {{ item.status }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  <button @click="viewItem(item)" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 mr-4">查看</button>
                  <button @click="editItem(item)" class="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300 mr-4">编辑</button>
                  <button @click="deleteItem(item)" class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 新增/编辑库存模态框 -->
    <div v-if="showAddModal" class="fixed inset-0 z-10 overflow-y-auto">
      <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
          <div class="absolute inset-0 bg-gray-500 dark:bg-gray-900 opacity-75"></div>
        </div>
        <div class="inline-block align-bottom bg-white dark:bg-gray-800 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
          <div class="bg-white dark:bg-gray-800 px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
              {{ editingItem ? '编辑库存' : '新增库存' }}
            </h3>
            <form @submit.prevent="submitForm">
              <div class="grid grid-cols-1 gap-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">商品名称</label>
                  <input v-model="form.name" type="text" class="mt-1 form-input" required />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">商品编号</label>
                  <input v-model="form.code" type="text" class="mt-1 form-input" required />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">商品类型</label>
                  <select v-model="form.type" class="mt-1 form-select" required>
                    <option v-for="type in types" :key="type" :value="type">{{ type }}</option>
                  </select>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">库存数量</label>
                  <input v-model="form.quantity" type="number" class="mt-1 form-input" required />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">单位</label>
                  <input v-model="form.unit" type="text" class="mt-1 form-input" required />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">仓库</label>
                  <select v-model="form.warehouse" class="mt-1 form-select" required>
                    <option v-for="warehouse in warehouses" :key="warehouse" :value="warehouse">{{ warehouse }}</option>
                  </select>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">备注</label>
                  <textarea v-model="form.remark" class="mt-1 form-textarea" rows="3"></textarea>
                </div>
              </div>
              <div class="mt-6 flex justify-end space-x-3">
                <button type="button" @click="showAddModal = false" class="btn-secondary">
                  取消
                </button>
                <button type="submit" class="btn-primary">
                  保存
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 数据定义
const types = ['原材料', '半成品', '成品', '配件']
const statuses = ['正常', '低库存', '缺货']
const warehouses = ['主仓库', 'A区仓库', 'B区仓库']

const inventory = ref([
  {
    id: 1,
    name: '商品A',
    code: 'SP001',
    type: '成品',
    quantity: 100,
    unit: '个',
    warehouse: '主仓库',
    status: '正常',
    remark: ''
  },
  // 更多示例数据...
])

const searchText = ref('')
const selectedType = ref('')
const selectedStatus = ref('')
const selectedWarehouse = ref('')
const showAddModal = ref(false)
const editingItem = ref(null)

const form = ref({
  name: '',
  code: '',
  type: '',
  quantity: 0,
  unit: '',
  warehouse: '',
  remark: ''
})

// 计算属性
const filteredInventory = computed(() => {
  return inventory.value.filter(item => {
    const matchesSearch = !searchText.value || 
      item.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
      item.code.toLowerCase().includes(searchText.value.toLowerCase())
    const matchesType = !selectedType.value || item.type === selectedType.value
    const matchesStatus = !selectedStatus.value || item.status === selectedStatus.value
    const matchesWarehouse = !selectedWarehouse.value || item.warehouse === selectedWarehouse.value
    return matchesSearch && matchesType && matchesStatus && matchesWarehouse
  })
})

const totalInventory = computed(() => {
  return inventory.value.reduce((sum, item) => sum + item.quantity, 0)
})

const totalValue = computed(() => {
  // 这里假设每个商品的价值是固定的，实际应用中应该从商品信息中获取
  return inventory.value.reduce((sum, item) => sum + item.quantity * 100, 0)
})

const lowStockCount = computed(() => {
  return inventory.value.filter(item => item.status === '低库存').length
})

const turnoverRate = computed(() => {
  // 这里使用一个简单的计算方式，实际应用中应该根据实际的出入库记录计算
  return Math.round((totalInventory.value / 1000) * 100)
})

// 方法
const getStatusClass = (status) => {
  switch (status) {
    case '正常':
      return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300'
    case '低库存':
      return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300'
    case '缺货':
      return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300'
    default:
      return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300'
  }
}

const formatNumber = (num) => {
  return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const viewItem = (item) => {
  // 实现查看详情逻辑
}

const editItem = (item) => {
  editingItem.value = item
  form.value = { ...item }
  showAddModal.value = true
}

const deleteItem = (item) => {
  if (confirm('确定要删除这个库存记录吗？')) {
    inventory.value = inventory.value.filter(i => i.id !== item.id)
  }
}

const submitForm = () => {
  if (editingItem.value) {
    // 更新现有记录
    const index = inventory.value.findIndex(item => item.id === editingItem.value.id)
    if (index !== -1) {
      inventory.value[index] = { ...form.value, id: editingItem.value.id }
    }
  } else {
    // 添加新记录
    const newItem = {
      ...form.value,
      id: inventory.value.length + 1,
      status: form.value.quantity < 10 ? '低库存' : '正常'
    }
    inventory.value.push(newItem)
  }
  showAddModal.value = false
  resetForm()
}

const resetForm = () => {
  form.value = {
    name: '',
    code: '',
    type: '',
    quantity: 0,
    unit: '',
    warehouse: '',
    remark: ''
  }
  editingItem.value = null
}

const exportInventory = () => {
  // 实现导出逻辑
  const data = JSON.stringify(inventory.value, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'inventory.json'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}
</script> 