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

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

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

const formRef = ref(null)
const form = reactive({
  warehouse_id: '',
  check_date: '',
  remark: '',
  items: []
})
const formRules = {
  warehouse_id: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  check_date: [{ required: true, message: '请选择盘点日期', trigger: 'change' }]
}

const statusMap = { draft: '盘点中', completed: '已完成' }
const statusType = { draft: 'warning', completed: 'success' }

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

async function handleAdd() {
  Object.assign(form, { warehouse_id: '', check_date: '', remark: '', items: [] })
  dialogVisible.value = true
}

// 选择仓库后自动加载该仓库库存
async function onWarehouseChange(warehouseId) {
  if (!warehouseId) { form.items = []; return }
  try {
    const res = await stockApi.getList({ warehouse_id: warehouseId, per_page: 500 })
    const stocks = res.data?.list || res.data?.data || []
    form.items = stocks.map(s => ({
      material_id: s.id,
      material_name: s.material_name,
      material_code: s.material_code,
      unit: s.unit,
      system_quantity: Number(s.quantity || 0),
      actual_quantity: Number(s.quantity || 0)
    }))
  } catch {
    ElMessage.error('加载库存数据失败')
  }
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    if (form.items.length === 0) { ElMessage.warning('当前仓库无库存数据'); return }
    submitLoading.value = true
    try {
      await inventoryCheckApi.create({ ...form })
      ElMessage.success('盘点单创建成功')
      dialogVisible.value = false
      fetchList()
    } catch {
      ElMessage.error('创建失败')
    } finally {
      submitLoading.value = false
    }
  })
}

async function handleComplete(row) {
  await ElMessageBox.confirm(
    `确认完成盘点单「${row.check_no}」吗？完成后不可修改。`,
    '完成确认',
    { type: 'warning' }
  )
  try {
    await inventoryCheckApi.complete(row.id, {})
    ElMessage.success('盘点完成')
    fetchList()
  } catch { ElMessage.error('操作失败') }
}

function viewDetail(row) {
  currentCheck.value = row
  detailVisible.value = true
}

function diff(item) {
  return Number(item.actual_quantity || 0) - Number(item.system_quantity || 0)
}

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:160px">
        <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="check_no" label="盘点单号" min-width="160" />
          <el-table-column prop="warehouse_name" label="仓库" min-width="110" />
          <el-table-column prop="check_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="operator_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 size="small" type="primary" text @click="viewDetail(row)">查看</el-button>
              <el-button
                v-if="row.status === 'draft'"
                size="small" type="success" text
                @click="handleComplete(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>

    <!-- 新建盘点 Dialog -->
    <el-dialog v-model="dialogVisible" title="新建盘点单" width="820px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-row :gutter="16">
          <el-col :span="10">
            <el-form-item label="仓库" prop="warehouse_id">
              <el-select
                v-model="form.warehouse_id"
                placeholder="选择仓库"
                filterable
                style="width:100%"
                @change="onWarehouseChange"
              >
                <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="8">
            <el-form-item label="盘点日期" prop="check_date">
              <el-date-picker
                v-model="form.check_date"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
                style="width:100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <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-if="form.items.length === 0" class="text-center text-gray-400 py-6">
          请先选择仓库以加载库存数据
        </div>
        <el-table v-else :data="form.items" style="width:100%" max-height="320">
          <el-table-column prop="material_code" label="物料编码" width="110" />
          <el-table-column prop="material_name" label="物料名称" min-width="130" />
          <el-table-column prop="unit" label="单位" width="70" align="center" />
          <el-table-column prop="system_quantity" label="系统数量" width="100" align="right" />
          <el-table-column label="实际数量" width="140" align="right">
            <template #default="{ row }">
              <el-input-number
                v-model="row.actual_quantity"
                :min="0"
                :precision="2"
                size="small"
                style="width:120px"
              />
            </template>
          </el-table-column>
          <el-table-column label="差异" width="90" align="right">
            <template #default="{ row }">
              <span :class="diff(row) === 0 ? 'text-gray-500' : diff(row) > 0 ? 'text-green-600' : 'text-red-500'">
                {{ diff(row) > 0 ? '+' : '' }}{{ diff(row).toFixed(2) }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">提交盘点</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情 Dialog -->
    <el-dialog v-model="detailVisible" title="盘点单详情" width="760px" destroy-on-close>
      <template v-if="currentCheck">
        <el-descriptions :column="3" border size="small" class="mb-4">
          <el-descriptions-item label="盘点单号">{{ currentCheck.check_no }}</el-descriptions-item>
          <el-descriptions-item label="仓库">{{ currentCheck.warehouse_name }}</el-descriptions-item>
          <el-descriptions-item label="盘点日期">{{ currentCheck.check_date }}</el-descriptions-item>
          <el-descriptions-item label="操作人">{{ currentCheck.operator_name }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="statusType[currentCheck.status]" size="small">
              {{ statusMap[currentCheck.status] }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注">{{ currentCheck.remark || '-' }}</el-descriptions-item>
        </el-descriptions>
        <el-table :data="currentCheck.items || []" style="width:100%" max-height="360">
          <el-table-column prop="material_name" label="物料名称" min-width="130" />
          <el-table-column prop="system_quantity" label="系统数量" width="100" align="right" />
          <el-table-column prop="actual_quantity" label="实际数量" width="100" align="right" />
          <el-table-column label="差异" width="90" align="right">
            <template #default="{ row }">
              <span :class="diff(row) === 0 ? 'text-gray-500' : diff(row) > 0 ? 'text-green-600' : 'text-red-500'">
                {{ diff(row) > 0 ? '+' : '' }}{{ Number(diff(row)).toFixed(2) }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-dialog>
  </div>
</template>
