<template>
  <div class="bedding-order-container">
    <el-row :gutter="20">
      <!-- 左侧商品展示 -->
      <el-col :span="6">
        <vab-card title="商品管理" height="calc(100vh - 400px)">
          <div class="product-list">
            <div 
              v-for="product in productList" 
              :key="product.id" 
              class="product-item"
              :class="{ active: currentProduct?.id === product.id }"
              @click="handleProductClick(product)"
            >
              <el-image :src="product.image" class="product-img" fit="cover" />
              <div class="info">
                <div class="name">{{ product.name }}</div>
                <div class="price">¥ {{ product.price }}</div>
                <div class="stock">库存: {{ product.stock }}</div>
              </div>
              <div class="actions">
                <el-switch v-model="product.isOnSale" size="small" />
              </div>
            </div>
            <el-button class="mt-10 w-full" icon="plus" @click="handleAddProduct"> <vab-icon icon="plus-line" /> 添加商品</el-button>
          </div>
        </vab-card>
      </el-col>

      <!-- 右侧订单管理 -->
      <el-col :span="18">
        <vab-card>
          <template #header>
            <div class="header-box">
              <span>订单管理</span>
              <div class="stats">
                <span class="stat-item">待发货: <span class="text-danger">12</span></span>
                <span class="stat-item">今日销售: <span class="text-success">¥ 3,450</span></span>
              </div>
            </div>
          </template>

          <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.orderNo" placeholder="请输入订单号" clearable />
                </el-form-item>
                <el-form-item label="学生">
                  <el-input v-model="queryForm.student" placeholder="姓名/学号" clearable style="width: 140px" />
                </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="ready" />
                    <el-option label="已完成" value="completed" />
                  </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="handleScan"><vab-icon icon="scan-line" /> 扫码核销</el-button>
            </vab-query-form-right-panel>
          </vab-query-form>

          <el-table v-loading="loading" :data="tableData" border stripe height="calc(100vh - 400px)">
            <el-table-column prop="orderNo" label="订单编号" width="180" fixed />
            <el-table-column prop="productName" label="商品名称" min-width="150" show-overflow-tooltip />
            <el-table-column prop="studentName" label="购买人" width="120">
              <template #default="{ row }">
                <div>{{ row.studentName }}</div>
                <div class="text-xs text-gray">{{ row.studentId }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="100">
              <template #default="{ row }">
                <span class="font-bold">¥ {{ row.amount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="下单时间" width="160" sortable />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button v-if="row.status === 'pending'" type="primary" size="small" @click="handleShip(row)"> <vab-icon icon="ship-line" /> 发货</el-button>
                <el-button v-if="row.status === 'ready'" type="success" size="small" @click="handleVerify(row)"> <vab-icon icon="check-line" /> 核销</el-button>
                <el-button size="small" @click="handleDetail(row)"> <vab-icon icon="info-line" /> 详情</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>
      </el-col>
    </el-row>

    <!-- 详情弹窗 -->
    <order-detail-dialog ref="orderDetailDialogRef" />

    <!-- 添加商品弹窗 -->
    <product-add-dialog ref="productAddDialogRef" @success="handleProductAddSuccess" />
  </div>
</template>

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

defineOptions({
  name: 'BeddingOrder',
})

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

const loading = ref(false)
const total = ref(100)
const tableData = ref([])
const orderDetailDialogRef = ref()
const productAddDialogRef = ref()
const currentProduct = ref(null)

const productList = ref([
  { id: 1, name: '标准卧具包 (男)', price: 450, stock: 120, isOnSale: true, image: 'https://picsum.photos/100/100?random=1' },
  { id: 2, name: '标准卧具包 (女)', price: 450, stock: 85, isOnSale: true, image: 'https://picsum.photos/100/100?random=2' },
  { id: 3, name: '夏季凉席套装', price: 120, stock: 200, isOnSale: true, image: 'https://picsum.photos/100/100?random=3' },
])

// --- Helpers ---
const getStatusLabel = (status) => {
  const map = { pending: '待发货', ready: '待自提', completed: '已完成' }
  return map[status]
}
const getStatusType = (status) => {
  const map = { pending: 'warning', ready: 'primary', completed: 'success' }
  return map[status]
}

// --- Methods ---
const generateMockData = () => {
  return [
    {
      orderNo: 'WJ20260123001',
      productName: '标准卧具包 (男)',
      productImage: 'https://picsum.photos/100/100?random=1',
      studentName: '梁健',
      studentId: '31901001',
      amount: 450,
      createTime: '2026-01-23 10:00:00',
      status: 'pending',
      verifyCode: '883921'
    },
    {
      orderNo: 'WJ20260123002',
      productName: '标准卧具包 (女)',
      productImage: 'https://picsum.photos/100/100?random=2',
      studentName: '鲁永波',
      studentId: '31901002',
      amount: 450,
      createTime: '2026-01-23 09:30:00',
      status: 'ready',
      verifyCode: '123456'
    },
    {
      orderNo: 'WJ20260122005',
      productName: '夏季凉席套装',
      productImage: 'https://picsum.photos/100/100?random=3',
      studentName: '王应哲',
      studentId: '31901003',
      amount: 120,
      createTime: '2026-01-22 14:00:00',
      status: 'completed',
      verifyCode: '998877'
    }
  ]
}

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

const handleProductClick = (product) => {
  currentProduct.value = product
}

const handleAddProduct = () => {
  productAddDialogRef.value.open()
}

const handleProductAddSuccess = (product) => {
  productList.value.push({
    id: productList.value.length + 1,
    ...product,
  })
}

const handleShip = (row) => {
  ElMessageBox.confirm(`确认对订单 ${row.orderNo} 进行发货/配货操作吗？`, '发货确认').then(() => {
    row.status = 'ready'
    ElMessage.success('发货成功，已通知学生自提')
  })
}

const handleVerify = (row) => {
  ElMessageBox.confirm(`确认核销订单 ${row.orderNo} 吗？`, '核销确认').then(() => {
    row.status = 'completed'
    ElMessage.success('核销成功')
  })
}

const handleScan = () => {
  ElMessage.info('请连接扫码枪或开启摄像头')
}

const handleDetail = (row) => {
  orderDetailDialogRef.value.open(row)
}

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

handleQuery()
</script>

<style lang="scss" scoped>
.bedding-order-container {
  .mb-20 { margin-bottom: 20px; }
  .mt-10 { margin-top: 10px; }
  .w-full { width: 100%; }
  .text-danger { color: var(--el-color-danger); }
  .text-success { color: var(--el-color-success); }
  .text-gray { color: #909399; }
  .text-xs { font-size: 12px; }
  .font-bold { font-weight: bold; }
  .flex { display: flex; }
  .items-center { align-items: center; }

  .product-list {
    height: calc(100vh - 300px);
    overflow-y: auto;
    .product-item {
      display: flex;
      padding: 10px;
      border: 1px solid #eee;
      border-radius: 8px;
      margin-bottom: 10px;
      cursor: pointer;
      transition: all 0.3s;
      
      &.active {
        border-color: var(--el-color-primary);
        background: var(--el-color-primary-light-9);
      }

      .product-img {
        width: 60px;
        height: 60px;
        border-radius: 4px;
        margin-right: 10px;
      }

      .info {
        flex: 1;
        .name { font-size: 14px; font-weight: bold; margin-bottom: 5px; }
        .price { color: var(--el-color-danger); font-weight: bold; }
        .stock { font-size: 12px; color: #999; }
      }

      .actions {
        display: flex;
        align-items: center;
      }
    }
  }

  .header-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .stats {
      font-size: 14px;
      .stat-item {
        margin-left: 20px;
        font-weight: bold;
      }
    }
  }
}
</style>