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

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

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

const formRef = ref(null)
const form = reactive({ id: null, order_no: '', supplier_id: '', total_amount: 0, remark: '' })
const isEdit = ref(false)
const formRules = {
  order_no: [{ required: true, message: '请输入采购单号', trigger: 'blur' }]
}

const statusMap = { 0: '待审批', 2: '已通过', 4: '已驳回' }
const statusType = { 0: 'warning', 2: 'success', 4: 'danger' }

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

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

function handleAdd() {
  isEdit.value = false
  Object.assign(form, { id: null, order_no: '', supplier_id: '', total_amount: 0, remark: '' })
  dialogVisible.value = true
}

async function handleEdit(row) {
  if (row.status >= 2) { ElMessage.warning('只能编辑待审批的采购单'); return }
  isEdit.value = true
  const res = await purchaseOrderApi.getDetail(row.id)
  const d = res.data
  Object.assign(form, { id: d.id, order_no: d.order_no, supplier_id: d.supplier_id || '', total_amount: d.total_amount, remark: d.remark || '' })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) { await purchaseOrderApi.update(form.id, form); ElMessage.success('更新成功') }
      else { await purchaseOrderApi.create(form); ElMessage.success('创建成功') }
      dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleDelete(row) {
  if (row.status >= 2) { ElMessage.warning('只能删除待审批的采购单'); return }
  await ElMessageBox.confirm(`确定删除采购单「${row.order_no}」吗？`, '删除确认', { type: 'warning' })
  await purchaseOrderApi.delete(row.id); ElMessage.success('删除成功'); fetchList()
}

async function handleAudit(row, status) {
  const msg = status === 2 ? '确认通过？' : '确认驳回？'
  await ElMessageBox.confirm(msg, '审批确认', { type: 'warning' })
  await purchaseOrderApi.audit(row.id, { status }); ElMessage.success('操作成功'); fetchList()
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }
onMounted(() => fetchList())
</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-input v-model="searchForm.order_no" placeholder="采购单号" style="width:180px" clearable @keydown.enter="handleSearch" />
      <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="order_no" label="采购单号" min-width="160" />
          <el-table-column label="供应商" min-width="140">
            <template #default="{ row }">{{ row.supplier?.name || '-' }}</template>
          </el-table-column>
          <el-table-column prop="total_amount" label="总金额" min-width="110" align="right" />
          <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="260" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.status===0" size="small" type="success" text @click="handleAudit(row, 2)">审批通过</el-button>
              <el-button v-if="row.status===0" size="small" type="warning" text @click="handleAudit(row, 4)">驳回</el-button>
              <el-button v-if="row.status<2" size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button v-if="row.status<2" size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </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="isEdit ? '编辑采购单' : '新增采购单'" width="550px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-form-item label="采购单号" prop="order_no">
          <el-input v-model="form.order_no" />
        </el-form-item>
        <el-form-item label="供应商ID">
          <el-input v-model="form.supplier_id" placeholder="供应商ID" />
        </el-form-item>
        <el-form-item label="总金额">
          <el-input-number v-model="form.total_amount" :min="0" :precision="2" style="width:100%" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item>
      </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>
