<template>
  <div class="lost-found-container">
    <!-- 顶部统计 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :span="6">
        <vab-card shadow="hover" class="stat-card">
          <div class="stat-icon bg-primary">
            <vab-icon icon="search-2-line" />
          </div>
          <div class="stat-info">
            <div class="stat-value">12</div>
            <div class="stat-label">今日新增</div>
          </div>
        </vab-card>
      </el-col>
      <el-col :span="6">
        <vab-card shadow="hover" class="stat-card">
          <div class="stat-icon bg-warning">
            <vab-icon icon="question-line" />
          </div>
          <div class="stat-info">
            <div class="stat-value">45</div>
            <div class="stat-label">寻找中/待认领</div>
          </div>
        </vab-card>
      </el-col>
      <el-col :span="6">
        <vab-card shadow="hover" class="stat-card">
          <div class="stat-icon bg-success">
            <vab-icon icon="check-line" />
          </div>
          <div class="stat-info">
            <div class="stat-value">128</div>
            <div class="stat-label">已找回/已认领</div>
          </div>
        </vab-card>
      </el-col>
      <el-col :span="6">
        <vab-card shadow="hover" class="stat-card">
          <div class="stat-icon bg-info">
            <vab-icon icon="archive-line" />
          </div>
          <div class="stat-info">
            <div class="stat-value">85%</div>
            <div class="stat-label">寻回率</div>
          </div>
        </vab-card>
      </el-col>
    </el-row>

    <vab-card>
      <vab-query-form>
        <vab-query-form-left-panel>
          <el-form :inline="true" :model="queryForm" @submit.prevent>
            <el-form-item label="物品名称">
              <el-input v-model="queryForm.keyword" placeholder="请输入物品名称" clearable />
            </el-form-item>
            <el-form-item label="类型">
              <el-select v-model="queryForm.type" placeholder="全部" clearable style="width: 120px">
                <el-option label="失物招领" value="found" />
                <el-option label="寻物启事" value="lost" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="queryForm.status" placeholder="全部" clearable style="width: 120px">
                <el-option label="进行中" value="pending" />
                <el-option label="已完成" value="claimed" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"> <vab-icon icon="search-line" /> 查询</el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-left-panel>
        <vab-query-form-right-panel>
          <el-button type="primary" @click="handleAdd"> <vab-icon icon="add-line" /> 发布信息</el-button>
        </vab-query-form-right-panel>
      </vab-query-form>

      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column label="图片" width="100" align="center">
          <template #default="{ row }">
            <el-image 
              style="width: 60px; height: 60px; border-radius: 4px"
              :src="row.image" 
              :preview-src-list="[row.image]"
              fit="cover"
            >
              <template #error>
                <div class="image-slot">
                  <vab-icon icon="image-line" />
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="物品名称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 'found' ? 'success' : 'warning'">
              {{ row.type === 'found' ? '拾取' : '丢失' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="100">
          <template #default="{ row }">
            {{ getCategoryLabel(row.category) }}
          </template>
        </el-table-column>
        <el-table-column prop="location" label="地点" min-width="150" show-overflow-tooltip />
        <el-table-column prop="time" label="时间" width="160" sortable />
        <el-table-column label="联系人" width="150">
          <template #default="{ row }">
            <div>{{ row.contactName }}</div>
            <div class="text-xs text-gray">{{ row.contactPhone }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'pending' ? 'danger' : 'info'">
              {{ row.status === 'pending' ? (row.type === 'found' ? '待认领' : '寻找中') : (row.type === 'found' ? '已认领' : '已找回') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <div v-if="row.status === 'pending'">
              <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="success" size="small" @click="handleComplete(row)">
                {{ row.type === 'found' ? '认领' : '归还' }}
              </el-button>
            </div>
            <span v-else class="text-gray text-xs">已结束</span>
            <el-button v-if="row.status === 'pending'" type="danger" size="small" link @click="handleDelete(row)" class="ml-10">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <vab-pagination
        :current-page="queryForm.pageNo"
        :page-size="queryForm.pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </vab-card>

    <lost-found-dialog ref="dialogRef" @success="handleSuccess" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import LostFoundDialog from './components/LostFoundDialog.vue'

defineOptions({
  name: 'LostAndFound',
})

// --- Data ---
const queryForm = reactive({
  keyword: '',
  type: '',
  status: '',
  pageNo: 1,
  pageSize: 10,
})

const loading = ref(false)
const total = ref(100)
const tableData = ref([])
const dialogRef = ref()

// --- Mock Data ---
const generateMockData = () => {
  return [
    {
      id: 1,
      type: 'found',
      name: '黑色联想笔记本电源适配器',
      category: 'electronics',
      location: '二号书院 201 自习室',
      time: '2026-01-24 10:30:00',
      contactName: '王阿姨',
      contactPhone: '13800138000',
      description: '在自习室最后一排桌子上发现的',
      status: 'pending',
      image: 'https://picsum.photos/200/200?random=1'
    },
    {
      id: 2,
      type: 'lost',
      name: '校园卡 (梁健)',
      category: 'card',
      location: '北区食堂一楼',
      time: '2026-01-23 18:00:00',
      contactName: '梁健',
      contactPhone: '13900139000',
      description: '吃饭时可能落在餐桌上了，卡号尾号 1001',
      status: 'pending',
      image: 'https://picsum.photos/200/200?random=2'
    },
    {
      id: 3,
      type: 'found',
      name: '白色保温杯',
      category: 'living',
      location: '操场看台',
      time: '2026-01-22 16:20:00',
      contactName: '李同学',
      contactPhone: '13700137000',
      description: '象印品牌，有小熊贴纸',
      status: 'claimed',
      image: 'https://picsum.photos/200/200?random=3'
    }
  ]
}

// --- Helpers ---
const getCategoryLabel = (val) => {
  const map = {
    electronics: '电子产品',
    card: '证件卡片',
    book: '书籍资料',
    living: '生活用品',
    clothing: '衣物饰品',
    other: '其他'
  }
  return map[val] || val
}

// --- Methods ---
const handleQuery = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = generateMockData()
    loading.value = false
  }, 500)
}

const handleAdd = () => {
  dialogRef.value.open()
}

const handleEdit = (row) => {
  dialogRef.value.open(row)
}

const handleComplete = (row) => {
  const actionText = row.type === 'found' ? '认领' : '归还'
  ElMessageBox.confirm(`确认该物品已${actionText}吗？`, '确认操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success'
  }).then(() => {
    row.status = 'claimed'
    ElMessage.success('操作成功')
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该条记录吗？', '删除确认', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  })
}

const handleSuccess = (data) => {
  if (data.id) {
    // Edit
    const index = tableData.value.findIndex(item => item.id === data.id)
    if (index !== -1) {
      Object.assign(tableData.value[index], data)
    }
  } else {
    // Add
    tableData.value.unshift({
      id: Date.now(),
      ...data
    })
  }
}

const handleCurrentChange = (val) => {
  queryForm.pageNo = val
  handleQuery()
}
const handleSizeChange = (val) => {
  queryForm.pageSize = val
  handleQuery()
}

onMounted(() => {
  handleQuery()
})
</script>

<style lang="scss" scoped>
.lost-found-container {
  .mb-20 { margin-bottom: 20px; }
  .ml-10 { margin-left: 10px; }
  .text-gray { color: #909399; }
  .text-xs { font-size: 12px; }

  .stat-card {
    :deep(.el-card__body) {
      display: flex;
      align-items: center;
      padding: 20px;
    }

    .stat-icon {
      width: 56px;
      height: 56px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      font-size: 28px;
      color: #fff;
      &.bg-primary { background: var(--el-color-primary); }
      &.bg-success { background: var(--el-color-success); }
      &.bg-warning { background: var(--el-color-warning); }
      &.bg-info { background: #909399; }
    }

    .stat-info {
      .stat-value { font-size: 24px; font-weight: bold; color: #303133; }
      .stat-label { font-size: 13px; color: #909399; margin-top: 5px; }
    }
  }
  
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 20px;
  }
}
</style>
