<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { transferApi, warehouseApi, materialApi } 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 materials = ref([])

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

const defaultItem = () => ({ material_id: '', material_name: '', quantity: 1 })
const formRef = ref(null)
const form = reactive({
  from_warehouse_id: '',
  to_warehouse_id: '',
  transfer_date: '',
  remark: '',
  items: [defaultItem()]
})
const formRules = {
  from_warehouse_id: [{ required: true, message: '请选择源仓库', trigger: 'change' }],
  to_warehouse_id: [{ required: true, message: '请选择目标仓库', trigger: 'change' }],
  transfer_date: [{ required: true, message: '请选择调拨日期', trigger: 'change' }]
}

const statusMap = { draft: '草稿', confirmed: '已确认', completed: '已完成', cancelled: '已取消' }
const statusType = { draft: 'info', confirmed: 'primary', completed: 'success', cancelled: 'danger' }

async function fetchList() {
  loading.value = true
  try {
    const res = await transferApi.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, { from_warehouse_id: '', to_warehouse_id: '', status: '' })
  handleSearch()
}

function handleAdd() {
  Object.assign(form, {
    from_warehouse_id: '', to_warehouse_id: '',
    transfer_date: '', remark: '',
    items: [defaultItem()]
  })
  dialogVisible.value = true
}

function addItem() { form.items.push(defaultItem()) }
function removeItem(idx) {
  if (form.items.length <= 1) { ElMessage.warning('至少保留一条物料'); return }
  form.items.splice(idx, 1)
}

function onMaterialChange(item) {
  const mat = materials.value.find(m => m.id === item.material_id)
  if (mat) item.material_name = mat.name
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    const hasEmpty = form.items.some(i => !i.material_id || i.quantity <= 0)
    if (hasEmpty) { ElMessage.warning('请完整填写物料信息'); return }
    submitLoading.value = true
    try {
      await transferApi.create({ ...form })
      ElMessage.success('创建成功')
      dialogVisible.value = false
      fetchList()
    } catch {
      ElMessage.error('创建失败')
    } finally {
      submitLoading.value = false
    }
  })
}

async function handleConfirm(row) {
  await ElMessageBox.confirm(`确认调拨单「${row.transfer_no}」吗？`, '确认操作', { type: 'warning' })
  try {
    await transferApi.confirm(row.id)
    ElMessage.success('确认成功')
    fetchList()
  } catch { ElMessage.error('操作失败') }
}

async function handleCancel(row) {
  await ElMessageBox.confirm(`取消调拨单「${row.transfer_no}」吗？取消后不可恢复。`, '取消确认', { type: 'warning' })
  try {
    await transferApi.cancel(row.id)
    ElMessage.success('已取消')
    fetchList()
  } catch { ElMessage.error('操作失败') }
}

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

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.from_warehouse_id" placeholder="源仓库" clearable filterable style="width:150px">
        <el-option v-for="w in warehouses" :key="w.id" :label="w.name" :value="w.id" />
      </el-select>
      <el-select v-model="searchForm.to_warehouse_id" placeholder="目标仓库" clearable filterable style="width:150px">
        <el-option v-for="w in warehouses" :key="w.id" :label="w.name" :value="w.id" />
      </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="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="w-1 h-5 bg-rose-500 rounded-full inline-block"></span>
          <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%" stripe>
          <el-table-column prop="transfer_no" label="调拨单号" min-width="160" />
          <el-table-column prop="from_warehouse_name" label="源仓库" min-width="110" />
          <el-table-column prop="to_warehouse_name" label="目标仓库" min-width="110" />
          <el-table-column prop="transfer_date" label="调拨日期" width="120" align="center" />
          <el-table-column label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="statusType[row.status]" size="small">
                {{ statusMap[row.status] || row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_by_name" label="创建人" width="90" align="center" />
          <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button
                v-if="row.status === 'draft'"
                size="small" type="success" text
                @click="handleConfirm(row)"
              >确认</el-button>
              <el-button
                v-if="row.status === 'draft'"
                size="small" type="danger" text
                @click="handleCancel(row)"
              >取消</el-button>
              <span v-if="!['draft'].includes(row.status)" class="text-gray-400 text-sm">-</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>

    <!-- 新建调拨单 Dialog -->
    <el-dialog v-model="dialogVisible" title="新建调拨单" width="680px" 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="from_warehouse_id">
              <el-select v-model="form.from_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="to_warehouse_id">
              <el-select v-model="form.to_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="transfer_date">
              <el-date-picker
                v-model="form.transfer_date"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
                style="width:100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="form.remark" placeholder="备注（可选）" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">调拨物料明细</el-divider>

        <div v-for="(item, idx) in form.items" :key="idx" class="flex items-center gap-2 mb-3">
          <el-select
            v-model="item.material_id"
            placeholder="选择物料"
            filterable
            style="flex:2"
            @change="onMaterialChange(item)"
          >
            <el-option
              v-for="m in materials"
              :key="m.id"
              :label="`${m.name}（${m.code || '-'}）`"
              :value="m.id"
            />
          </el-select>
          <el-input-number
            v-model="item.quantity"
            :min="1"
            placeholder="数量"
            style="width:130px"
          />
          <el-button type="danger" text @click="removeItem(idx)">删除</el-button>
        </div>
        <el-button type="primary" text @click="addItem">+ 添加物料</el-button>
      </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>
