소스 검색

fix(web-admin): archive dialog loads all brands for required preference

Preselect preferred brand but allow multi-brand qty entry like any mode.

Co-authored-by: Cursor <cursoragent@cursor.com>
zlwu 4 달 전
부모
커밋
07cadc9025
1개의 변경된 파일과 542개의 추가작업 그리고 497개의 파일을 삭제
  1. 542 497
      web-admin/src/components/business/pl-plan-archive-dialog/index.vue

+ 542 - 497
web-admin/src/components/business/pl-plan-archive-dialog/index.vue

@@ -10,12 +10,15 @@
     modal-class="order-module-dialog-mask"
     :close-on-click-modal="false"
     style="backdrop-filter: none"
+    @close="handleClose"
     @closed="handleClosed"
     @opened="handleOpened"
   >
     <div class="pl-arrange-layout">
       <section class="pl-arrange-form-panel">
         <div v-loading="loading" class="pl-arrange-form-scroll">
+          <div ref="feedbackMirrorEl" class="pl-archive-feedback-mirror" />
+
           <section class="pl-plan-form-section">
             <h4 class="pl-plan-subtitle">产品实际数量</h4>
             <PlPlanFormProductTable
@@ -30,7 +33,9 @@
             >
               <div class="pl-archive-brand-qty-head">
                 <span class="pl-archive-brand-qty-title">{{ row.productName }} · 按品牌填量</span>
-                <el-tag v-if="row.brandMode === 'required'" size="small" type="warning">指定品牌</el-tag>
+                <el-tag v-if="row.brandMode === 'required'" size="small" type="warning"
+                  >指定品牌</el-tag
+                >
                 <el-tag v-else size="small" type="info">不限品牌</el-tag>
               </div>
               <BrandQtyChipsField
@@ -38,7 +43,7 @@
                 :brand-mode="archiveBrandMode(row)"
                 :required-brand-id="row.brandId"
                 :brand-options="row.brandOptions || []"
-                :unit="row.unit || '吨'"
+                :unit="resolveProductUnitLabel(row.unit)"
                 variant="admin"
                 :actual-qty="Number(row.actualQty ?? 0)"
                 @update:actual-qty="(val) => onArchiveBrandActualQty(row, val)"
@@ -57,11 +62,10 @@
             <el-form
               v-if="formData.hasFreight === 1"
               :model="formData"
-              label-width="140px"
-              label-position="right"
+              label-position="top"
               class="pl-plan-freight-form"
             >
-              <div class="form-grid-4 pl-plan-archive-freight-grid">
+              <div class="form-grid-5 pl-plan-archive-freight-grid">
                 <el-form-item label="运费计算方式">
                   <el-select v-model="formData.freightType">
                     <el-option label="按重量" value="by_weight" />
@@ -69,11 +73,7 @@
                   </el-select>
                 </el-form-item>
                 <el-form-item label="运输公里数">
-                  <el-input-number
-                    v-model="formData.distanceKm"
-                    :min="0"
-                    :precision="2"
-                  />
+                  <el-input-number v-model="formData.distanceKm" :min="0" :precision="2" />
                 </el-form-item>
                 <el-form-item
                   v-if="formData.freightType === 'by_weight'"
@@ -86,9 +86,6 @@
                     @change="freightCalc.markTransportQtyTouched()"
                   />
                 </el-form-item>
-                <div v-else class="pl-plan-archive-freight-grid-cell" aria-hidden="true" />
-
-                <div class="pl-plan-archive-freight-grid-cell" aria-hidden="true" />
                 <el-form-item
                   v-if="formData.freightType === 'by_weight'"
                   :label="`运输单价(元/${freightUnitLabel})`"
@@ -99,7 +96,6 @@
                     :precision="2"
                   />
                 </el-form-item>
-                <div v-else class="pl-plan-archive-freight-grid-cell" aria-hidden="true" />
                 <el-form-item label="运费金额(元)">
                   <el-input-number
                     v-model="freightCalc.freightAmount.value"
@@ -116,7 +112,16 @@
 
       <section class="pl-arrange-view-panel">
         <h3 class="pl-arrange-view-title">计划单查看</h3>
-        <PlPlanViewTabs v-if="planId" ref="tabsRef" :plan-id="planId" embedded feedback-editable />
+        <PlPlanViewTabs
+          v-if="planId && feedbackMirrorTarget"
+          ref="tabsRef"
+          :plan-id="planId"
+          embedded
+          feedback-editable
+          :arrange-driver-url="driverUrl"
+          :arrange-site-records="siteRecords"
+          :feedback-mirror-to="feedbackMirrorTarget"
+        />
       </section>
     </div>
 
@@ -134,198 +139,229 @@
 </template>
 
 <script setup lang="ts">
-import { Check, Close } from '@element-plus/icons-vue'
-import { fetchProductDetail, type ProductDetail } from '@/api/crm/product'
-import {
-  inboundOrderApi,
-  outboundOrderApi,
-  planApi,
-  transportApi,
-  type Plan,
-  type PlanArchiveBody,
-  type PlanProduct,
-  type PlIoOrder,
-  type Transport
-} from '@/api/pl'
-import BrandQtyChipsField from '@/components/business/brand-qty-chips-field/index.vue'
-import PlPlanFormProductTable from '@/components/business/pl-plan-form-dialog/PlPlanFormProductTable.vue'
-import PlPlanViewTabs from '@/components/business/pl-plan-view-tabs/index.vue'
-import type { PlanFormProductRow } from '@/composables/usePlContractToPlan'
-import {
-  buildMissingHazardCertReadyMessage,
-  enrichPlanProductsHazardFromCrm
-} from '@/composables/usePlToxicProductCertCheck'
-import { usePlFreightCalc, resolveFreightUnitLabel } from '@/composables/usePlFreightCalc'
-import { useDictStore } from '@/store/modules/dict'
-import { pickBxData } from '@/utils/http/bx'
-
-const props = defineProps<{
-  visible: boolean
-  planId: string
-}>()
-
-const emit = defineEmits<{
-  'update:visible': [value: boolean]
-  success: []
-}>()
-
-const innerVisible = computed({
-  get: () => props.visible,
-  set: value => emit('update:visible', value)
-})
-
-const loading = ref(false)
-const submitLoading = ref(false)
-const tabsRef = ref<InstanceType<typeof PlPlanViewTabs> | null>(null)
-const plan = ref<Partial<Plan>>({})
-const productRows = ref<PlanFormProductRow[]>([])
-
-const formData = reactive({
-  hasFreight: 0,
-  distanceKm: null as number | null,
-  freightType: 'by_weight'
-})
-
-const hasFreightRef = computed(() => formData.hasFreight)
-const freightTypeRef = computed(() => formData.freightType)
-const freightCalc = usePlFreightCalc({
-  products: productRows,
-  hasFreight: hasFreightRef,
-  freightType: freightTypeRef
-})
-
-const dictStore = useDictStore()
-
-const freightUnitLabel = computed(() => {
-  const unitCode = resolveFreightUnitLabel(productRows.value)
-  return dictStore.getLabel('crm_product_unit', unitCode) || unitCode || '吨'
-})
-
-const isAdjustMode = computed(() => plan.value.archiveStatus === 'archived')
-
-const dialogTitle = computed(() => {
-  const no = plan.value.planNo || ''
-  return isAdjustMode.value
-    ? no
-      ? `调整归档内容 · ${no}`
-      : '调整归档内容'
-    : no
-      ? `运输计划归档 · ${no}`
-      : '运输计划归档'
-})
-
-const submitLabel = computed(() => (isAdjustMode.value ? '确认保存' : '确认归档'))
-
-const brandedProductRows = computed(() =>
-  productRows.value.filter(row => row.brandMode === 'required' || row.brandMode === 'any')
-)
-
-function archiveBrandMode(row: PlanFormProductRow): 'any' | 'required' | null {
-  if (row.brandMode === 'any' || row.brandMode === 'required') return row.brandMode
-  return null
-}
-
-function brandQtySum(row: PlanFormProductRow): number {
-  return (row.brandQtyRows || []).reduce((sum, item) => sum + Number(item.qty || 0), 0)
-}
-
-function isBrandQtySumMatch(row: PlanFormProductRow): boolean {
-  if (!row.brandMode) return true
-  return Math.abs(brandQtySum(row) - Number(row.actualQty ?? 0)) < 0.0005
-}
-
-function onArchiveBrandActualQty(row: PlanFormProductRow, val: number) {
-  // any:合计回写实际数量;required:实际数量可在产品表改,芯片数量跟合计联动
-  if (row.brandMode === 'any') {
-    row.actualQty = Number(val)
-  }
-}
-
-function syncRequiredBrandQty(row: PlanFormProductRow) {
-  if (row.brandMode !== 'required' || !row.brandQtyRows?.length) return
-  row.brandQtyRows[0].qty = Number(row.actualQty ?? 0)
-}
-
-watch(
-  productRows,
-  rows => {
-    rows.forEach(row => {
-      if (row.brandMode === 'required') syncRequiredBrandQty(row)
-    })
-  },
-  { deep: true }
-)
-
-function mapPlanProducts(products: PlanProduct[]): PlanFormProductRow[] {
-  return products.map((item, index) => ({
-    id: item.id,
-    productId: String(item.productId || index),
-    productNo: item.productNo || String(item.productId || index),
-    productName: item.productName || '',
-    brandMode: item.brandMode,
-    brandId: item.brandId,
-    brandName: item.brandName,
-    brandOptions: [],
-    brandQtyRows: [],
-    model: item.model,
-    categoryName: item.categoryName,
-    unit: item.unit || '吨',
-    quantity: Number(item.quantity ?? item.inboundEstimateQty ?? item.outboundEstimateQty ?? 0),
-    actualQty: item.actualQty != null ? Number(item.actualQty) : undefined,
-    packageSpec: item.packageSpec,
-    deliveryMethod: item.deliveryMethod,
-    taxPrice: item.taxPrice != null ? Number(item.taxPrice) : undefined,
-    taxAmount: item.taxAmount != null ? Number(item.taxAmount) : undefined,
-    taxSubtotal: item.taxSubtotal != null ? Number(item.taxSubtotal) : undefined,
-    remark: item.remark,
-    isExplosive: Number(item.isExplosive ?? 0),
-    isToxic: Number(item.isToxic ?? 0)
-  }))
-}
-
-async function initBrandQtyRows(rows: PlanFormProductRow[]) {
-  const needDetailIds = [
-    ...new Set(
-      rows
-        .filter(row => row.brandMode === 'any' && row.productId)
-        .map(row => row.productId)
-    )
-  ]
-  const detailMap = new Map<string, ProductDetail>()
-  await Promise.all(
-    needDetailIds.map(async productId => {
-      try {
-        const res = await fetchProductDetail({ id: productId })
-        const detail = pickBxData<ProductDetail>(res)
-        if (detail?.id) detailMap.set(productId, detail)
-      } catch {
-        // 品牌列表加载失败时保留空行,提交时由后端校验
-      }
-    })
+  import { Check, Close } from '@element-plus/icons-vue'
+  import { fetchProductDetail, type ProductDetail } from '@/api/crm/product'
+  import {
+    inboundOrderApi,
+    outboundOrderApi,
+    planApi,
+    transportApi,
+    type Plan,
+    type PlanArchiveBody,
+    type PlanProduct,
+    type PlIoOrder,
+    type Transport
+  } from '@/api/pl'
+  import BrandQtyChipsField from '@/components/business/brand-qty-chips-field/index.vue'
+  import PlPlanFormProductTable from '@/components/business/pl-plan-form-dialog/PlPlanFormProductTable.vue'
+  import PlPlanViewTabs from '@/components/business/pl-plan-view-tabs/index.vue'
+  import { type PlanFormProductRow } from '@/composables/usePlContractToPlan'
+  import { applyAliasDisplayMeta, buildProductAliasOptions } from '@/utils/crm-product-brand'
+  import { usePlPlanArrangeActions } from '@/composables/usePlPlanArrangeActions'
+  import {
+    buildMissingHazardCertReadyMessage,
+    enrichPlanProductsHazardFromCrm
+  } from '@/composables/usePlToxicProductCertCheck'
+  import { usePlFreightCalc, resolveFreightUnitLabel } from '@/composables/usePlFreightCalc'
+  import { useDictStore } from '@/store/modules/dict'
+  import { pickBxData } from '@/utils/http/bx'
+
+  const props = defineProps<{
+    visible: boolean
+    planId: string
+  }>()
+
+  const emit = defineEmits<{
+    'update:visible': [value: boolean]
+    success: []
+  }>()
+
+  const innerVisible = computed({
+    get: () => props.visible,
+    set: (value) => emit('update:visible', value)
+  })
+
+  const loading = ref(false)
+  const submitLoading = ref(false)
+  const tabsRef = ref<InstanceType<typeof PlPlanViewTabs> | null>(null)
+  const plan = ref<Partial<Plan>>({})
+  const feedbackMirrorEl = ref<HTMLElement | null>(null)
+  /** 仅在弹窗 opened 且镜像节点已挂载后传入,避免 Teleport 目标为空导致 Vue patch 崩溃 */
+  const feedbackMirrorTarget = ref<HTMLElement | null>(null)
+
+  const { driverUrl, siteRecords, resetArrangeActions, loadArrangeActions } =
+    usePlPlanArrangeActions()
+
+  const productRows = ref<PlanFormProductRow[]>([])
+
+  const formData = reactive({
+    hasFreight: 0,
+    distanceKm: null as number | null,
+    freightType: 'by_weight'
+  })
+
+  const hasFreightRef = computed(() => formData.hasFreight)
+  const freightTypeRef = computed(() => formData.freightType)
+  const freightCalc = usePlFreightCalc({
+    products: productRows,
+    hasFreight: hasFreightRef,
+    freightType: freightTypeRef
+  })
+
+  const dictStore = useDictStore()
+
+  const freightUnitLabel = computed(() => {
+    const unitCode = resolveFreightUnitLabel(productRows.value)
+    return dictStore.getLabel('crm_product_unit', unitCode) || unitCode || '吨'
+  })
+
+  function resolveProductUnitLabel(unit?: string) {
+    const code = (unit || '').trim()
+    return dictStore.getLabel('crm_product_unit', code) || code || '吨'
+  }
+
+  const isAdjustMode = computed(() => plan.value.archiveStatus === 'archived')
+
+  const dialogTitle = computed(() => {
+    const no = plan.value.planNo || ''
+    return isAdjustMode.value
+      ? no
+        ? `调整归档内容 · ${no}`
+        : '调整归档内容'
+      : no
+        ? `运输计划归档 · ${no}`
+        : '运输计划归档'
+  })
+
+  const submitLabel = computed(() => (isAdjustMode.value ? '确认保存' : '确认归档'))
+
+  const brandedProductRows = computed(() =>
+    productRows.value.filter((row) => row.brandMode === 'required' || row.brandMode === 'any')
   )
 
-  rows.forEach(row => {
-    const actual = Number(row.actualQty ?? 0)
-    if (row.brandMode === 'required') {
-      const option = {
-        brandId: row.brandId || '',
-        brandName: row.brandName || '指定品牌'
-      }
-      row.brandOptions = option.brandId ? [option] : []
-      row.brandQtyRows = option.brandId
-        ? [{ brandId: option.brandId, brandName: option.brandName, qty: actual }]
-        : []
-      return
+  function archiveBrandMode(row: PlanFormProductRow): 'any' | 'required' | null {
+    if (row.brandMode === 'any' || row.brandMode === 'required') return row.brandMode
+    return null
+  }
+
+  function brandQtySum(row: PlanFormProductRow): number {
+    return (row.brandQtyRows || []).reduce((sum, item) => sum + Number(item.qty || 0), 0)
+  }
+
+  function isBrandQtySumMatch(row: PlanFormProductRow): boolean {
+    if (!row.brandMode) return true
+    return Math.abs(brandQtySum(row) - Number(row.actualQty ?? 0)) < 0.0005
+  }
+
+  function onArchiveBrandActualQty(row: PlanFormProductRow, val: number) {
+    if (row.brandMode === 'any' || row.brandMode === 'required') {
+      row.actualQty = Number(val)
     }
-    if (row.brandMode === 'any') {
+  }
+
+  function mapPlanProducts(products: PlanProduct[]): PlanFormProductRow[] {
+    return products.map((item, index) => ({
+      id: item.id,
+      productId: String(item.productId || index),
+      productNo: item.productNo || String(item.productId || index),
+      productName: item.productName || '',
+      brandMode: item.brandMode,
+      brandId: item.brandId,
+      brandName: item.brandName,
+      brandOptions: [],
+      brandQtyRows: [],
+      model: item.model,
+      categoryName: item.categoryName,
+      unit: item.unit || '吨',
+      quantity: Number(item.quantity ?? item.inboundEstimateQty ?? item.outboundEstimateQty ?? 0),
+      actualQty: item.actualQty != null ? Number(item.actualQty) : undefined,
+      packageSpec: item.packageSpec,
+      deliveryMethod: item.deliveryMethod,
+      taxRate: item.taxRate != null ? Number(item.taxRate) : undefined,
+      taxPrice: item.taxPrice != null ? Number(item.taxPrice) : undefined,
+      taxAmount: item.taxAmount != null ? Number(item.taxAmount) : undefined,
+      taxSubtotal: item.taxSubtotal != null ? Number(item.taxSubtotal) : undefined,
+      remark: item.remark,
+      isExplosive: Number(item.isExplosive ?? 0),
+      isToxic: Number(item.isToxic ?? 0)
+    }))
+  }
+
+  /** 归档表单只回填标准名/别名/产品编码,不改动品牌模式(由 initBrandQtyRows 处理) */
+  async function enrichArchiveAliasDisplay(rows: PlanFormProductRow[]) {
+    await Promise.all(
+      rows.map(async (line) => {
+        if (!line?.productId) {
+          line.standardProductName = line?.productName
+          line.aliasName = undefined
+          line.aliasOptions = []
+          return
+        }
+        try {
+          const res = await fetchProductDetail({ id: String(line.productId) })
+          const detail = pickBxData<ProductDetail>(res)
+          if (!detail) return
+          applyAliasDisplayMeta(line, detail)
+          line.aliasOptions = buildProductAliasOptions(detail.aliases)
+          const crmNo = String(detail.productNo || '').trim()
+          if (crmNo) line.productNo = crmNo
+        } catch {
+          line.standardProductName = line.productName
+          line.aliasName = undefined
+          line.aliasOptions = line.aliasOptions || []
+        }
+      })
+    )
+  }
+
+  async function initBrandQtyRows(rows: PlanFormProductRow[]) {
+    const needDetailIds = [
+      ...new Set(
+        rows
+          .filter(
+            (row) =>
+              (row.brandMode === 'any' || row.brandMode === 'required') && row.productId
+          )
+          .map((row) => row.productId)
+      )
+    ]
+    const detailMap = new Map<string, ProductDetail>()
+    await Promise.all(
+      needDetailIds.map(async (productId) => {
+        try {
+          const res = await fetchProductDetail({ id: productId })
+          const detail = pickBxData<ProductDetail>(res)
+          if (detail?.id) detailMap.set(productId, detail)
+        } catch {
+          // 提交时由后端校验
+        }
+      })
+    )
+
+    rows.forEach((row) => {
+      const actual = Number(row.actualQty ?? 0)
+      if (row.brandMode !== 'any' && row.brandMode !== 'required') return
+
       const brands = (detailMap.get(row.productId)?.brands || []).filter(
-        b => (b.status || 'on') === 'on'
+        (b) => (b.status || 'on') === 'on'
       )
-      row.brandOptions = brands.map(b => ({
+      row.brandOptions = brands.map((b) => ({
         brandId: b.id || '',
         brandName: b.brandName || ''
       }))
-      // 芯片交互:默认不预选;仅单品牌时预填实际数量
+
+      if (row.brandMode === 'required' && row.brandId) {
+        const name =
+          row.brandName ||
+          row.brandOptions.find((o) => o.brandId === row.brandId)?.brandName ||
+          '指定品牌'
+        if (!row.brandOptions.some((o) => o.brandId === row.brandId)) {
+          row.brandOptions = [{ brandId: row.brandId, brandName: name }, ...row.brandOptions]
+        }
+        row.brandQtyRows = [{ brandId: row.brandId, brandName: name, qty: actual }]
+        return
+      }
+
       if (row.brandOptions.length === 1) {
         row.brandQtyRows = [
           {
@@ -338,343 +374,352 @@ async function initBrandQtyRows(rows: PlanFormProductRow[]) {
       } else {
         row.brandQtyRows = []
       }
+    })
+  }
+
+  function resetState() {
+    plan.value = {}
+    productRows.value = []
+    Object.assign(formData, {
+      hasFreight: 0,
+      distanceKm: null,
+      freightType: 'by_weight'
+    })
+    freightCalc.resetFreightCalc()
+    resetArrangeActions()
+  }
+
+  async function applyFreightPrefill(data: Plan) {
+    formData.hasFreight = data.hasFreight ?? 0
+    freightCalc.resetFreightCalc()
+
+    if (data.freightAmount != null && data.hasFreight === 1) {
+      freightCalc.freightAmount.value = Number(data.freightAmount)
+      freightCalc.freightAmountTouched.value = true
     }
-  })
-}
 
-function resetState() {
-  plan.value = {}
-  productRows.value = []
-  Object.assign(formData, {
-    hasFreight: 0,
-    distanceKm: null,
-    freightType: 'by_weight'
-  })
-  freightCalc.resetFreightCalc()
-}
+    if (!data.transportId) return
 
-async function applyFreightPrefill(data: Plan) {
-  formData.hasFreight = data.hasFreight ?? 0
-  freightCalc.resetFreightCalc()
+    try {
+      const transportRes = await transportApi.get(data.transportId)
+      const transport = pickBxData<Transport>(transportRes)
+      formData.distanceKm = transport.distanceKm != null ? Number(transport.distanceKm) : null
+      formData.freightType = transport.freightType || 'by_weight'
 
-  if (data.freightAmount != null && data.hasFreight === 1) {
-    freightCalc.freightAmount.value = Number(data.freightAmount)
-    freightCalc.freightAmountTouched.value = true
+      // 首次归档时运输量仅按实际数量汇总,不回填安排运输阶段可能基于计划数量的运输量
+      if (isAdjustMode.value && transport.transportQty != null) {
+        freightCalc.transportQty.value = Number(transport.transportQty)
+        freightCalc.transportQtyTouched.value = true
+      }
+      if (transport.freightPrice != null) {
+        freightCalc.freightPrice.value = Number(transport.freightPrice)
+      }
+      if (transport.freightAmount != null) {
+        freightCalc.freightAmount.value = Number(transport.freightAmount)
+        freightCalc.freightAmountTouched.value = true
+      }
+    } catch {
+      // 回退计划主表冗余字段
+    }
+  }
+
+  async function handleOpened() {
+    if (!props.planId) return
+    loading.value = true
+    resetState()
+    await nextTick()
+    feedbackMirrorTarget.value = feedbackMirrorEl.value
+    try {
+      const res = await planApi.get(props.planId)
+      const data = pickBxData<Plan>(res)
+      if (!data?.id) {
+        throw new Error('运输计划数据无效')
+      }
+      plan.value = data
+      const rawProducts = Array.isArray(data.products) ? data.products : []
+      const enrichedProducts = await enrichPlanProductsHazardFromCrm(rawProducts)
+      productRows.value = mapPlanProducts(enrichedProducts)
+      await enrichArchiveAliasDisplay(productRows.value)
+      // 入库/出库单实际数量预填归档表单(归档提交时后端也会再同步一次)
+      if (data.planType === 'inbound' || data.planType === 'outbound') {
+        try {
+          const api = data.planType === 'inbound' ? inboundOrderApi : outboundOrderApi
+          const ioRes = await api.getByPlan(data.id)
+          const io = pickBxData<PlIoOrder | null>(ioRes)
+          if (io && io.status !== 'voided' && Array.isArray(io.items)) {
+            const qtyMap = new Map(
+              io.items
+                .filter((it) => it.planProductId && it.actualQty != null)
+                .map((it) => [it.planProductId, Number(it.actualQty)])
+            )
+            productRows.value = productRows.value.map((row) => {
+              if (!row.id || !qtyMap.has(row.id)) return row
+              return { ...row, actualQty: qtyMap.get(row.id) }
+            })
+          }
+        } catch {
+          // 无入库/出库单时保持计划原实际数量
+        }
+      }
+      await initBrandQtyRows(productRows.value)
+      await applyFreightPrefill(data)
+      await loadArrangeActions(props.planId)
+    } catch (error) {
+      innerVisible.value = false
+      const message = error instanceof Error ? error.message : '加载运输计划失败'
+      ElMessage.error(message.includes('加载') ? message : `加载运输计划失败:${message}`)
+    } finally {
+      loading.value = false
+    }
   }
 
-  if (!data.transportId) return
+  /** 关闭动画开始前先卸掉 Teleport,避免 destroy-on-close 与镜像目标同帧销毁触发 Vue patch 崩溃 */
+  function handleClose() {
+    feedbackMirrorTarget.value = null
+  }
 
-  try {
-    const transportRes = await transportApi.get(data.transportId)
-    const transport = pickBxData<Transport>(transportRes)
-    formData.distanceKm = transport.distanceKm != null ? Number(transport.distanceKm) : null
-    formData.freightType = transport.freightType || 'by_weight'
+  function handleClosed() {
+    feedbackMirrorTarget.value = null
+    resetState()
+  }
 
-    // 首次归档时运输量仅按实际数量汇总,不回填安排运输阶段可能基于计划数量的运输量
-    if (isAdjustMode.value && transport.transportQty != null) {
-      freightCalc.transportQty.value = Number(transport.transportQty)
-      freightCalc.transportQtyTouched.value = true
+  async function handleSubmit() {
+    if (!productRows.value.length) {
+      ElMessage.warning('暂无产品明细')
+      return
     }
-    if (transport.freightPrice != null) {
-      freightCalc.freightPrice.value = Number(transport.freightPrice)
+    if (productRows.value.some((row) => !row.id)) {
+      ElMessage.error('产品明细缺少行 ID,无法提交')
+      return
     }
-    if (transport.freightAmount != null) {
-      freightCalc.freightAmount.value = Number(transport.freightAmount)
-      freightCalc.freightAmountTouched.value = true
+    if (productRows.value.some((row) => row.actualQty == null || Number(row.actualQty) < 0)) {
+      ElMessage.warning('请填写有效的实际数量')
+      return
     }
-  } catch {
-    // 回退计划主表冗余字段
-  }
-}
-
-async function handleOpened() {
-  if (!props.planId) return
-  loading.value = true
-  resetState()
-  try {
-    const res = await planApi.get(props.planId)
-    const data = pickBxData<Plan>(res)
-    if (!data?.id) {
-      throw new Error('运输计划数据无效')
+    const brandMismatch = brandedProductRows.value.find((row) => !isBrandQtySumMatch(row))
+    if (brandMismatch) {
+      ElMessage.warning(`「${brandMismatch.productName}」各品牌数量合计须等于实际数量`)
+      return
     }
-    plan.value = data
-    const rawProducts = Array.isArray(data.products) ? data.products : []
-    const enrichedProducts = await enrichPlanProductsHazardFromCrm(rawProducts)
-    productRows.value = mapPlanProducts(enrichedProducts)
-    // 入库/出库单实际数量预填归档表单(归档提交时后端也会再同步一次)
-    if (data.planType === 'inbound' || data.planType === 'outbound') {
-      try {
-        const api = data.planType === 'inbound' ? inboundOrderApi : outboundOrderApi
-        const ioRes = await api.getByPlan(data.id)
-        const io = pickBxData<PlIoOrder | null>(ioRes)
-        if (io && io.status !== 'voided' && Array.isArray(io.items)) {
-          const qtyMap = new Map(
-            io.items
-              .filter(it => it.planProductId && it.actualQty != null)
-              .map(it => [it.planProductId, Number(it.actualQty)])
-          )
-          productRows.value = productRows.value.map(row => {
-            if (!row.id || !qtyMap.has(row.id)) return row
-            return { ...row, actualQty: qtyMap.get(row.id) }
-          })
-        }
-      } catch {
-        // 无入库/出库单时保持计划原实际数量
-      }
+    if (
+      formData.hasFreight === 1 &&
+      formData.freightType === 'by_weight' &&
+      (!freightCalc.transportQty.value || Number(freightCalc.transportQty.value) <= 0)
+    ) {
+      ElMessage.warning('运输量须大于0,请填写产品实际数量')
+      return
     }
-    await initBrandQtyRows(productRows.value)
-    await applyFreightPrefill(data)
-  } catch (error) {
-    innerVisible.value = false
-    const message = error instanceof Error ? error.message : '加载运输计划失败'
-    ElMessage.error(message.includes('加载') ? message : `加载运输计划失败:${message}`)
-  } finally {
-    loading.value = false
-  }
-}
-
-function handleClosed() {
-  resetState()
-}
-
-async function handleSubmit() {
-  if (!productRows.value.length) {
-    ElMessage.warning('暂无产品明细')
-    return
-  }
-  if (productRows.value.some(row => !row.id)) {
-    ElMessage.error('产品明细缺少行 ID,无法提交')
-    return
-  }
-  if (productRows.value.some(row => row.actualQty == null || Number(row.actualQty) < 0)) {
-    ElMessage.warning('请填写有效的实际数量')
-    return
-  }
-  const brandMismatch = brandedProductRows.value.find(row => !isBrandQtySumMatch(row))
-  if (brandMismatch) {
-    ElMessage.warning(`「${brandMismatch.productName}」各品牌数量合计须等于实际数量`)
-    return
-  }
-  if (
-    formData.hasFreight === 1 &&
-    formData.freightType === 'by_weight' &&
-    (!freightCalc.transportQty.value || Number(freightCalc.transportQty.value) <= 0)
-  ) {
-    ElMessage.warning('运输量须大于0,请填写产品实际数量')
-    return
-  }
-  if (formData.hasFreight === 1 && !plan.value.transportId) {
-    ElMessage.warning('计划有运输费用但未安排运输,请先安排运输')
-    return
-  }
-
-  if (!isAdjustMode.value) {
-    const certMessage = buildMissingHazardCertReadyMessage(plan.value, productRows.value)
-    if (certMessage) {
-      await ElMessageBox.alert(`${certMessage},请至【危化品证上传】页面操作。`, '无法归档', {
-        type: 'warning'
-      })
+    if (formData.hasFreight === 1 && !plan.value.transportId) {
+      ElMessage.warning('计划有运输费用但未安排运输,请先安排运输')
       return
     }
-  }
 
-  submitLoading.value = true
-  try {
-    const body: PlanArchiveBody = {
-      products: productRows.value.map(row => ({
-        id: row.id!,
-        actualQty: Number(row.actualQty ?? 0),
-        brandQtys: row.brandMode
-          ? (row.brandQtyRows || [])
-              .filter(r => Number(r.qty) > 0)
-              .map(r => ({
-                brandId: r.brandId,
-                brandName: r.brandName,
-                qty: Number(r.qty)
-              }))
-          : undefined
-      })),
-      freight: {
-        hasFreight: formData.hasFreight,
-        ...(formData.hasFreight === 1
-          ? {
-              distanceKm: formData.distanceKm ?? undefined,
-              freightType: formData.freightType,
-              freightPrice:
-                formData.freightType === 'by_weight'
-                  ? freightCalc.freightPrice.value ?? undefined
-                  : undefined,
-              freightAmount:
-                freightCalc.calculatedFreight.value || freightCalc.freightAmount.value || undefined,
-              transportQty:
-                formData.freightType === 'by_weight'
-                  ? freightCalc.transportQty.value ?? undefined
-                  : undefined
-            }
-          : {})
+    if (!isAdjustMode.value) {
+      const certMessage = buildMissingHazardCertReadyMessage(plan.value, productRows.value)
+      if (certMessage) {
+        await ElMessageBox.alert(`${certMessage},请至【危化品证上传】页面操作。`, '无法归档', {
+          type: 'warning'
+        })
+        return
       }
     }
 
-    await planApi.archive(props.planId, body)
-    ElMessage.success(isAdjustMode.value ? '保存成功' : '归档成功')
-    tabsRef.value?.reload()
-    emit('success')
-    innerVisible.value = false
-  } catch (e: unknown) {
-    const message = e instanceof Error ? e.message : isAdjustMode.value ? '保存失败' : '归档失败'
-    ElMessage.error(message)
-  } finally {
-    submitLoading.value = false
-  }
-}
+    submitLoading.value = true
+    try {
+      const body: PlanArchiveBody = {
+        products: productRows.value.map((row) => ({
+          id: row.id!,
+          actualQty: Number(row.actualQty ?? 0),
+          brandQtys: row.brandMode
+            ? (row.brandQtyRows || [])
+                .filter((r) => Number(r.qty) > 0)
+                .map((r) => ({
+                  brandId: r.brandId,
+                  brandName: r.brandName,
+                  qty: Number(r.qty)
+                }))
+            : undefined
+        })),
+        freight: {
+          hasFreight: formData.hasFreight,
+          ...(formData.hasFreight === 1
+            ? {
+                distanceKm: formData.distanceKm ?? undefined,
+                freightType: formData.freightType,
+                freightPrice:
+                  formData.freightType === 'by_weight'
+                    ? (freightCalc.freightPrice.value ?? undefined)
+                    : undefined,
+                freightAmount:
+                  freightCalc.calculatedFreight.value ||
+                  freightCalc.freightAmount.value ||
+                  undefined,
+                transportQty:
+                  formData.freightType === 'by_weight'
+                    ? (freightCalc.transportQty.value ?? undefined)
+                    : undefined
+              }
+            : {})
+        }
+      }
+
+      await planApi.archive(props.planId, body)
+      ElMessage.success(isAdjustMode.value ? '保存成功' : '归档成功')
+      tabsRef.value?.reload()
+      emit('success')
+      innerVisible.value = false
+    } catch (e: unknown) {
+      const message = e instanceof Error ? e.message : isAdjustMode.value ? '保存失败' : '归档失败'
+      ElMessage.error(message)
+    } finally {
+      submitLoading.value = false
+    }
+  }
 </script>
 
 <style scoped lang="scss">
-.pl-arrange-layout {
-  display: flex;
-  flex-direction: column;
-  gap: 16px;
-  min-height: 480px;
-}
-
-.pl-arrange-form-panel {
-  flex: 0 0 auto;
-  max-height: 52vh;
-  overflow: hidden;
-}
-
-.pl-arrange-form-scroll {
-  display: flex;
-  flex-direction: column;
-  gap: 20px;
-  max-height: 52vh;
-  overflow-y: auto;
-  padding-right: 4px;
-}
-
-.pl-arrange-view-panel {
-  flex: 1 1 auto;
-  min-height: 280px;
-  display: flex;
-  flex-direction: column;
-  overflow: hidden;
-}
-
-.pl-arrange-view-title {
-  margin: 0 0 12px;
-  font-size: 14px;
-  font-weight: 600;
-  color: var(--section-bar-title-color, var(--primary-dark, #059669));
-}
-
-.pl-plan-subtitle {
-  margin: 0 0 10px;
-  font-size: 13px;
-  font-weight: 600;
-  color: #475569;
-}
-
-.pl-archive-brand-qty-block {
-  margin-top: 12px;
-  padding: 12px;
-  border: 1px solid var(--el-border-color-lighter, #e2e8f0);
-  border-radius: 8px;
-  background: var(--mint-bg-soft, #f8fafc);
-}
-
-.pl-archive-brand-qty-head {
-  display: flex;
-  flex-wrap: wrap;
-  align-items: center;
-  gap: 8px;
-  margin-bottom: 8px;
-}
-
-.pl-archive-brand-qty-title {
-  font-size: 13px;
-  font-weight: 600;
-  color: #334155;
-}
-
-.pl-plan-freight-section {
+  .pl-arrange-layout {
+    display: flex;
+    flex-direction: column;
+    gap: 16px;
+    min-height: 480px;
+  }
+
+  .pl-arrange-form-panel {
+    flex: 0 0 auto;
+    overflow: visible;
+  }
+
+  .pl-arrange-form-scroll {
+    display: flex;
+    flex-direction: column;
+    gap: 20px;
+    overflow: visible;
+
+    /* 禁止子项被压扁:否则 Teleport 回传区高度坍塌,内容叠到产品/运费区块上 */
+    > * {
+      flex: 0 0 auto;
+      min-height: auto;
+    }
+  }
+
+  .pl-archive-feedback-mirror {
+    width: 100%;
+  }
+
+  .pl-arrange-view-panel {
+    flex: 0 0 auto;
+    min-height: 280px;
+    display: flex;
+    flex-direction: column;
+    overflow: visible;
+  }
+
+  .pl-arrange-view-title {
+    margin: 0 0 12px;
+    font-size: 14px;
+    font-weight: 600;
+    color: var(--section-bar-title-color, var(--primary-dark, #059669));
+  }
+
+  .pl-plan-form-section {
+    flex: 0 0 auto;
+    min-width: 0;
+  }
+
   .pl-plan-subtitle {
-    margin-top: 4px;
-    margin-bottom: 0;
-  }
-
-  :deep(.el-form-item__label) {
-    width: 140px !important;
-    max-width: 140px;
-  }
-}
-
-.pl-plan-freight-section-head {
-  display: flex;
-  align-items: center;
-  justify-content: flex-start;
-  gap: 16px;
-  margin-bottom: 10px;
-}
-
-.pl-plan-freight-switch {
-  display: inline-flex;
-  align-items: center;
-  gap: 8px;
-  flex-shrink: 0;
-  cursor: pointer;
-}
-
-.pl-plan-freight-switch-label {
-  font-size: 13px;
-  color: var(--mint-text-muted, #64748b);
-  white-space: nowrap;
-}
-
-.pl-plan-freight-form {
-  :deep(.el-form-item) {
-    margin-bottom: 0;
+    margin: 0 0 10px;
+    font-size: 13px;
+    font-weight: 600;
+    color: #475569;
+  }
+
+  .pl-archive-brand-qty-block {
+    margin-top: 12px;
+    padding: 12px;
+    border: 1px solid var(--el-border-color-lighter, #e2e8f0);
+    border-radius: 8px;
+    background: var(--mint-bg-soft, #f8fafc);
+  }
+
+  .pl-archive-brand-qty-head {
+    display: flex;
+    flex-wrap: wrap;
     align-items: center;
+    gap: 8px;
+    margin-bottom: 8px;
   }
 
-  :deep(.el-form-item__label) {
-    height: auto !important;
-    line-height: 1.4 !important;
-    padding: 0 8px 0 0 !important;
-    justify-content: flex-end;
+  .pl-archive-brand-qty-title {
+    font-size: 13px;
+    font-weight: 600;
+    color: #334155;
   }
 
-  :deep(.el-form-item__content) {
-    flex: 1;
-    min-width: 0;
+  .pl-plan-freight-section {
+    .pl-plan-subtitle {
+      margin-top: 4px;
+      margin-bottom: 0;
+    }
+
+    :deep(.el-form-item__label) {
+      width: 140px !important;
+      max-width: 140px;
+    }
   }
 
-  .pl-plan-archive-freight-grid {
+  .pl-plan-freight-section-head {
+    display: flex;
     align-items: center;
-    row-gap: 12px;
+    justify-content: flex-start;
+    gap: 16px;
+    margin-bottom: 10px;
   }
 
-  .pl-plan-archive-freight-grid-cell {
-    min-height: 1px;
+  .pl-plan-freight-switch {
+    display: inline-flex;
+    align-items: center;
+    gap: 8px;
+    flex-shrink: 0;
+    cursor: pointer;
   }
 
-  :deep(.el-select),
-  :deep(.el-input-number) {
-    width: 100%;
+  .pl-plan-freight-switch-label {
+    font-size: 13px;
+    color: var(--mint-text-muted, #64748b);
+    white-space: nowrap;
   }
-}
 
-.pl-arrange-footer {
-  display: flex;
-  flex-wrap: wrap;
-  gap: 8px;
-  justify-content: flex-end;
-}
+  .pl-plan-freight-form {
+    :deep(.el-form-item) {
+      margin-bottom: 0;
+    }
+
+    :deep(.el-form-item__content) {
+      min-width: 0;
+    }
 
+    .pl-plan-archive-freight-grid {
+      align-items: start;
+    }
+
+    :deep(.el-select),
+    :deep(.el-input-number) {
+      width: 100%;
+    }
+  }
+
+  .pl-arrange-footer {
+    display: flex;
+    flex-wrap: wrap;
+    gap: 8px;
+    justify-content: flex-end;
+  }
 </style>
 
 <style lang="scss">
-.el-dialog.pl-plan-archive-dialog.dialog-form-layout {
-  width: min(1680px, calc(100vw - 80px)) !important;
-  max-height: calc(100vh - 48px);
-}
+  .el-dialog.pl-plan-archive-dialog.dialog-form-layout {
+    width: min(1680px, calc(100vw - 80px)) !important;
+    max-height: calc(100vh - 48px);
+  }
 </style>