Files
shanxia2.0/web-admin/src/components/business/pl-plan-form-dialog/index.vue
T
2026-07-20 10:50:26 +08:00

1203 lines
38 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!-- eslint-disable vue/no-v-model-argument -->
<template>
<el-dialog
v-model="innerVisible"
:title="dialogTitle"
width="1680px"
align-center
destroy-on-close
append-to-body
class="dialog-form-layout pl-plan-form-dialog"
modal-class="order-module-dialog-mask"
:close-on-click-modal="false"
style="backdrop-filter: none"
@closed="handleClosed"
@opened="handleOpened"
>
<div class="pl-plan-form-body">
<section class="pl-plan-form-section">
<h3 class="pl-plan-form-section-title">基础信息</h3>
<el-form ref="basicFormRef" :model="formData" :rules="basicRules" label-position="right" label-width="100px" class="pl-dialog-form">
<div class="form-grid-4">
<el-form-item label="计划日期" prop="planDate">
<el-date-picker
v-model="formData.planDate"
type="date"
placeholder="选择日期"
value-format="YYYY-MM-DD"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="归属公司" prop="belongsCompany">
<el-select v-model="formData.belongsCompany" placeholder="请选择归属公司">
<el-option label="安庆山峡" value="shanxia" />
<el-option label="安徽云栋" value="yundong" />
</el-select>
</el-form-item>
<el-form-item label="单据类型" prop="planType">
<el-select v-model="formData.planType" placeholder="请选择单据类型" style="width: 100%">
<el-option label="直销单" value="direct" />
<el-option label="入库单" value="inbound" />
<el-option label="出库单" value="outbound" />
</el-select>
</el-form-item>
<el-form-item label="跟进人">
<el-input v-model="formData.followUserName" readonly />
</el-form-item>
</div>
</el-form>
</section>
<section class="pl-plan-form-section">
<div class="pl-plan-form-section-head">
<h3 class="pl-plan-form-section-title">合同信息</h3>
<div class="pl-plan-form-section-actions">
<el-button
v-if="contractSnapshot"
class="btn-ghost"
@click="handleViewContract"
>
<el-icon><View /></el-icon>查看合同
</el-button>
<el-button class="btn-main" type="primary" @click="contractSelectorVisible = true">
<el-icon><Search /></el-icon>选择合同
</el-button>
</div>
</div>
<p v-if="!contractSnapshot" class="pl-plan-form-empty-hint">请选择 CRM 合同,系统将自动带入合同与产品信息</p>
<template v-else>
<div class="pl-plan-contract-kv-rows">
<ViewKvTable :fields="contractBasicRow1Fields" mode="triple" />
<ViewKvTable :fields="contractBasicRow2Fields" mode="triple" />
</div>
<h4 class="pl-plan-subtitle">合同产品预览</h4>
<p class="pl-plan-form-empty-hint">点击「选择」将合同产品加入下方产品信息;已添加的产品不可重复选择</p>
<PlPlanFormProductTable
:products="contractProductRows"
show-select
:selected-product-ids="selectedPlanProductIds"
@select="handleSelectContractProduct"
/>
</template>
</section>
<section class="pl-plan-form-section">
<h3 class="pl-plan-form-section-title">产品信息</h3>
<PlPlanFormProductTable
:products="formData.products"
show-delete
editable-remark
editable-qty
@remove="handleRemoveProduct"
/>
</section>
<section class="pl-plan-form-section">
<h3 class="pl-plan-form-section-title">运输信息</h3>
<el-form :model="formData" label-position="right" label-width="100px" class="pl-dialog-form">
<div class="form-grid-4">
<el-form-item label="车牌号">
<el-select
v-model="formData.vehicleId"
placeholder="请选择车牌号"
filterable
clearable
:loading="vehicleLoading"
@change="handleVehicleChange"
>
<el-option
v-for="item in vehicleList"
:key="item.id"
:label="item.licensePlate"
:value="item.id"
/>
</el-select>
</el-form-item>
<el-form-item label="运输公司">
<el-select
v-model="formData.carrierId"
placeholder="请选择运输公司"
filterable
clearable
>
<el-option v-for="c in carrierList" :key="c.id" :label="c.carrierName" :value="c.id" />
</el-select>
</el-form-item>
</div>
<PlVehicleSummaryStrip
v-if="vehicleBundle"
:detail="vehicleBundle.detail"
:personnel-list="vehicleBundle.personnelList"
:carrier-name="summaryCarrierName"
@view="vehicleViewVisible = true"
/>
<div class="pl-plan-logistics-row">
<div class="pl-plan-logistics-block">
<h4 class="pl-plan-subtitle">取货信息</h4>
<div class="form-grid-2">
<el-form-item label="取货地址" class="form-col-span-2">
<PlAddressWithLibrary
v-model="formData.pickupAddress"
v-model:lng="formData.pickupLng"
v-model:lat="formData.pickupLat"
placeholder="取货地址"
/>
</el-form-item>
<el-form-item label="取货时间">
<el-date-picker
v-model="formData.pickupTime"
type="date"
placeholder="选择取货时间"
value-format="YYYY-MM-DD"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="注意事项">
<el-input v-model="formData.pickupNotes" placeholder="取货注意事项" />
</el-form-item>
</div>
</div>
<div class="pl-plan-flow-bridge" aria-hidden="true">
<span class="pl-plan-flow-bridge__label">运输</span>
<span class="pl-plan-flow-bridge__arrow">
<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path
d="M5 12h11.5"
stroke="currentColor"
stroke-width="2.75"
stroke-linecap="round"
/>
<path
d="M13.5 8.5 18.5 12l-5 3.5"
stroke="currentColor"
stroke-width="2.75"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</span>
</div>
<div class="pl-plan-logistics-block">
<h4 class="pl-plan-subtitle">送货信息</h4>
<div class="form-grid-2">
<el-form-item label="送货地址" class="form-col-span-2">
<PlAddressWithLibrary
v-model="formData.destinationAddress"
v-model:lng="formData.destinationLng"
v-model:lat="formData.destinationLat"
placeholder="送货地址"
/>
</el-form-item>
<el-form-item label="送达时间">
<el-date-picker
v-model="formData.deliveryTime"
type="date"
placeholder="选择送达时间"
value-format="YYYY-MM-DD"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="注意事项">
<el-input v-model="formData.destinationNotes" placeholder="送货注意事项" />
</el-form-item>
</div>
</div>
</div>
</el-form>
</section>
<section class="pl-plan-form-section">
<h3 class="pl-plan-form-section-title">备注</h3>
<el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
</section>
</div>
<template #footer>
<div class="dialog-footer">
<el-button @click="innerVisible = false">
<el-icon><Close /></el-icon>取消
</el-button>
<el-button
:type="showSaveAndArrange ? 'default' : 'primary'"
:class="showSaveAndArrange ? 'btn-ghost' : undefined"
:loading="submitLoading"
@click="handleSubmit('save')"
>
<el-icon><Check /></el-icon>{{ saveButtonLabel }}
</el-button>
<el-button
v-if="showSaveAndArrange"
type="primary"
:loading="submitLoading"
@click="handleSubmit('saveAndArrange')"
>
<el-icon><Van /></el-icon>{{ saveAndArrangeLabel }}
</el-button>
</div>
</template>
<ContractSelector
v-model:visible="contractSelectorVisible"
hide-amount
:selectable-statuses="planSelectableContractStatuses"
@confirm="handleContractConfirm"
/>
<ContractDetailDialog v-if="contractDetailDialogActive" ref="contractDetailRef" hide-product-price />
<PlVehicleViewDialog
v-model:visible="vehicleViewVisible"
:vehicle-id="formData.vehicleId"
:bundle="vehicleBundle"
/>
</el-dialog>
</template>
<script setup lang="ts">
import { Check, Close, Search, Van, View } from '@element-plus/icons-vue'
import { getContract } from '@/api/crm/contract'
import type { ContractVO } from '@/api/crm/contract/types'
import { carrierApi, planApi, transportApi, vehicleApi, type Carrier, type Plan, type PlanProduct, type PlanUpdatePayload, type Vehicle, type VehiclePersonnelRow } from '@/api/pl'
import ContractSelector from '@/components/business/contract-selector/index.vue'
import ViewKvTable from '@/components/business/system-view-dialog/ViewKvTable.vue'
import type { ViewField } from '@/components/business/system-view-dialog/types'
import PlVehicleSummaryStrip from '@/components/business/pl-vehicle-summary-strip/index.vue'
import PlVehicleViewDialog from '@/components/business/pl-vehicle-view-dialog/index.vue'
import PlAddressWithLibrary from '@/components/business/pl-address-with-library/index.vue'
import PlPlanFormProductTable from './PlPlanFormProductTable.vue'
import {
applyContractToPlanForm,
mapContractProducts,
type PlanFormProductRow
} from '@/composables/usePlContractToPlan'
import {
buildMissingHazardCertReadyMessage,
enrichPlanProductsHazardFromCrm
} from '@/composables/usePlToxicProductCertCheck'
import { usePlFreightCalc } from '@/composables/usePlFreightCalc'
import { loadVehicleViewBundle, type VehicleViewBundle } from '@/composables/usePlVehicleViewDetail'
import { useDictStore } from '@/store/modules/dict'
import { useUserStore } from '@/store/modules/user'
import { formatDate } from '@/utils/format'
import { pickBxData, pickBxList } from '@/utils/http/bx'
const ContractDetailDialog = defineAsyncComponent(
() => import('@/views/crm/contract/components/ContractDetailDialog.vue')
)
/** 运输计划仅允许关联已审批、执行中的合同 */
const planSelectableContractStatuses = ['approved', 'executing']
const props = defineProps<{
visible: boolean
planId?: string
}>()
const emit = defineEmits<{
'update:visible': [value: boolean]
success: [payload?: { planId: string; openArrange: boolean }]
}>()
const userStore = useUserStore()
const dictStore = useDictStore()
/** 当前登录用户 ID(后端 current-user 返回 id,兼容历史 userId 字段) */
function resolveCurrentUserId() {
const info = userStore.info || ({} as Api.Auth.UserInfo)
const fromInfo = String(info.id || info.userId || '')
if (fromInfo) return fromInfo
const token = userStore.accessToken
if (!token || token.split('.').length < 2) return ''
try {
const payload = token.split('.')[1]
const b64 = payload.replace(/-/g, '+').replace(/_/g, '/')
const pad = '='.repeat((4 - (b64.length % 4)) % 4)
const obj = JSON.parse(atob(b64 + pad))
return String(obj?.sub || '')
} catch {
return ''
}
}
function resolveCurrentUserName() {
const info = userStore.info || ({} as Api.Auth.UserInfo & Record<string, string>)
return info.realName || info.userName || info.username || info.nickName || ''
}
const isEdit = computed(() => !!props.planId)
const dialogTitle = computed(() => (isEdit.value ? '编辑运输计划' : '新增运输计划'))
const showSaveAndArrange = computed(
() => !isEdit.value || loadedTransportStatus.value === 'pending'
)
const saveButtonLabel = computed(() => (isEdit.value ? '保存' : '创建'))
const saveAndArrangeLabel = computed(() =>
isEdit.value ? '保存并安排运输' : '创建并安排运输'
)
const innerVisible = computed({
get: () => props.visible,
set: value => emit('update:visible', value)
})
const submitLoading = ref(false)
const detailLoading = ref(false)
const loadedTransportStatus = ref('pending')
const contractSelectorVisible = ref(false)
const contractDetailDialogActive = ref(false)
const contractDetailRef = ref<InstanceType<typeof ContractDetailDialog>>()
const vehicleViewVisible = ref(false)
const vehicleLoading = ref(false)
const basicFormRef = ref()
const contractSnapshot = ref<ContractVO | null>(null)
const vehicleList = ref<Vehicle[]>([])
const carrierList = ref<Carrier[]>([])
const vehicleBundle = ref<VehicleViewBundle | null>(null)
const selectedDriverId = ref('')
const formData = reactive({
planDate: new Date().toISOString().split('T')[0],
belongsCompany: 'shanxia',
planType: '',
followUserId: '',
followUserName: '',
contractId: '',
contractNo: '',
supplierId: '',
supplierName: '',
destinationId: '',
destinationName: '',
customerId: '',
customerName: '',
contactName: '',
contactPhone: '',
partyA: '',
partyB: '',
contractStartDate: '',
contractEndDate: '',
settlementMethod: '',
hasFreight: 0,
pickupAddress: '',
pickupLng: null as number | null,
pickupLat: null as number | null,
pickupTime: '',
pickupNotes: '',
destinationAddress: '',
destinationLng: null as number | null,
destinationLat: null as number | null,
deliveryTime: '',
destinationNotes: '',
vehicleId: '',
carrierId: '',
distanceKm: null as number | null,
freightType: 'by_weight',
remark: '',
products: [] as PlanFormProductRow[]
})
const basicRules = {
planDate: [{ required: true, message: '请选择计划日期', trigger: 'change' }],
belongsCompany: [{ required: true, message: '请选择归属公司', trigger: 'change' }],
planType: [{ required: true, message: '请选择单据类型', trigger: 'change' }]
}
const productsRef = computed(() => formData.products)
const hasFreightRef = computed(() => formData.hasFreight)
const freightTypeRef = computed(() => formData.freightType)
const freightCalc = usePlFreightCalc({
products: productsRef,
hasFreight: hasFreightRef,
freightType: freightTypeRef
})
const selectedVehicle = computed(() => vehicleList.value.find(item => item.id === formData.vehicleId))
const summaryCarrierName = computed(() => {
const carrier = carrierList.value.find(item => item.id === formData.carrierId)
if (carrier?.carrierName) return carrier.carrierName
return vehicleBundle.value?.detail?.carrierName || ''
})
function buildContractBasicFields(contract: ContractVO): ViewField[] {
const settlementMethod = contract.settlementMethod
return [
{ label: '合同编号', value: contract.contractNo, long: false },
{ label: '合同名称', value: contract.contractName, long: false },
{ label: '签订日期', value: contract.signDate, long: false },
{
label: '合同有效期',
value:
contract.startDate && contract.endDate
? `${contract.startDate} ~ ${contract.endDate}`
: contract.startDate || contract.endDate || '—',
long: false
},
{
label: '结算方式',
value: settlementMethod ? dictStore.getLabel('crm_settlement_method', settlementMethod) : '—',
tagType: settlementMethod ? dictStore.getTagType('crm_settlement_method', settlementMethod) : undefined,
long: false
}
]
}
const contractBasicFieldRows = computed(() => {
const contract = contractSnapshot.value
if (!contract) return { row1: [] as ViewField[], row2: [] as ViewField[] }
const fields = buildContractBasicFields(contract)
return { row1: fields.slice(0, 3), row2: fields.slice(3, 6) }
})
const contractBasicRow1Fields = computed(() => contractBasicFieldRows.value.row1)
const contractBasicRow2Fields = computed(() => contractBasicFieldRows.value.row2)
/** 合同产品预览:固定展示合同原始明细,与下方可编辑的计划产品分离 */
const contractProductRows = computed<PlanFormProductRow[]>(() =>
mapContractProducts(contractSnapshot.value?.products)
)
const selectedPlanProductIds = computed(() =>
formData.products.map(item => String(item.productId))
)
function enrichProductsFromContract(products: PlanFormProductRow[], contract?: ContractVO | null) {
if (!contract?.products?.length) return products
const contractMap = new Map(
contract.products.map(item => [String(item.productId || item.id), item])
)
return products.map(item => {
const contractProduct = contractMap.get(String(item.productId))
if (!contractProduct) return item
return {
...item,
model: item.model || contractProduct.model || contractProduct.productModel,
categoryName: item.categoryName || contractProduct.categoryName,
unit: item.unit || contractProduct.unit || '吨',
taxRate: item.taxRate ?? contractProduct.taxRate,
packageSpec: item.packageSpec || contractProduct.packageSpec,
deliveryMethod: item.deliveryMethod || contractProduct.deliveryMethod,
taxPrice:
item.taxPrice ?? (contractProduct.price != null ? Number(contractProduct.price) : undefined),
taxSubtotal:
item.taxSubtotal ??
(contractProduct.subtotal != null ? Number(contractProduct.subtotal) : undefined),
taxAmount:
item.taxAmount ??
(contractProduct.taxAmount != null ? Number(contractProduct.taxAmount) : undefined)
}
})
}
function mapPlanProductToFormRow(item: PlanProduct, index: number): PlanFormProductRow {
return {
id: item.id,
productId: String(item.productId || index),
productNo: item.productNo || String(item.productId || index),
productName: item.productName || '',
model: item.model,
categoryName: item.categoryName,
unit: item.unit || '吨',
quantity: Number(item.quantity || item.inboundEstimateQty || item.outboundEstimateQty || 0),
actualQty: 0,
packageSpec: item.packageSpec,
deliveryMethod: item.deliveryMethod,
taxRate: undefined,
taxPrice: item.taxPrice ?? item.inboundPrice ?? item.outboundPrice,
taxSubtotal: item.taxSubtotal ?? item.inboundAmount ?? item.outboundAmount,
taxAmount: item.taxAmount,
remark: item.remark,
isExplosive: Number(item.isExplosive ?? (item as { is_explosive?: number }).is_explosive ?? 0),
isToxic: Number(item.isToxic ?? (item as { is_toxic?: number }).is_toxic ?? 0),
purchaseCertUrl: item.purchaseCertUrl,
transportCertUrl: item.transportCertUrl,
legalUseCertUrl: item.legalUseCertUrl
}
}
function mapProductsToSubmitPayload() {
return formData.products.map(item => ({
productId: item.productId,
productNo: item.productNo,
productName: item.productName,
model: item.model,
unit: item.unit,
categoryName: item.categoryName,
packageSpec: item.packageSpec,
deliveryMethod: item.deliveryMethod,
quantity: item.quantity,
actualQty: 0,
taxPrice: item.taxPrice,
taxAmount: item.taxAmount,
taxSubtotal: item.taxSubtotal,
remark: item.remark,
isExplosive: Number(item.isExplosive || 0),
isToxic: Number(item.isToxic || 0),
purchaseCertUrl: item.purchaseCertUrl || undefined,
transportCertUrl: item.transportCertUrl || undefined,
legalUseCertUrl: item.legalUseCertUrl || undefined
}))
}
function buildTransportBlock(options?: { allowClear?: boolean }) {
if (!formData.vehicleId) {
if (!options?.allowClear) return undefined
return {
vehicleId: '',
freightType: formData.freightType
}
}
return {
vehicleId: formData.vehicleId,
driverId: selectedDriverId.value || undefined,
carrierId: formData.carrierId || undefined,
distanceKm: formData.distanceKm ?? undefined,
freightType: formData.freightType,
transportQty:
formData.freightType === 'by_weight' ? freightCalc.transportQty.value ?? undefined : undefined,
freightPrice:
formData.freightType === 'by_weight' ? freightCalc.freightPrice.value ?? undefined : undefined,
freightAmount: freightCalc.freightAmount.value ?? undefined
}
}
function buildPlanCommonPayload(options?: { allowClearTransport?: boolean }): PlanUpdatePayload {
return {
planDate: formData.planDate,
belongsCompany: formData.belongsCompany,
planType: formData.planType,
contractNo: formData.contractNo,
supplierId: formData.supplierId || undefined,
supplierName: formData.supplierName || undefined,
destinationId: formData.destinationId || undefined,
destinationName: formData.destinationName || undefined,
customerId: formData.customerId || undefined,
customerName: formData.customerName || undefined,
contactName: formData.contactName || undefined,
contactPhone: formData.contactPhone || undefined,
partyA: formData.partyA || undefined,
partyB: formData.partyB || undefined,
contractStartDate: formData.contractStartDate || undefined,
contractEndDate: formData.contractEndDate || undefined,
settlementMethod: formData.settlementMethod || undefined,
hasFreight: formData.hasFreight,
pickupAddress: formData.pickupAddress || undefined,
pickupLng: formData.pickupLng,
pickupLat: formData.pickupLat,
pickupTime: formData.pickupTime || undefined,
pickupNotes: formData.pickupNotes || undefined,
destinationAddress: formData.destinationAddress || undefined,
destinationLng: formData.destinationLng,
destinationLat: formData.destinationLat,
deliveryTime: formData.deliveryTime || undefined,
destinationNotes: formData.destinationNotes || undefined,
followUserId: formData.followUserId || undefined,
followUserName: formData.followUserName || undefined,
remark: formData.remark || undefined,
products: mapProductsToSubmitPayload(),
transport: buildTransportBlock({ allowClear: options?.allowClearTransport })
}
}
async function restoreFreightFromTransport(plan: Plan) {
if (!plan.transportId) {
if (plan.freightAmount) {
freightCalc.freightAmount.value = Number(plan.freightAmount)
}
return
}
try {
const transportRes = await transportApi.get(plan.transportId)
const transport = (transportRes.data ?? transportRes) as {
distanceKm?: number
freightType?: string
freightPrice?: number
transportQty?: number
freightAmount?: number
carrierId?: string
driverId?: string
}
formData.distanceKm = transport.distanceKm != null ? Number(transport.distanceKm) : null
formData.freightType = transport.freightType || 'by_weight'
if (transport.carrierId) {
formData.carrierId = transport.carrierId
}
if (transport.driverId) {
selectedDriverId.value = transport.driverId
}
freightCalc.freightPrice.value =
transport.freightPrice != null ? Number(transport.freightPrice) : null
freightCalc.freightAmount.value =
transport.freightAmount != null ? Number(transport.freightAmount) : null
freightCalc.freightAmountTouched.value = false
} catch {
if (plan.freightAmount) {
freightCalc.freightAmount.value = Number(plan.freightAmount)
}
}
}
function resetForm() {
loadedTransportStatus.value = 'pending'
contractSnapshot.value = null
vehicleBundle.value = null
selectedDriverId.value = ''
Object.assign(formData, {
planDate: new Date().toISOString().split('T')[0],
belongsCompany: 'shanxia',
planType: '',
followUserId: resolveCurrentUserId(),
followUserName: resolveCurrentUserName(),
contractId: '',
contractNo: '',
supplierId: '',
supplierName: '',
destinationId: '',
destinationName: '',
customerId: '',
customerName: '',
contactName: '',
contactPhone: '',
partyA: '',
partyB: '',
contractStartDate: '',
contractEndDate: '',
settlementMethod: '',
hasFreight: 0,
pickupAddress: '',
pickupLng: null as number | null,
pickupLat: null as number | null,
pickupTime: '',
pickupNotes: '',
destinationAddress: '',
destinationLng: null as number | null,
destinationLat: null as number | null,
deliveryTime: '',
destinationNotes: '',
vehicleId: '',
carrierId: '',
distanceKm: null,
freightType: 'by_weight',
remark: '',
products: []
})
freightCalc.resetFreightCalc()
basicFormRef.value?.clearValidate()
}
function handleOpened() {
loadMasterData().then(async () => {
if (props.planId) {
await loadPlanForEdit(props.planId)
} else {
resetForm()
}
})
}
async function loadPlanForEdit(planId: string) {
detailLoading.value = true
try {
resetForm()
const res = await planApi.get(planId)
const data = (res.data ?? res) as Plan
Object.assign(formData, {
planDate: data.planDate,
belongsCompany: data.belongsCompany,
planType: data.planType,
followUserId: data.followUserId || resolveCurrentUserId(),
followUserName: data.followUserName || resolveCurrentUserName(),
contractId: data.contractId || '',
contractNo: data.contractNo || '',
supplierId: data.supplierId || '',
supplierName: data.supplierName || '',
destinationId: data.destinationId || '',
destinationName: data.destinationName || '',
customerId: data.customerId || '',
customerName: data.customerName || '',
contactName: data.contactName || '',
contactPhone: data.contactPhone || '',
partyA: data.partyA || '',
partyB: data.partyB || '',
contractStartDate: data.contractStartDate || '',
contractEndDate: data.contractEndDate || '',
settlementMethod: data.settlementMethod || '',
hasFreight: data.hasFreight ?? 0,
pickupAddress: data.pickupAddress || '',
pickupLng: data.pickupLng != null ? Number(data.pickupLng) : null,
pickupLat: data.pickupLat != null ? Number(data.pickupLat) : null,
pickupTime: formatDate(data.pickupTime) || '',
pickupNotes: data.pickupNotes || '',
destinationAddress: data.destinationAddress || '',
destinationLng: data.destinationLng != null ? Number(data.destinationLng) : null,
destinationLat: data.destinationLat != null ? Number(data.destinationLat) : null,
deliveryTime: formatDate(data.deliveryTime) || '',
destinationNotes: data.destinationNotes || '',
vehicleId: data.vehicleId || '',
remark: data.remark || '',
products: (data.products || []).map(mapPlanProductToFormRow)
})
loadedTransportStatus.value = data.transportStatus || 'pending'
if (data.contractId) {
try {
const contractRes = await getContract(data.contractId)
contractSnapshot.value = (contractRes.data ?? contractRes) as ContractVO
} catch {
contractSnapshot.value = buildContractSnapshotFromPlan(data)
}
}
formData.products = await enrichPlanProductsHazardFromCrm(
enrichProductsFromContract(formData.products, contractSnapshot.value)
)
if (data.vehicleId) {
await handleVehicleChange(data.vehicleId)
}
freightCalc.resetFreightCalc()
await restoreFreightFromTransport(data)
} finally {
detailLoading.value = false
}
}
function buildContractSnapshotFromPlan(plan: Plan): ContractVO {
return {
id: plan.contractId || '',
contractNo: plan.contractNo || '',
contractName: plan.contractNo || '',
customerId: plan.customerId || '',
customerName: plan.customerName || '',
contactName: plan.contactName || '',
contactMobile: plan.contactPhone || '',
contractType: '',
amount: plan.totalAmount || 0,
signDate: '',
startDate: plan.contractStartDate || '',
endDate: plan.contractEndDate || '',
contractPeriod: 0,
status: '',
approvalStatus: '',
contractFile: '',
attachmentFiles: '',
ownerUserId: '',
ownerUserName: '',
receivedAmount: 0,
unreceivedAmount: 0,
invoiceAmount: 0,
uninvoiceAmount: 0,
partyA: plan.partyA || '',
partyAAddress: '',
partyAContact: '',
partyAMobile: '',
supplierName: plan.supplierName,
settlementMethod: plan.settlementMethod,
partyB: plan.partyB || '',
partyBAddress: plan.destinationAddress || '',
partyBContact: plan.contactName || '',
partyBMobile: plan.contactPhone || '',
paymentTerms: '',
deliveryTerms: '',
contractTerms: '',
invalidReason: '',
invalidTime: '',
createTime: '',
remark: plan.remark || '',
products: formData.products as unknown as ContractVO['products']
}
}
function handleClosed() {
resetForm()
}
async function loadMasterData() {
try {
const [vehicleRes, carrierRes] = await Promise.all([
vehicleApi.list({ vehicleStatus: 'available', excludeIneligibleCarrier: true }),
carrierApi.list({ status: '1', page: 1, pageSize: 100 })
])
vehicleList.value = pickBxList<Vehicle>(vehicleRes)
carrierList.value = pickBxList<Carrier>(carrierRes)
} catch {
vehicleList.value = []
carrierList.value = []
}
}
async function handleViewContract() {
const contractId = formData.contractId || contractSnapshot.value?.id
if (!contractId) {
ElMessage.warning('请先选择合同')
return
}
contractDetailDialogActive.value = true
await nextTick()
contractDetailRef.value?.open(contractId)
}
async function handleContractConfirm(contract: ContractVO) {
const mapped = applyContractToPlanForm(contract)
contractSnapshot.value = contract
Object.assign(formData, {
...mapped,
products: [],
followUserId: resolveCurrentUserId(),
followUserName: resolveCurrentUserName()
})
freightCalc.resetFreightCalc()
}
async function handleSelectContractProduct(row: PlanFormProductRow) {
const productId = String(row.productId)
if (formData.products.some(item => String(item.productId) === productId)) {
ElMessage.warning('该产品已添加到运输计划中')
return
}
const [enriched] = await enrichPlanProductsHazardFromCrm(
enrichProductsFromContract([{ ...row }], contractSnapshot.value)
)
formData.products.push(enriched)
freightCalc.resetFreightCalc()
}
function handleRemoveProduct(index: number) {
formData.products.splice(index, 1)
}
function resolveDefaultDriver(personnelList: VehiclePersonnelRow[]) {
const drivers = personnelList.filter(item => item.role === 'driver' && item.personnelId)
const defaultDriver = drivers.find(item => item.isDefault === 1) || drivers[0]
selectedDriverId.value = defaultDriver?.personnelId || ''
}
async function handleVehicleChange(vehicleId: string) {
vehicleBundle.value = null
selectedDriverId.value = ''
if (!vehicleId) {
formData.carrierId = ''
return
}
const vehicle = vehicleList.value.find(item => item.id === vehicleId)
if (vehicle?.carrierId) {
formData.carrierId = vehicle.carrierId
} else {
formData.carrierId = ''
}
vehicleLoading.value = true
try {
vehicleBundle.value = await loadVehicleViewBundle(vehicleId)
if (vehicleBundle.value.detail?.carrierId) {
formData.carrierId = vehicleBundle.value.detail.carrierId
}
resolveDefaultDriver(vehicleBundle.value.personnelList || [])
} finally {
vehicleLoading.value = false
}
}
function validateBusinessRules() {
if (!formData.contractId) {
ElMessage.warning('请选择合同')
return false
}
if (!formData.products.length) {
ElMessage.warning('请至少保留一条产品明细')
return false
}
return true
}
async function handleSubmit(mode: 'save' | 'saveAndArrange' = 'save') {
const valid = await basicFormRef.value?.validate().catch(() => false)
if (!valid || !validateBusinessRules()) return
submitLoading.value = true
try {
const commonPayload = buildPlanCommonPayload({ allowClearTransport: isEdit.value })
let planId = props.planId || ''
if (isEdit.value) {
if (!props.planId) return
await planApi.update(props.planId, commonPayload)
planId = props.planId
ElMessage.success('保存成功')
} else {
const res = await planApi.createFull({
...commonPayload,
contractId: formData.contractId
} as Parameters<typeof planApi.createFull>[0])
const created = pickBxData<Plan>(res)
planId = String(created?.id || '')
if (!planId) {
ElMessage.error('创建成功但未返回计划 ID')
return
}
ElMessage.success('创建成功')
}
let openArrange = false
if (mode === 'saveAndArrange' && planId) {
const detailRes = await planApi.get(planId)
const plan = pickBxData<Plan>(detailRes)
const rawProducts = Array.isArray(plan?.products) ? plan.products : []
const enrichedProducts = await enrichPlanProductsHazardFromCrm(rawProducts)
const certMessage = buildMissingHazardCertReadyMessage(plan, enrichedProducts)
if (certMessage) {
await ElMessageBox.alert(
`${certMessage},请至【危化品证上传】页面操作。`,
'无法安排运输',
{ type: 'warning' }
)
openArrange = false
} else {
openArrange = true
}
}
innerVisible.value = false
emit('success', { planId, openArrange })
} finally {
submitLoading.value = false
}
}
</script>
<style scoped lang="scss">
.pl-plan-form-body {
display: flex;
flex-direction: column;
gap: 16px;
}
.pl-plan-form-section {
padding: 16px;
border: 1px solid #e2e8f0;
border-radius: 10px;
background: #fff;
}
.pl-plan-form-section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.pl-plan-form-section-actions {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.pl-plan-form-section-title {
margin: 0 0 12px;
padding-left: 10px;
font-size: 14px;
font-weight: 600;
color: var(--section-bar-title-color, var(--primary-dark, #059669));
border-left: 3px solid var(--section-bar-border-color, var(--primary, #10b981));
line-height: 1;
}
.pl-plan-form-section-head .pl-plan-form-section-title {
margin-bottom: 0;
}
.pl-plan-subtitle {
margin: 16px 0 10px;
font-size: 13px;
font-weight: 600;
color: #1e293b;
}
.pl-plan-form-empty-hint,
.text-muted {
margin: 0 0 8px;
font-size: 13px;
color: #64748b;
}
.pl-plan-contract-kv-rows {
:deep(.view-kv-table-wrap) {
border-radius: 0;
}
:deep(.view-kv-table-wrap:first-child) {
border-radius: 8px 8px 0 0;
}
:deep(.view-kv-table-wrap:last-child) {
border-radius: 0 0 8px 8px;
border-top: none;
}
:deep(.view-kv-table-wrap:only-child) {
border-radius: 8px;
}
}
.pl-plan-kv-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 10px 16px;
}
.pl-plan-kv-grid-2 {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.pl-plan-kv {
min-width: 0;
}
.pl-plan-kv-span {
grid-column: 1 / -1;
}
.pl-plan-party-row,
.pl-plan-logistics-row {
display: flex;
align-items: stretch;
gap: 0;
margin-top: 8px;
}
.pl-plan-party-row .pl-plan-party-block,
.pl-plan-logistics-row .pl-plan-logistics-block {
flex: 1 1 0;
min-width: 0;
}
.pl-plan-flow-bridge {
flex: 0 0 88px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
padding: 0 8px;
}
.pl-plan-flow-bridge__label {
font-size: 12px;
font-weight: 600;
color: var(--primary-dark, #168f45);
letter-spacing: 0.06em;
padding: 4px 10px;
border-radius: 999px;
background: #e6f8ed;
border: 1px solid #a8e0b8;
line-height: 1.2;
}
.pl-plan-flow-bridge__arrow {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: 50%;
color: var(--primary-dark, #168f45);
background: linear-gradient(145deg, #e6f8ed 0%, #d4f0de 100%);
border: 1px solid #a8e0b8;
box-shadow: 0 2px 8px rgba(28, 168, 81, 0.14);
svg {
width: 22px;
height: 22px;
display: block;
}
}
.pl-plan-kv-grid-party {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
.pl-plan-logistics-block {
padding: 10px 12px;
border: 1px solid #e2e8f0;
border-radius: 8px;
background: #f8fafc;
.pl-plan-subtitle {
margin: 0 0 8px;
}
:deep(.el-form-item) {
margin-bottom: 0;
}
.form-grid-2 {
gap: 8px 12px;
}
}
.pl-plan-party-block {
padding: 12px;
border: 1px solid #e2e8f0;
border-radius: 8px;
background: #f8fafc;
}
.pl-plan-party-title {
margin: 0 0 10px;
font-size: 13px;
font-weight: 600;
color: #1e293b;
}
@media (max-width: 1200px) {
.pl-plan-kv-grid,
.pl-plan-kv-grid-party {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 1100px) {
.pl-plan-party-row,
.pl-plan-logistics-row {
flex-direction: column;
}
.pl-plan-flow-bridge {
flex: 0 0 auto;
flex-direction: row;
gap: 12px;
padding: 8px 0;
}
.pl-plan-flow-bridge__arrow {
transform: rotate(90deg);
}
}
@media (max-width: 768px) {
.pl-plan-kv-grid,
.pl-plan-kv-grid-party {
grid-template-columns: 1fr;
}
}
</style>
<style lang="scss">
.el-dialog.pl-plan-form-dialog.dialog-form-layout {
width: min(1680px, calc(100vw - 80px)) !important;
max-height: var(--dialog-max-height, calc(100vh - 40px));
}
.el-dialog.pl-plan-form-dialog.dialog-form-layout .el-dialog__body {
min-height: min(720px, calc(100vh - 180px));
}
</style>