<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { stockApi, warehouseApi, materialApi } from '@/api/inventory.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const warehouses = ref([])
const materials = ref([])

const searchForm = reactive({ warehouse_id: '', material_id: '', low_stock: '' })
const pagination = reactive({ page: 1, per_page: 20 })

async function fetchList() {
  loading.value = true
  try {
    const res = await stockApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } catch {
    ElMessage.error('获取库存列表失败')
  } finally {
    loading.value = false
  }
}

async function fetchOptions() {
  try {
    const [wRes, mRes] = await Promise.all([
      warehouseApi.getList({ per_page: 500 }),
      materialApi.getList({ per_page: 500 })
    ])
    warehouses.value = wRes.data?.list || wRes.data?.data || []
    materials.value = mRes.data?.list || mRes.data?.data || []
  } catch {}
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() {
  Object.assign(searchForm, { warehouse_id: '', material_id: '', low_stock: '' })
  handleSearch()
}
function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

function isLowStock(row) {
  return row.min_quantity != null && Number(row.quantity) < Number(row.min_quantity)
}

function handleExport() {
  ElMessage.info('导出功能待实现')
}

onMounted(() => { fetchList(); fetchOptions() })
</script>

<template>
  <div class="p-6 space-y-4">
    <!-- 搜索栏 -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-select v-model="searchForm.warehouse_id" placeholder="选择仓库" clearable filterable style="width:160px">
        <el-option v-for="w in warehouses" :key="w.id" :label="w.name" :value="w.id" />
      </el-select>
      <el-select v-model="searchForm.material_id" placeholder="选择物料" clearable filterable style="width:180px">
        <el-option v-for="m in materials" :key="m.id" :label="`${m.name}(${m.code || '-'})`" :value="m.id" />
      </el-select>
      <el-select v-model="searchForm.low_stock" placeholder="库存状态" clearable style="width:130px">
        <el-option label="全部" value="" />
        <el-option label="低库存预警" value="1" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button class="ml-auto" @click="handleExport">导出</el-button>
    </div>

    <!-- 低库存说明 -->
    <el-alert
      title="红色行表示当前库存低于最低库存量，请及时补货"
      type="warning"
      show-icon
      :closable="false"
    />

    <!-- 列表卡片 -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center gap-3 px-5 py-4 border-b border-gray-50">
        <span class="w-1 h-5 bg-rose-500 rounded-full inline-block"></span>
        <span class="font-medium text-gray-700">库存查询</span>
        <span class="text-sm text-gray-400 ml-1">共 {{ total }} 条</span>
      </div>
      <div class="px-2">
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width:100%"
          :row-class-name="({ row }) => isLowStock(row) ? 'low-stock-row' : ''"
        >
          <el-table-column prop="warehouse_name" label="仓库" min-width="110" />
          <el-table-column prop="material_code" label="物料编码" width="120" />
          <el-table-column prop="material_name" label="物料名称" min-width="140" />
          <el-table-column prop="category" label="分类" width="100" align="center" />
          <el-table-column prop="unit" label="单位" width="70" align="center" />
          <el-table-column label="当前库存" width="110" align="right">
            <template #default="{ row }">
              <span :class="isLowStock(row) ? 'text-red-500 font-bold' : 'text-gray-700'">
                {{ row.quantity }}
              </span>
              <el-tag v-if="isLowStock(row)" type="danger" size="small" class="ml-1">偏低</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="min_quantity" label="最低库存" width="100" align="right" />
          <el-table-column prop="max_quantity" label="最高库存" width="100" align="right" />
          <el-table-column prop="updated_at" label="更新时间" min-width="160" />
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.per_page"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total,sizes,prev,pager,next,jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<style>
.el-table .low-stock-row {
  background-color: #fff5f5 !important;
}
</style>
