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

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

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

const formRef = ref(null)
const form = reactive({
  id: null, warehouse_id: '', movement_no: '', type: '', direction: '', related_order: '', remark: ''
})
const formRules = {
  warehouse_id: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  movement_no: [{ required: true, message: '请输入单据编号', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  direction: [{ required: true, message: '请选择方向', trigger: 'change' }]
}

const typeMap = { 1: '采购入库', 2: '领用出库', 3: '退货入库', 4: '报损出库' }
const directionMap = { 1: '入库', 2: '出库' }
const directionType = { 1: 'success', 2: 'danger' }
const statusMap = { 0: '待确认', 1: '已确认' }
const statusType = { 0: 'warning', 1: 'success' }

async function fetchList() {
  loading.value = true
  try {
    const res = await stockMovementApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } finally { loading.value = false }
}

async function fetchWarehouses() {
  try {
    const res = await warehouseApi.getList({ per_page: 500 })
    warehouses.value = res.data?.list || res.data?.data || []
  } catch {}
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() { Object.assign(searchForm, { warehouse_id: '', type: '', status: '' }); handleSearch() }

function handleAdd() {
  Object.assign(form, { id: null, warehouse_id: '', movement_no: '', type: '', direction: '', related_order: '', remark: '' })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      await stockMovementApi.create(form)
      ElMessage.success('创建成功'); dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleConfirm(row) {
  await ElMessageBox.confirm('确认该出入库单？确认后将更新库存', '确认操作', { type: 'warning' })
  await stockMovementApi.confirm(row.id); ElMessage.success('确认成功'); fetchList()
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

onMounted(() => { fetchList(); fetchWarehouses() })
</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:180px">
        <el-option v-for="w in warehouses" :key="w.id" :label="w.name" :value="w.id" />
      </el-select>
      <el-select v-model="searchForm.type" placeholder="类型" clearable style="width:140px">
        <el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width:120px">
        <el-option v-for="(v, k) in statusMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3">
          <span class="font-medium text-gray-700">出入库记录</span>
        </div>
        <el-button type="primary" @click="handleAdd">新增出入库</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column prop="movement_no" label="单据编号" min-width="160" />
          <el-table-column label="仓库" min-width="120">
            <template #default="{ row }">{{ row.warehouse?.name || '-' }}</template>
          </el-table-column>
          <el-table-column label="类型" width="110" align="center">
            <template #default="{ row }"><el-tag size="small">{{ typeMap[row.type] || '-' }}</el-tag></template>
          </el-table-column>
          <el-table-column label="方向" width="90" align="center">
            <template #default="{ row }"><el-tag :type="directionType[row.direction]" size="small">{{ directionMap[row.direction] || '-' }}</el-tag></template>
          </el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template #default="{ row }"><el-tag :type="statusType[row.status]" size="small">{{ statusMap[row.status] }}</el-tag></template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
          <el-table-column label="操作" width="100" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.status === 0" size="small" type="success" text @click="handleConfirm(row)">确认</el-button>
              <span v-else class="text-muted">-</span>
            </template>
          </el-table-column>
        </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>

    <el-dialog v-model="dialogVisible" title="新增出入库" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouse_id">
              <el-select v-model="form.warehouse_id" placeholder="选择仓库" filterable style="width:100%">
                <el-option v-for="w in warehouses" :key="w.id" :label="w.name" :value="w.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据编号" prop="movement_no">
              <el-input v-model="form.movement_no" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="选择类型" style="width:100%">
                <el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="方向" prop="direction">
              <el-select v-model="form.direction" placeholder="选择方向" style="width:100%">
                <el-option v-for="(v, k) in directionMap" :key="k" :label="v" :value="Number(k)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联单号">
              <el-input v-model="form.related_order" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
