Files
shanxia2.0/web-admin/src/components/business/pl-plan-delivery-section/index.vue
T
2026-09-03 13:50:25 +08:00

809 lines
24 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>
<div class="pl-plan-delivery-section">
<div v-if="tabMode" class="pl-plan-delivery-tabs">
<button
v-for="(delivery, index) in modelValue"
:key="delivery.seq + '-' + index"
type="button"
class="pl-plan-delivery-tab"
:class="{ 'is-active': activeIndex === index }"
@click="activeIndex = index"
>
#{{ delivery.seq || index + 1 }}
{{ delivery.customerName || '未选客户' }}
<span v-if="segmentQtyLabel(delivery)" class="pl-plan-delivery-tab__qty">
{{ segmentQtyLabel(delivery) }}
</span>
</button>
</div>
<div v-else class="pl-plan-delivery-section__toolbar">
<p class="pl-plan-delivery-section__hint">支持多个送货客户;数量不平衡仅告警,可暂存。</p>
</div>
<article
v-for="(delivery, index) in modelValue"
v-show="!tabMode || activeIndex === index"
:key="delivery.seq + '-' + index"
class="pl-plan-delivery-card"
:class="{ 'is-tab-panel': tabMode }"
>
<header v-if="!tabMode" class="pl-plan-delivery-card__head">
<h4 class="pl-plan-delivery-card__title">送货段 #{{ delivery.seq || index + 1 }}</h4>
<div class="pl-plan-delivery-card__actions">
<el-button
v-if="index > 0"
class="btn-ghost"
size="small"
@click="moveDelivery(index, -1)"
>
<el-icon><Top /></el-icon>上移
</el-button>
<el-button
v-if="index < modelValue.length - 1"
class="btn-ghost"
size="small"
@click="moveDelivery(index, 1)"
>
<el-icon><Bottom /></el-icon>下移
</el-button>
<el-button
v-if="modelValue.length > 1"
class="btn-ghost"
size="small"
type="danger"
@click="removeDelivery(index)"
>
<el-icon><Delete /></el-icon>删除
</el-button>
</div>
</header>
<PlPlanContractMultiSelect
v-model="delivery.contracts"
:customer-id="delivery.customerId"
:disabled="!delivery.customerId || isPlInternalCustomerName(delivery.customerName)"
:required="!!delivery.customerId && !isPlInternalCustomerName(delivery.customerName)"
compact-summary
>
<template #toolbar="{ open, disabled, hint, hintWarn }">
<div class="pl-plan-party-select-row">
<el-form-item label="送货客户" required class="pl-plan-party-select-row__customer">
<div class="customer-select-row">
<el-select
:model-value="delivery.customerId"
class="customer-select-row__select"
filterable
remote
clearable
:remote-method="(q) => searchCustomerOptions(q, index)"
:loading="customerOptionsLoading[index]"
placeholder="客户名称/拼音首字母"
@focus="handleCustomerSelectFocus(index)"
@update:model-value="(val) => handleCustomerChange(index, val)"
>
<el-option
v-for="item in customerOptionsByIndex[index] || []"
:key="item.id"
:label="item.customerName"
:value="item.id"
/>
</el-select>
<el-button
text
class="customer-select-row__search"
@click="emit('open-customer-picker', index)"
>
<el-icon><Search /></el-icon>
</el-button>
</div>
</el-form-item>
<el-form-item
v-if="!isPlInternalCustomerName(delivery.customerName)"
label="送货合同"
class="pl-plan-party-select-row__contract"
>
<div class="pl-plan-contract-trigger">
<el-button class="btn-ghost" :disabled="disabled" @click="open">
<el-icon><Search /></el-icon>选择合同
</el-button>
<span
v-if="hint"
class="pl-plan-contract-trigger__hint"
:class="{ 'is-warn': hintWarn }"
>
{{ hint }}
</span>
</div>
</el-form-item>
</div>
</template>
</PlPlanContractMultiSelect>
<div class="form-grid-2">
<el-form-item label="送货时间" required>
<el-date-picker
:model-value="delivery.deliveryTime"
type="date"
placeholder="选择送货时间"
value-format="YYYY-MM-DD"
style="width: 100%"
@update:model-value="patchDelivery(index, { deliveryTime: $event || '' })"
/>
</el-form-item>
<el-form-item label="联系方式">
<el-input
:model-value="delivery.contact"
placeholder="联系方式"
@update:model-value="patchDelivery(index, { contact: $event })"
/>
</el-form-item>
<el-form-item label="送货地址" class="form-col-span-2">
<PlAddressWithLibrary
:model-value="delivery.address"
:lng="delivery.lng"
:lat="delivery.lat"
:contact="delivery.contact"
placeholder="送货地址"
@apply="patchDeliveryAddress(index, $event)"
/>
</el-form-item>
<el-form-item label="注意事项" class="form-col-span-2">
<el-input
:model-value="delivery.notes"
placeholder="送货注意事项"
@update:model-value="patchDelivery(index, { notes: $event })"
/>
</el-form-item>
<el-form-item label="地磅单" class="form-col-span-2">
<div class="pl-plan-dibang-row">
<el-checkbox
:model-value="delivery.generateDibang === 1"
:disabled="readonly || !canManualDibang(delivery.customerName)"
@update:model-value="(checked) => handleDibangToggle(index, checked)"
>
生成地磅单({{ directionLabel(delivery.dibangDirection) }})
</el-checkbox>
<span
v-if="canManualDibang(delivery.customerName)"
class="pl-plan-dibang-row__hint"
>
该车辆地磅单可选,请自行勾选
</span>
<span
v-else-if="isPlInternalCustomerName(delivery.customerName)"
class="pl-plan-dibang-row__hint"
>
本段客户为内部客户时默认勾选
</span>
<span v-else-if="delivery.customerId" class="pl-plan-dibang-row__hint">
仅安庆山峡/安徽云栋可生成地磅单
</span>
</div>
</el-form-item>
</div>
<div class="pl-plan-stop-products-head">
<span class="pl-plan-stop-products-head__title">送货产品</span>
<div v-if="!readonly" class="pl-plan-stop-products-head__actions">
<el-button class="btn-ghost" size="small" @click="emit('sync-products', index)">
<el-icon><Refresh /></el-icon>从装货同步
</el-button>
<span class="pl-plan-stop-products-head__add-wrap" @click="handleSelectProductsClick(index)">
<el-button
class="btn-main"
type="primary"
size="small"
:disabled="selectProductsDisabled(delivery)"
>
<el-icon><Plus /></el-icon>选择产品
</el-button>
</span>
</div>
</div>
<p v-if="showSplitHint" class="pl-plan-delivery-section__split-hint">
多个送货段,请拆分各段数量
</p>
<p
v-if="missingFromLoadHint(delivery)"
class="pl-plan-delivery-section__missing-load-hint"
>
{{ missingFromLoadHint(delivery) }}
</p>
<p v-if="!delivery.products.length" class="pl-plan-delivery-section__empty-hint">
可从装货同步,或点击「选择产品」从合同中添加
</p>
<PlPlanStopProductTable
:products="delivery.products"
:editable="!readonly"
:compact="compactProducts"
:allow-remove="!readonly"
:contract-id="deliveryContractId(delivery)"
:exclude-plan-id="excludePlanId"
@remove="(productIndex) => removeStopProduct(index, productIndex)"
/>
</article>
</div>
</template>
<script setup lang="ts">
import { Bottom, Delete, Plus, Refresh, Search, Top } from '@element-plus/icons-vue'
import { fetchCustomerOptions } from '@/api/crm/customer'
import { customerStopPrefApi, type CustomerStopPref } from '@/api/pl/index'
import PlAddressWithLibrary, {
type PlAddressApplyPayload
} from '@/components/business/pl-address-with-library/index.vue'
import PlPlanContractMultiSelect from '@/components/business/pl-plan-contract-multi-select/index.vue'
import PlPlanStopProductTable from '@/components/business/pl-plan-stop-product-table/index.vue'
import { resolveAddressNotesFill } from '@/utils/pl-address-notes-fill'
import {
canManualToggleStopDibang,
createEmptyDeliveryForm,
resolveStopDibangDefaults,
sumStopProductsPlanQty,
type PlanDeliveryForm,
type PlanStopProductFormRow
} from '@/utils/pl-plan-stop-form'
import { findDeliveryProductsMissingFromLoad } from '@/utils/pl-plan-contract-product'
import { isPlInternalCustomerName } from '@/utils/pl-internal-customer'
import { pickBxData } from '@/utils/http/bx'
const props = withDefaults(
defineProps<{
modelValue: PlanDeliveryForm[]
tabMode?: boolean
readonly?: boolean
compactProducts?: boolean
qtyUnitLabel?: string
/** 多送货段时提示拆分数量 */
showSplitHint?: boolean
excludePlanId?: string
/** 装货段产品,用于「送货产品不在装货列表」软提醒 */
loadProducts?: PlanStopProductFormRow[]
/** 当前计划车牌(主牌),用于地磅可选车例外 */
vehiclePlate?: string
}>(),
{
tabMode: true,
readonly: false,
compactProducts: true,
qtyUnitLabel: '',
showSplitHint: false,
excludePlanId: '',
loadProducts: () => [],
vehiclePlate: ''
}
)
const emit = defineEmits<{
'update:modelValue': [value: PlanDeliveryForm[]]
'open-customer-picker': [index: number]
'sync-products': [index: number]
'select-products': [index: number]
'add-delivery': []
'active-index-change': [index: number]
}>()
interface CustomerOptionRow {
id: string
customerName: string
customerNo?: string
}
const activeIndex = ref(0)
function deliveryContractId(delivery: PlanDeliveryForm) {
return String(delivery.contracts?.[0]?.contractId || '').trim()
}
function selectProductsDisabled(delivery: PlanDeliveryForm) {
if (isPlInternalCustomerName(delivery.customerName)) return false
return !deliveryContractId(delivery)
}
function handleSelectProductsClick(index: number) {
const delivery = props.modelValue[index]
if (!delivery) return
if (selectProductsDisabled(delivery)) {
ElMessage.warning('请先选择送货合同后再选择产品')
return
}
emit('select-products', index)
}
function missingFromLoadHint(delivery: PlanDeliveryForm) {
const names = findDeliveryProductsMissingFromLoad(delivery.products, props.loadProducts)
if (!names.length) return ''
return `注意:产品「${names.join('、')}」不在装货产品列表中,请核对(不影响保存/安排)`
}
const customerOptionsByIndex = ref<Record<number, CustomerOptionRow[]>>({})
const customerOptionsLoading = ref<Record<number, boolean>>({})
watch(
() => props.modelValue.length,
(len) => {
if (activeIndex.value >= len) {
activeIndex.value = Math.max(0, len - 1)
}
}
)
watch(
activeIndex,
(index) => {
emit('active-index-change', index)
},
{ immediate: true }
)
function resequence(list: PlanDeliveryForm[]) {
return list.map((row, index) => ({ ...row, seq: index + 1 }))
}
function patchDelivery(index: number, partial: Partial<PlanDeliveryForm>) {
const next = props.modelValue.map((row, i) => (i === index ? { ...row, ...partial } : row))
emit('update:modelValue', next)
}
function patchDeliveryAddress(index: number, fields: PlAddressApplyPayload) {
const delivery = props.modelValue[index]
const partial: Partial<PlanDeliveryForm> = {
address: fields.address,
lng: fields.lng,
lat: fields.lat
}
if (fields.contact !== undefined) {
partial.contact = fields.contact
}
const nextNotes = resolveAddressNotesFill(delivery?.notes, fields.notes)
if (nextNotes !== undefined) {
partial.notes = nextNotes
}
patchDelivery(index, partial)
}
function removeStopProduct(deliveryIndex: number, productIndex: number) {
const delivery = props.modelValue[deliveryIndex]
if (!delivery) return
patchDelivery(deliveryIndex, {
products: delivery.products.filter((_, i) => i !== productIndex)
})
}
function addDelivery() {
const nextSeq = props.modelValue.length + 1
emit('update:modelValue', resequence([
...props.modelValue,
createEmptyDeliveryForm(nextSeq)
]))
activeIndex.value = props.modelValue.length
emit('add-delivery')
}
function removeDelivery(index: number) {
const next = props.modelValue.filter((_, i) => i !== index)
emit('update:modelValue', resequence(
next.length ? next : [createEmptyDeliveryForm(1)]
))
if (activeIndex.value >= index && activeIndex.value > 0) {
activeIndex.value -= 1
}
}
function moveDelivery(index: number, delta: number) {
const target = index + delta
if (target < 0 || target >= props.modelValue.length) return
const next = [...props.modelValue]
const temp = next[index]
next[index] = next[target]
next[target] = temp
emit('update:modelValue', resequence(next))
if (activeIndex.value === index) {
activeIndex.value = target
} else if (activeIndex.value === target) {
activeIndex.value = index
}
}
function segmentQtyLabel(delivery: PlanDeliveryForm) {
const qty = sumStopProductsPlanQty(delivery.products || [])
if (qty <= 0) return ''
const unit = props.qtyUnitLabel || ''
const text = String(parseFloat(qty.toFixed(3)))
return unit ? `${text}${unit}` : text
}
function directionLabel(direction?: string) {
if (direction === 'outbound') return '出库'
if (direction === 'inbound') return '入库'
return '无'
}
function extractCustomerOptions(res: unknown): CustomerOptionRow[] {
const unwrapped = (res as { data?: unknown })?.data ?? res
if (Array.isArray(unwrapped)) return unwrapped as CustomerOptionRow[]
const payload = (unwrapped as { list?: CustomerOptionRow[]; rows?: CustomerOptionRow[] }) || {}
return payload.list || payload.rows || []
}
function ensureCustomerOption(index: number, customer?: Partial<CustomerOptionRow> | null) {
if (!customer?.id) return
const id = String(customer.id)
const list = customerOptionsByIndex.value[index] || []
const existing = list.find((item) => String(item.id) === id)
if (existing) {
if (!customer.customerName) return
customerOptionsByIndex.value = {
...customerOptionsByIndex.value,
[index]: list.map((item) =>
String(item.id) === id
? {
...item,
customerName: customer.customerName || item.customerName,
customerNo: customer.customerNo || item.customerNo
}
: item
)
}
return
}
customerOptionsByIndex.value = {
...customerOptionsByIndex.value,
[index]: [
{ id, customerName: customer.customerName || '', customerNo: customer.customerNo },
...list
]
}
}
watch(
() => props.modelValue.map((row) => [row.customerId, row.customerName] as const),
(rows) => {
rows.forEach((pair, index) => {
const [customerId, customerName] = pair
if (!customerId) return
ensureCustomerOption(index, {
id: String(customerId),
customerName: customerName || ''
})
})
},
{ immediate: true, deep: true }
)
async function loadDefaultCustomerOptions(
index: number,
customerId?: string,
customerName?: string
) {
customerOptionsLoading.value = { ...customerOptionsLoading.value, [index]: true }
try {
const res = await fetchCustomerOptions({ limit: 20 })
customerOptionsByIndex.value = {
...customerOptionsByIndex.value,
[index]: extractCustomerOptions(res)
}
ensureCustomerOption(index, { id: customerId, customerName })
} finally {
customerOptionsLoading.value = { ...customerOptionsLoading.value, [index]: false }
}
}
async function searchCustomerOptions(query: string, index: number) {
const keyword = query?.trim()
const delivery = props.modelValue[index]
if (!keyword) {
await loadDefaultCustomerOptions(index, delivery?.customerId, delivery?.customerName)
return
}
customerOptionsLoading.value = { ...customerOptionsLoading.value, [index]: true }
try {
const res = await fetchCustomerOptions({ keyword, limit: 50 })
customerOptionsByIndex.value = {
...customerOptionsByIndex.value,
[index]: extractCustomerOptions(res)
}
ensureCustomerOption(index, {
id: delivery?.customerId,
customerName: delivery?.customerName
})
} finally {
customerOptionsLoading.value = { ...customerOptionsLoading.value, [index]: false }
}
}
function handleCustomerSelectFocus(index: number) {
if (!(customerOptionsByIndex.value[index] || []).length) {
const delivery = props.modelValue[index]
loadDefaultCustomerOptions(index, delivery?.customerId, delivery?.customerName)
}
}
function handleCustomerChange(index: number, customerId?: string) {
if (!customerId) {
patchDelivery(index, {
customerId: '',
customerName: '',
contracts: [],
generateDibang: 0,
dibangDirection: 'none',
address: '',
lng: null,
lat: null,
contact: '',
notes: ''
})
return
}
const current = props.modelValue[index]
if (current && String(current.customerId) === String(customerId)) {
ensureCustomerOption(index, { id: customerId, customerName: current.customerName })
return
}
const customer = (customerOptionsByIndex.value[index] || []).find(
(item) => String(item.id) === String(customerId)
)
const customerName = customer?.customerName || ''
const defaults = resolveStopDibangDefaults(customerName, 'delivery', props.vehiclePlate)
patchDelivery(index, {
customerId: String(customerId),
customerName,
contracts: [],
generateDibang: defaults.generateDibang,
dibangDirection: defaults.dibangDirection,
address: '',
lng: null,
lat: null,
contact: '',
notes: ''
})
void applyDeliveryStopPref(index, String(customerId))
}
async function applyDeliveryStopPref(index: number, customerId: string) {
try {
const res = await customerStopPrefApi.get({ customerId, stopType: 'delivery' })
const pref = pickBxData<CustomerStopPref | null>(res)
if (!pref) return
const current = props.modelValue[index]
if (!current || String(current.customerId) !== String(customerId)) return
const partial: Partial<PlanDeliveryForm> = {}
const prefAddress = (pref.address || '').trim()
if (prefAddress) partial.address = prefAddress
if (pref.lng != null) partial.lng = pref.lng
if (pref.lat != null) partial.lat = pref.lat
const prefContact = (pref.contact || '').trim()
if (prefContact) partial.contact = prefContact
const prefNotes = (pref.notes || '').trim()
if (prefNotes) partial.notes = prefNotes
if (Object.keys(partial).length) patchDelivery(index, partial)
} catch {
// 静默:不阻断选客户
}
}
function canManualDibang(customerName?: string | null) {
return canManualToggleStopDibang(customerName, props.vehiclePlate)
}
function handleDibangToggle(index: number, checked: boolean) {
const delivery = props.modelValue[index]
if (!canManualDibang(delivery?.customerName)) {
if (!isPlInternalCustomerName(delivery?.customerName)) {
patchDelivery(index, { generateDibang: 0, dibangDirection: 'none' })
}
return
}
patchDelivery(index, {
generateDibang: checked ? 1 : 0,
dibangDirection: checked ? 'inbound' : 'none'
})
}
function applyCustomerFromPicker(
index: number,
customer: { id: string | number; customerName?: string }
) {
ensureCustomerOption(index, { id: String(customer.id), customerName: customer.customerName })
handleCustomerChange(index, String(customer.id))
}
defineExpose({
applyCustomerFromPicker,
ensureCustomerOption,
loadDefaultCustomerOptions,
addDelivery,
moveDelivery,
removeDelivery
})
</script>
<style scoped lang="scss">
.pl-plan-delivery-section__toolbar {
margin-bottom: 8px;
}
.pl-plan-delivery-section__hint {
margin: 0;
font-size: 12px;
color: #64748b;
}
.pl-plan-delivery-tabs {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-bottom: 8px;
}
.pl-plan-delivery-tab {
border: 1px solid #d9e8e2;
background: #fff;
border-radius: 6px;
padding: 5px 10px;
font-size: 11px;
font-weight: 600;
cursor: pointer;
color: #64748b;
font-family: inherit;
max-width: 100%;
text-align: left;
line-height: 1.35;
&.is-active {
border-color: #7dd3fc;
background: #f0f9ff;
color: #0284c7;
}
&__qty {
margin-left: 4px;
font-weight: 400;
color: #94a3b8;
}
}
.pl-plan-delivery-card {
&.is-tab-panel {
border: none;
padding: 0;
margin: 0;
background: transparent;
}
&:not(.is-tab-panel) {
border: 1px solid #d9e8e2;
border-radius: 10px;
padding: 14px;
margin-bottom: 12px;
background: #fff;
}
}
.pl-plan-delivery-card__head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.pl-plan-delivery-card__title {
margin: 0;
font-size: 13px;
font-weight: 600;
color: #1e293b;
}
.pl-plan-delivery-card__actions {
display: flex;
align-items: center;
gap: 8px;
}
.pl-plan-stop-products-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin: 8px 0 0;
}
.pl-plan-stop-products-head__title {
font-size: 12px;
font-weight: 600;
color: #64748b;
}
.pl-plan-stop-products-head__actions {
display: flex;
align-items: center;
gap: 8px;
}
.pl-plan-stop-products-head__add-wrap {
display: inline-flex;
}
.pl-plan-delivery-section__split-hint {
margin: 6px 0 0;
font-size: 12px;
color: #d97706;
}
.pl-plan-delivery-section__missing-load-hint {
margin: 6px 0 0;
font-size: 12px;
font-weight: 700;
color: #dc2626;
}
.pl-plan-delivery-section__empty-hint {
margin: 6px 0 0;
font-size: 12px;
color: #94a3b8;
}
.pl-plan-dibang-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
}
.pl-plan-dibang-row__hint {
font-size: 12px;
color: #64748b;
}
.customer-select-row {
display: flex;
align-items: center;
gap: 4px;
width: 100%;
}
.customer-select-row__select {
flex: 1 1 auto;
min-width: 0;
}
.pl-plan-party-select-row {
display: flex;
flex-direction: row;
align-items: flex-start;
gap: 12px;
margin-bottom: 8px;
}
.pl-plan-party-select-row__customer {
flex: 1.4 1 0;
min-width: 0;
margin-bottom: 0 !important;
}
.pl-plan-party-select-row__contract {
flex: 1 1 0;
min-width: 120px;
margin-bottom: 0 !important;
}
.pl-plan-contract-trigger {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
min-height: 32px;
}
.pl-plan-contract-trigger__hint {
font-size: 12px;
color: #64748b;
&.is-warn {
color: #d97706;
}
}
</style>