<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getStockInList, auditStockIn } from '@/api/stockIn'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const query = reactive({ page: 1, size: 10 })
const tableData = ref([])
const total = ref(0)

function statusTag(status) {
  return { 0: 'warning', 1: 'success', 2: 'info' }[status] || 'info'
}
function statusText(status) {
  return { 0: '待审核', 1: '已入库', 2: '已取消' }[status] || '未知'
}

async function loadData() { try { const r = await getStockInList(query); tableData.value = r.data?.records || []; total.value = r.data?.total || 0 } catch { /* */ } }
function handleCreate() { router.push('/stock-in/add') }
function handleView(row) { /* 查看详情弹窗 */ ElMessage.info('入库单号: ' + (row.recordNo || row.record_no)) }
async function handleAudit(row) { await auditStockIn(row.id, { status: 1 }); ElMessage.success('审核通过，库存已更新'); loadData() }

onMounted(loadData)
</script>

<template>
  <div class="page-container">
    <div class="search-bar">
      <el-input v-model="query.recordNo" placeholder="入库单号" clearable style="width:180px" />
      <el-button type="primary" :icon="Search" @click="loadData">搜索</el-button>
      <el-button :icon="Refresh" @click="Object.keys(query).forEach(k=>query[k]=k==='page'?1:k==='size'?10:'');loadData()">重置</el-button>
    </div>
    <div class="tool-bar">
      <el-button type="primary" v-permission="'stock-in:add'" :icon="Plus" @click="handleCreate">+ 新建入库单</el-button>
    </div>
    <el-table :data="tableData" border stripe>
      <el-table-column prop="recordNo" label="入库单号" width="150" />
      <el-table-column prop="supplierName" label="供应商" min-width="180" />
      <el-table-column prop="totalAmount" label="总金额" width="110"><template #default="{row}">¥{{row.totalAmount}}</template></el-table-column>
      <el-table-column prop="inDate" label="入库日期" width="120" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{row}"><el-tag :type="statusTag(row.status)" size="small">{{statusText(row.status)}}</el-tag></template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{row}">
          <div class="table-actions">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button v-if="row.status===0" size="small" type="success" v-permission="'stock-in:audit'" @click="handleAudit(row)">审核</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="display:flex;justify-content:flex-end;margin-top:16px"><el-pagination v-model:current-page="query.page" v-model:page-size="query.size" :total="total" :page-sizes="[10,20,50]" layout="total,sizes,prev,pager,next" @current-change="loadData" @size-change="query.page=1;loadData()" /></div>
  </div>
</template>
