<script setup lang="ts">
/**
 * 订单管理 —— 全真实 API 驱动
 * 列表 + 开单 + 详情（含发货记录 timeline）+ 安排发货弹窗（防超发）
 */
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { Search, Plus, View, Delete, Van } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import request from '@/api/request'

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

const searchForm = reactive({ keyword: '', shipping_state: '', payment_state: '' })

const fetchOrders = async () => {
  loading.value = true
  try {
    const params: Record<string, any> = { page: page.value, size: pageSize.value }
    if (searchForm.keyword) params.keyword = searchForm.keyword
    if (searchForm.shipping_state) params.shipping_state = searchForm.shipping_state
    if (searchForm.payment_state) params.payment_state = searchForm.payment_state
    const data: any = await request.get('/api/orders', { params })
    orderList.value = data?.items || []
    total.value = data?.total || 0
  } catch {}
  finally { loading.value = false }
}

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

const shippingTagType = (s: string) => ({ pending: 'info', partial: 'warning', shipped: 'success' }[s] || 'info')
const shippingLabel = (s: string) => ({ pending: '待发货', partial: '部分发货', shipped: '已发货' }[s] || s)
const paymentTagType = (s: string) => ({ unpaid: 'danger', partial: 'warning', cleared: 'success' }[s] || 'info')
const paymentLabel = (s: string) => ({ unpaid: '未收款', partial: '部分收款', cleared: '已结清' }[s] || s)
const formatCurrency = (v: number) => `￥${v?.toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`

// ════════════════════════ 订单详情 ════════════════════════
const detailVisible = ref(false)
const detailLoading = ref(false)
const currentOrder = ref<any>({})
const activeDetailTab = ref('items')
const shippingHistory = ref<any[]>([])
const shippingHistoryLoading = ref(false)

const openDetail = async (row: any) => {
  activeDetailTab.value = 'items'
  detailVisible.value = true
  detailLoading.value = true
  shippingHistory.value = []
  try {
    const data: any = await request.get(`/api/orders/${row.id}`)
    currentOrder.value = data
    // 同时加载发货轨迹
    fetchShippingHistory(row.id)
  } catch {}
  finally { detailLoading.value = false }
}

const fetchShippingHistory = async (orderId: string) => {
  shippingHistoryLoading.value = true
  try {
    const data: any = await request.get(`/api/shipping/order/${orderId}`)
    shippingHistory.value = data?.shipments || []
  } catch {}
  finally { shippingHistoryLoading.value = false }
}

// ════════════════════════ 沉浸式开单 ════════════════════════
const createVisible = ref(false)
const createSubmitting = ref(false)
const createFormRef = ref<FormInstance>()
const customerOptions = ref<any[]>([])
const customerLoading = ref(false)

const fetchCustomers = async (q?: string) => {
  customerLoading.value = true
  try {
    const params: Record<string, any> = { page: 1, size: 50 }
    if (q) params.keyword = q
    const data: any = await request.get('/api/customers', { params })
    customerOptions.value = data?.items || []
  } catch {}
  finally { customerLoading.value = false }
}

const skuOptions = ref<any[]>([])
const fetchSkus = async () => {
  try {
    const data: any = await request.get('/api/products/skus', { params: { page: 1, size: 100 } })
    skuOptions.value = data?.items || []
  } catch {}
}

interface OrderRow {
  sku_id: string; sku_name: string; spec: string; unit_price: number
  qty: number; subtotal: number; price_source: string; price_hint: string
}

const orderForm = reactive({ customer_id: '', remark: '', items: [] as OrderRow[] })
const createRules = reactive<FormRules>({ customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }] })
const totalAmount = computed(() => orderForm.items.reduce((s, r) => s + r.subtotal, 0))

const openCreateOrder = async () => {
  orderForm.customer_id = ''; orderForm.remark = ''; orderForm.items = []
  addRow()
  createVisible.value = true
  await fetchCustomers(); await fetchSkus()
  nextTick(() => createFormRef.value?.clearValidate())
}

const addRow = () => {
  orderForm.items.push({ sku_id: '', sku_name: '', spec: '', unit_price: 0, qty: 1, subtotal: 0, price_source: '', price_hint: '' })
}
const removeRow = (idx: number) => {
  if (orderForm.items.length <= 1) { ElMessage.warning('至少保留一个明细行'); return }
  orderForm.items.splice(idx, 1)
}

const handleSkuChange = async (skuId: string, idx: number) => {
  const row = orderForm.items[idx]
  const sku = skuOptions.value.find((s: any) => s.id === skuId)
  if (sku) { row.sku_name = sku.name; row.spec = sku.spec || '' }
  if (!orderForm.customer_id || !skuId) {
    row.unit_price = sku?.standard_price || 0; row.price_source = 'standard'; row.price_hint = '指导价（未选客户）'
    updateSubtotal(idx); return
  }
  try {
    const data: any = await request.get('/api/orders/price/calculate', { params: { customer_id: orderForm.customer_id, sku_id: skuId } })
    row.unit_price = data.unit_price; row.price_source = data.price_source
    row.price_hint = data.price_source === 'history' ? `历史专享价（来自 ${data.last_order_no}）` : '标准指导价'
  } catch { row.unit_price = sku?.standard_price || 0; row.price_source = 'standard'; row.price_hint = '指导价（定价服务异常）' }
  updateSubtotal(idx)
}

const handleCustomerChange = () => { orderForm.items.forEach((r, i) => { if (r.sku_id) handleSkuChange(r.sku_id, i) }) }
const updateSubtotal = (idx: number) => { const r = orderForm.items[idx]; r.subtotal = Math.round(r.qty * r.unit_price * 100) / 100 }

const submitOrder = async () => {
  const valid = await createFormRef.value?.validate().catch(() => false)
  if (!valid) return
  if (!orderForm.items.some(r => r.sku_id)) { ElMessage.warning('请至少添加一个产品明细行'); return }
  if (orderForm.items.some(r => !r.sku_id)) { ElMessage.warning('有未选择产品的明细行'); return }
  createSubmitting.value = true
  try {
    await request.post('/api/orders', {
      customer_id: orderForm.customer_id, remark: orderForm.remark || null,
      items: orderForm.items.map(r => ({ sku_id: r.sku_id, qty: r.qty, unit_price: r.unit_price })),
    })
    ElMessage.success('订单创建成功！'); createVisible.value = false; fetchOrders()
  } catch {}
  finally { createSubmitting.value = false }
}

// ════════════════════════ 安排发货 ════════════════════════
const shipDialogVisible = ref(false)
const shipSubmitting = ref(false)
const shipFormRef = ref<FormInstance>()
const shipOrder = ref<any>({})

interface ShipRow {
  order_item_id: string; sku_id: string; sku_code: string; sku_name: string
  qty: number; shipped_qty: number; remaining: number; ship_qty: number
  overLimit: boolean
}

const shipForm = reactive({
  carrier: '',
  tracking_no: '',
  remark: '',
  items: [] as ShipRow[],
})

const canSubmitShip = computed(() => {
  return shipForm.items.some(r => r.ship_qty > 0) && !shipForm.items.some(r => r.overLimit)
})

const openShipDialog = async (row: any) => {
  // 加载订单详情获取 items
  try {
    const data: any = await request.get(`/api/orders/${row.id}`)
    shipOrder.value = data
    shipForm.carrier = ''
    shipForm.tracking_no = ''
    shipForm.remark = ''
    shipForm.items = (data.items || []).map((item: any) => {
      const remaining = item.qty - (item.shipped_qty || 0)
      return {
        order_item_id: item.id,
        sku_id: item.sku_id,
        sku_code: item.sku_code,
        sku_name: item.sku_name,
        qty: item.qty,
        shipped_qty: item.shipped_qty || 0,
        remaining,
        ship_qty: remaining > 0 ? remaining : 0,
        overLimit: false,
      }
    })
    shipDialogVisible.value = true
  } catch {}
}

const validateShipQty = (idx: number) => {
  const row = shipForm.items[idx]
  row.overLimit = row.ship_qty > row.remaining || row.ship_qty < 0
}

const submitShipping = async () => {
  const activeItems = shipForm.items.filter(r => r.ship_qty > 0)
  if (!activeItems.length) { ElMessage.warning('请至少填写一行发货数量'); return }
  if (shipForm.items.some(r => r.overLimit)) { ElMessage.error('存在超发行，请检查'); return }

  try {
    await ElMessageBox.confirm(
      `确认对订单「${shipOrder.value.order_no}」执行发货？（${activeItems.length} 个明细行）`,
      '发货确认', { type: 'warning' }
    )
  } catch { return }

  shipSubmitting.value = true
  try {
    await request.post('/api/shipping', {
      order_id: shipOrder.value.id,
      carrier: shipForm.carrier || null,
      tracking_no: shipForm.tracking_no || null,
      remark: shipForm.remark || null,
      items: activeItems.map(r => ({
        order_item_id: r.order_item_id,
        sku_id: r.sku_id,
        shipped_qty: r.ship_qty,
      })),
    })
    ElMessage.success('发货成功，库存已同步扣减')
    shipDialogVisible.value = false
    fetchOrders()
    // 如果详情也开着，刷新它
    if (detailVisible.value && currentOrder.value.id === shipOrder.value.id) {
      openDetail(shipOrder.value)
    }
  } catch {}
  finally { shipSubmitting.value = false }
}

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

<template>
  <div class="order-management-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.keyword" placeholder="模糊搜索" clearable style="width:180px" @keyup.enter="handleSearch" />
          </el-form-item>
          <el-form-item label="发货状态">
            <el-select v-model="searchForm.shipping_state" clearable placeholder="全部" style="width:120px">
              <el-option label="待发货" value="pending" /><el-option label="部分发货" value="partial" /><el-option label="已发货" value="shipped" />
            </el-select>
          </el-form-item>
          <el-form-item label="收款状态">
            <el-select v-model="searchForm.payment_state" clearable placeholder="全部" style="width:120px">
              <el-option label="未收款" value="unpaid" /><el-option label="部分收款" value="partial" /><el-option label="已结清" value="cleared" />
            </el-select>
          </el-form-item>
          <el-form-item><el-button type="primary" :icon="Search" @click="handleSearch">检索</el-button></el-form-item>
        </el-form>
        <el-button type="primary" :icon="Plus" size="large" @click="openCreateOrder">新建订单</el-button>
      </div>
    </el-card>

    <!-- 2. 订单列表 -->
    <el-card shadow="never" class="table-card">
      <el-table :data="orderList" v-loading="loading" stripe border style="width:100%" height="calc(100vh - 290px)">
        <el-table-column prop="order_no" label="订单编号" width="200" fixed="left">
          <template #default="{ row }"><span class="order-id-bold">{{ row.order_no }}</span></template>
        </el-table-column>
        <el-table-column prop="customer_name" label="客户名称" min-width="200" show-overflow-tooltip />
        <el-table-column label="订单金额" width="140" align="right">
          <template #default="{ row }"><b style="color:#e6a23c">{{ formatCurrency(row.total_amount) }}</b></template>
        </el-table-column>
        <el-table-column label="发货状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="(shippingTagType(row.shipping_state) as any)" effect="dark" size="small">{{ shippingLabel(row.shipping_state) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="收款状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="(paymentTagType(row.payment_state) as any)" size="small">{{ paymentLabel(row.payment_state) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="order_date" label="下单日期" width="120" align="center" />
        <el-table-column prop="salesperson_name" label="业务员" width="100" align="center" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link :icon="View" @click="openDetail(row)">详情</el-button>
            <el-button type="success" link :icon="Van" @click="openShipDialog(row)" :disabled="row.shipping_state === 'shipped'">发货</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. 沉浸式开单抽屉 ═══════ -->
    <el-drawer v-model="createVisible" title="✨ 新建订单" size="85%" destroy-on-close>
      <el-form ref="createFormRef" :model="orderForm" :rules="createRules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="选择客户" prop="customer_id">
              <el-select v-model="orderForm.customer_id" filterable remote reserve-keyword
                :remote-method="fetchCustomers" :loading="customerLoading" placeholder="搜索客户名称"
                style="width:100%" @change="handleCustomerChange">
                <el-option v-for="c in customerOptions" :key="c.id" :label="c.name" :value="c.id">
                  <span>{{ c.name }}</span><span style="float:right; color:#909399; font-size:12px">{{ c.level }}级</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="备注"><el-input v-model="orderForm.remark" placeholder="订单备注（非必填）" /></el-form-item>
          </el-col>
          <el-col :span="4" style="text-align:right; padding-top:2px">
            <el-statistic title="订单总额" :value="totalAmount" :precision="2" prefix="￥" />
          </el-col>
        </el-row>
        <el-divider content-position="left">📦 订单明细</el-divider>
        <el-table :data="orderForm.items" border style="width:100%">
          <el-table-column type="index" label="#" width="50" />
          <el-table-column label="选择产品" min-width="260">
            <template #default="{ row, $index }">
              <el-select v-model="row.sku_id" filterable placeholder="搜索 SKU / 产品名" style="width:100%"
                @change="(val: string) => handleSkuChange(val, $index)">
                <el-option v-for="s in skuOptions" :key="s.id" :label="`${s.sku_code} — ${s.name}`" :value="s.id">
                  <span>{{ s.sku_code }}</span><span style="margin-left:8px; color:#606266">{{ s.name }}</span>
                  <span style="float:right; color:#909399; font-size:12px">库存:{{ s.stock_qty }}</span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="规格" width="100"><template #default="{ row }">{{ row.spec || '-' }}</template></el-table-column>
          <el-table-column label="单价" width="160">
            <template #default="{ row, $index }">
              <el-input-number v-model="row.unit_price" :min="0" :precision="2" size="small" style="width:120px" @change="updateSubtotal($index)" />
              <el-tooltip v-if="row.price_hint" :content="row.price_hint" placement="top">
                <el-tag :type="row.price_source === 'history' ? 'success' : 'info'" size="small" effect="plain" style="margin-left:4px; cursor:help">
                  {{ row.price_source === 'history' ? '专享' : '指导' }}
                </el-tag>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="120">
            <template #default="{ row, $index }">
              <el-input-number v-model="row.qty" :min="0.01" :precision="2" size="small" style="width:100px" @change="updateSubtotal($index)" />
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120" align="right">
            <template #default="{ row }"><b style="color:#e6a23c">{{ formatCurrency(row.subtotal) }}</b></template>
          </el-table-column>
          <el-table-column label="" width="60">
            <template #default="{ $index }"><el-button type="danger" link :icon="Delete" @click="removeRow($index)" /></template>
          </el-table-column>
        </el-table>
        <el-button type="primary" plain :icon="Plus" style="width:100%; margin-top:12px" @click="addRow">添加产品行</el-button>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button type="primary" size="large" :loading="createSubmitting" @click="submitOrder">
          ✅ 确认开单（总额 {{ formatCurrency(totalAmount) }}）
        </el-button>
      </template>
    </el-drawer>

    <!-- ═══════ 4. 订单详情抽屉（含发货轨迹 tab）═══════ -->
    <el-drawer v-model="detailVisible" title="订单全景详情" size="750px">
      <div v-loading="detailLoading">
        <template v-if="currentOrder.id">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单编号"><span class="order-id-bold">{{ currentOrder.order_no }}</span></el-descriptions-item>
            <el-descriptions-item label="客户">{{ currentOrder.customer_name }}</el-descriptions-item>
            <el-descriptions-item label="业务员">{{ currentOrder.salesperson_name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="下单日期">{{ currentOrder.order_date }}</el-descriptions-item>
            <el-descriptions-item label="订单金额"><b style="color:#e6a23c">{{ formatCurrency(currentOrder.total_amount) }}</b></el-descriptions-item>
            <el-descriptions-item label="已收款">{{ formatCurrency(currentOrder.paid_amount || 0) }}</el-descriptions-item>
            <el-descriptions-item label="发货状态">
              <el-tag :type="(shippingTagType(currentOrder.shipping_state) as any)" effect="dark" size="small">{{ shippingLabel(currentOrder.shipping_state) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="收款状态">
              <el-tag :type="(paymentTagType(currentOrder.payment_state) as any)" size="small">{{ paymentLabel(currentOrder.payment_state) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ currentOrder.remark || '-' }}</el-descriptions-item>
          </el-descriptions>

          <el-tabs v-model="activeDetailTab" style="margin-top:16px">
            <!-- Tab 1: 商品明细 -->
            <el-tab-pane label="📦 商品明细" name="items">
              <el-table :data="currentOrder.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="180" show-overflow-tooltip />
                <el-table-column prop="spec" label="规格" width="100" />
                <el-table-column label="单价" width="110" align="right"><template #default="{ row }">{{ formatCurrency(row.unit_price) }}</template></el-table-column>
                <el-table-column prop="qty" label="订购" width="70" align="center" />
                <el-table-column label="已发" width="70" align="center">
                  <template #default="{ row }">
                    <span :style="{ color: row.shipped_qty >= row.qty ? '#67c23a' : '#e6a23c', fontWeight: 'bold' }">{{ row.shipped_qty }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="小计" width="110" align="right"><template #default="{ row }"><b>{{ formatCurrency(row.sub_total) }}</b></template></el-table-column>
              </el-table>
            </el-tab-pane>

            <!-- Tab 2: 发货记录 -->
            <el-tab-pane label="🚛 发货记录" name="shipping">
              <div v-loading="shippingHistoryLoading">
                <el-empty v-if="!shippingHistory.length" description="暂无发货记录" />
                <el-timeline v-else>
                  <el-timeline-item
                    v-for="ship in shippingHistory" :key="ship.id"
                    :timestamp="ship.ship_date" placement="top"
                    :color="ship.status === 'delivered' ? '#67c23a' : '#409eff'"
                  >
                    <el-card shadow="hover" class="timeline-card">
                      <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px">
                        <span class="order-id-bold">{{ ship.shipping_no }}</span>
                        <el-tag size="small" :type="ship.status === 'delivered' ? 'success' : 'primary'" effect="dark">
                          {{ ship.status === 'delivered' ? '已签收' : '运输中' }}
                        </el-tag>
                      </div>
                      <p style="margin:4px 0; font-size:13px; color:#606266">物流：{{ ship.carrier || '-' }} | 单号：{{ ship.tracking_no || '-' }}</p>
                      <p style="margin:4px 0; font-size:13px; color:#606266">操作人：{{ ship.operator_name || '-' }}</p>
                      <el-table :data="ship.items" border size="small" style="margin-top:8px">
                        <el-table-column prop="sku_code" label="SKU" width="140" />
                        <el-table-column prop="sku_name" label="产品" min-width="130" />
                        <el-table-column prop="spec" label="规格" width="100">
                          <template #default="{ row }">{{ row.spec || '-' }}</template>
                        </el-table-column>
                        <el-table-column label="发货数量" width="100" align="center">
                          <template #default="{ row }">{{ row.shipped_qty }} {{ row.unit || '' }}</template>
                        </el-table-column>
                      </el-table>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-tab-pane>
          </el-tabs>

          <!-- 详情页快速发货按钮 -->
          <div v-if="currentOrder.shipping_state !== 'shipped'" style="margin-top:16px; text-align:right">
            <el-button type="success" :icon="Van" @click="openShipDialog(currentOrder)">安排发货</el-button>
          </div>
        </template>
      </div>
    </el-drawer>

    <!-- ═══════ 5. 安排发货弹窗（防超发）═══════ -->
    <el-dialog v-model="shipDialogVisible" title="🚛 安排发货" width="750px" destroy-on-close>
      <el-alert
        :title="`订单 ${shipOrder.order_no} — ${shipOrder.customer_name}`"
        type="info" show-icon :closable="false" style="margin-bottom:16px"
      />
      <el-form label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="物流公司"><el-input v-model="shipForm.carrier" placeholder="如 德邦物流" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物流单号"><el-input v-model="shipForm.tracking_no" placeholder="快递/物流单号" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注"><el-input v-model="shipForm.remark" placeholder="非必填" /></el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-divider content-position="left">📦 发货明细（防超发校验）</el-divider>
      <el-table :data="shipForm.items" border style="width:100%">
        <el-table-column prop="sku_code" label="SKU" width="160">
          <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 label="购买量" width="80" align="center"><template #default="{ row }">{{ row.qty }}</template></el-table-column>
        <el-table-column label="已发" width="70" align="center">
          <template #default="{ row }"><span style="color:#67c23a; font-weight:bold">{{ row.shipped_qty }}</span></template>
        </el-table-column>
        <el-table-column label="可发余量" width="80" align="center">
          <template #default="{ row }"><span style="color:#e6a23c; font-weight:bold">{{ row.remaining }}</span></template>
        </el-table-column>
        <el-table-column label="本次发货" width="130">
          <template #default="{ row, $index }">
            <el-input-number
              v-model="row.ship_qty"
              :min="0" :max="row.remaining" :precision="2"
              size="small" style="width:110px"
              :class="{ 'over-limit': row.overLimit }"
              @change="validateShipQty($index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.remaining <= 0" type="success" size="small">已发完</el-tag>
            <el-tag v-else-if="row.overLimit" type="danger" size="small">超发!</el-tag>
            <el-tag v-else-if="row.ship_qty > 0" type="primary" size="small" effect="plain">待发</el-tag>
            <el-tag v-else type="info" size="small" effect="plain">跳过</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="shipSubmitting" :disabled="!canSubmitShip" @click="submitShipping">
          确认发货
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.order-management-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); }
.order-id-bold { font-family: Consolas, 'Courier New', monospace; font-weight: bold; color: #409eff; }
.sku-bold { font-family: Consolas, 'Courier New', monospace; font-weight: bold; color: #409eff; }
.timeline-card { border-radius: 6px; }
.timeline-card p { line-height: 1.4; }
.over-limit :deep(.el-input__inner) { color: #f56c6c !important; border-color: #f56c6c !important; }
</style>
