<script setup lang="ts">
/**
 * 发货大盘 —— 全真实 API 驱动
 * GET /api/shipping 列表 + 详情查看
 */
import { ref, reactive, onMounted } from 'vue'
import { Search, View } from '@element-plus/icons-vue'
import request from '@/api/request'

// ════════════════════════ 列表 ════════════════════════
const loading = ref(false)
const shippingList = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)

const searchForm = reactive({ order_no: '', tracking_no: '' })

const fetchList = async () => {
  loading.value = true
  try {
    const params: Record<string, any> = { page: page.value, size: pageSize.value }
    if (searchForm.order_no) params.order_no = searchForm.order_no
    if (searchForm.tracking_no) params.tracking_no = searchForm.tracking_no
    const data: any = await request.get('/api/shipping', { params })
    shippingList.value = data?.items || []
    total.value = data?.total || 0
  } catch {}
  finally { loading.value = false }
}

const handleSearch = () => { page.value = 1; fetchList() }
const handlePageChange = (p: number) => { page.value = p; fetchList() }
const handleSizeChange = (s: number) => { pageSize.value = s; page.value = 1; fetchList() }

const statusTagType = (s: string) => ({ transit: 'primary', delivered: 'success', pending: 'info' }[s] || 'info')
const statusLabel = (s: string) => ({ transit: '运输中', delivered: '已签收', pending: '待揽收' }[s] || s)

// ════════════════════════ 详情 ════════════════════════
const detailVisible = ref(false)
const detailLoading = ref(false)
const currentShip = ref<any>({})

const openDetail = async (row: any) => {
  detailVisible.value = true
  detailLoading.value = true
  try {
    // 通过订单发货轨迹接口获取含明细的完整数据
    const data: any = await request.get(`/api/shipping/order/${row.order_id}`)
    const matched = (data?.shipments || []).find((s: any) => s.id === row.id)
    currentShip.value = matched || row
  } catch {}
  finally { detailLoading.value = false }
}

// ════════════════════════ Init ════════════════════════
onMounted(fetchList)
</script>

<template>
  <div class="shipping-wrapper">
    <!-- 1. 筛选 -->
    <el-card shadow="never" class="filter-card">
      <div class="filter-wrapper">
        <el-form :inline="true" :model="searchForm" class="filter-form">
          <el-form-item label="订单号">
            <el-input v-model="searchForm.order_no" placeholder="模糊搜索" clearable style="width:180px" @keyup.enter="handleSearch" />
          </el-form-item>
          <el-form-item label="物流单号">
            <el-input v-model="searchForm.tracking_no" placeholder="搜索快递单号" clearable style="width:180px" @keyup.enter="handleSearch" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">检索</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 2. 发货单列表 -->
    <el-card shadow="never" class="table-card">
      <el-table :data="shippingList" v-loading="loading" stripe border style="width:100%" height="calc(100vh - 250px)">
        <el-table-column prop="shipping_no" label="发货单号" width="200" fixed="left">
          <template #default="{ row }"><span class="shipping-id-bold">{{ row.shipping_no }}</span></template>
        </el-table-column>
        <el-table-column prop="order_no" label="关联订单" width="200">
          <template #default="{ row }"><span class="order-id">{{ row.order_no }}</span></template>
        </el-table-column>
        <el-table-column prop="customer_name" label="客户名称" min-width="160" show-overflow-tooltip />
        <el-table-column prop="carrier" label="物流公司" width="140">
          <template #default="{ row }">{{ row.carrier || '-' }}</template>
        </el-table-column>
        <el-table-column prop="tracking_no" label="物流单号" width="180">
          <template #default="{ row }">{{ row.tracking_no || '-' }}</template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="(statusTagType(row.status) as any)" effect="dark" size="small">{{ statusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ship_date" label="发货日期" width="120" align="center" />
        <el-table-column prop="operator_name" label="操作人" width="100" align="center" />
        <el-table-column prop="created_at" label="创建时间" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link :icon="View" @click="openDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        style="margin-top:16px; justify-content:flex-end" background
        layout="total, sizes, prev, pager, next"
        :total="total" :page-size="pageSize" :current-page="page" :page-sizes="[10, 20, 50]"
        @current-change="handlePageChange" @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 3. 发货详情 Drawer -->
    <el-drawer v-model="detailVisible" title="发货单详情" size="550px">
      <div v-loading="detailLoading">
        <template v-if="currentShip.id">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="发货单号"><span class="shipping-id-bold">{{ currentShip.shipping_no }}</span></el-descriptions-item>
            <el-descriptions-item label="关联订单">{{ currentShip.order_no || '-' }}</el-descriptions-item>
            <el-descriptions-item label="客户名称">{{ currentShip.customer_name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="物流公司">{{ currentShip.carrier || '-' }}</el-descriptions-item>
            <el-descriptions-item label="物流单号">{{ currentShip.tracking_no || '-' }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="(statusTagType(currentShip.status) as any)" effect="dark" size="small">{{ statusLabel(currentShip.status) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="发货日期">{{ currentShip.ship_date }}</el-descriptions-item>
            <el-descriptions-item label="操作人">{{ currentShip.operator_name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ currentShip.remark || '-' }}</el-descriptions-item>
          </el-descriptions>

          <el-divider content-position="left">📦 发货明细</el-divider>
          <el-table :data="currentShip.items || []" border stripe style="width:100%">
            <el-table-column prop="sku_code" label="SKU" width="180">
              <template #default="{ row }"><span class="sku-bold">{{ row.sku_code }}</span></template>
            </el-table-column>
            <el-table-column prop="sku_name" label="产品名称" min-width="160" show-overflow-tooltip />
            <el-table-column prop="spec" label="包装规格" width="120">
              <template #default="{ row }">{{ row.spec || '-' }}</template>
            </el-table-column>
            <el-table-column label="发货数量" width="110" align="center">
              <template #default="{ row }">{{ row.shipped_qty }} {{ row.unit || '' }}</template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped>
.shipping-wrapper { display: flex; flex-direction: column; gap: 16px; height: 100%; }
.filter-card { border-radius: 8px; border: none; box-shadow: 0 1px 4px rgba(0,21,41,0.08); }
.filter-wrapper { display: flex; justify-content: space-between; align-items: center; }
.filter-form .el-form-item { margin-bottom: 0; }
.table-card { flex: 1; border-radius: 8px; border: none; box-shadow: 0 1px 4px rgba(0,21,41,0.08); }
.shipping-id-bold { font-family: Consolas, 'Courier New', monospace; font-weight: bold; color: #67c23a; }
.order-id { font-family: Consolas, 'Courier New', monospace; color: #409eff; }
.sku-bold { font-family: Consolas, 'Courier New', monospace; font-weight: bold; color: #409eff; }
</style>
