WEB/src/views/order/waveOrder/component/WavePlatformPrintPreviewDialog.vue
2026-06-01 18:13:54 +08:00

1170 lines
35 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.

<template>
<el-dialog
v-model="visibleProxy"
title="批量打印(平台数据)"
width="min(980px, 92vw)"
align-center
destroy-on-close
append-to-body
class="wave-platform-print-dialog"
>
<div v-if="errorMessage" class="wave-print-error">
<el-alert type="error" :closable="false" :title="errorMessage" />
</div>
<div v-else-if="payload" ref="printRootRef" class="wave-print-body">
<div class="wave-print-settings-bar">
<el-select
v-model="printSettings.station"
placeholder="请选择打印台"
size="small"
:loading="stationLoading"
@change="handleStationChange"
>
<el-option
v-for="item in stationOptions"
:key="item.stationId"
:label="item.name"
:value="item.stationId"
/>
</el-select>
</div>
<div class="wave-print-meta">
<span class="wave-print-meta__hint">{{ browserPrintHint }}</span>
<span>仓库:<code>{{ requestMeta?.warehouse_id ?? '—' }}</code></span>
<span>请求波次:<code>{{ requestMeta?.wave_ids?.length ?? 0 }}</code></span>
<span>返回普通波次:<code>{{ waveGroupList.length }}</code></span>
<span>返回锁定波次:<code>{{ lockedWaveGroupList.length }}</code></span>
</div>
<section class="wave-print-section">
<h4 class="wave-print-section__title">普通波次 / 平台列表</h4>
<div v-if="hasWaveGroups" class="wave-group-list">
<article v-for="wave in waveGroupList" :key="wave.waveKey" class="wave-group-card">
<header class="wave-group-card__header">
<div class="wave-group-card__title">
<span>波次:</span>
<code>{{ wave.wave_no }}</code>
<span class="wave-group-card__sep">|</span>
<span>ID:</span>
<code>{{ wave.wave_id }}</code>
</div>
<div class="wave-group-card__meta">
<el-tag size="small" type="info">平台 {{ wave.platforms.length }}</el-tag>
<el-tag size="small" type="success">订单 {{ wave.order_count }}</el-tag>
</div>
</header>
<div v-if="wave.platforms.length" class="wave-platform-list">
<article v-for="platform in wave.platforms" :key="platform.platformKey" class="wave-platform-card">
<div class="wave-platform-card__header">
<div class="wave-platform-card__title">
<span v-if="platform.sys_logistics_name" class="wave-platform-card__logistics">{{
platform.sys_logistics_name
}}</span>
<span v-if="platform.sys_logistics_name" class="wave-platform-card__sep-inline">|</span>
{{ platform.platform_name }}
<span class="wave-platform-card__code">{{ platform.platform_display }}</span>
</div>
<el-tag size="small" type="warning">订单 {{ platform.order_count }}</el-tag>
</div>
</article>
</div>
<p v-else class="wave-print-muted">(该波次无平台数据)</p>
</article>
</div>
<p v-else class="wave-print-muted wave-print-section__sub">(无 waveGroups)</p>
</section>
<section class="wave-print-section wave-print-section--locked">
<div class="wave-print-section__header">
<h4 class="wave-print-section__title">锁定波次 / 平台列表</h4>
<el-button
type="warning"
size="small"
plain
:loading="unlockAllLoading"
:disabled="!hasLockedWaveGroups"
@click="unlockAllLockedGroups"
>
一键解锁
</el-button>
</div>
<div v-if="hasLockedWaveGroups" class="wave-group-list">
<article v-for="wave in lockedWaveGroupList" :key="wave.waveKey" class="wave-group-card wave-group-card--locked">
<header class="wave-group-card__header">
<div class="wave-group-card__title">
<span>波次:</span>
<code>{{ wave.wave_no }}</code>
<span class="wave-group-card__sep">|</span>
<span>ID:</span>
<code>{{ wave.wave_id }}</code>
</div>
<div class="wave-group-card__meta">
<el-tag size="small" type="info">平台 {{ wave.platforms.length }}</el-tag>
<el-tag size="small" type="warning">锁定订单 {{ wave.order_count }}</el-tag>
</div>
</header>
<div v-if="wave.platforms.length" class="wave-platform-list">
<article v-for="platform in wave.platforms" :key="platform.platformKey" class="wave-platform-card wave-platform-card--locked">
<div class="wave-platform-card__header">
<div class="wave-platform-card__title">
<span v-if="platform.sys_logistics_name" class="wave-platform-card__logistics">{{
platform.sys_logistics_name
}}</span>
<span v-if="platform.sys_logistics_name" class="wave-platform-card__sep-inline">|</span>
{{ platform.platform_name }}
<span class="wave-platform-card__code">{{ platform.platform_display }}</span>
</div>
<div class="wave-platform-card__actions">
<el-tag size="small" type="danger">锁定订单 {{ platform.order_count }}</el-tag>
<el-button
type="warning"
size="small"
text
:loading="unlockingPlatformKey === platform.platformKey"
:disabled="unlockAllLoading"
@click="unlockSinglePlatform(wave, platform)"
>
解锁
</el-button>
</div>
</div>
</article>
</div>
<p v-else class="wave-print-muted">(该锁定波次无平台数据)</p>
</article>
</div>
<p v-else class="wave-print-muted wave-print-section__sub">(无 locked_wave_groups)</p>
</section>
</div>
<div v-else class="wave-print-muted">(无数据)</div>
<template #footer>
<el-button @click="visibleProxy = false">关闭</el-button>
<el-button
type="primary"
:loading="stationPrinting"
:disabled="!payload || !printSettings.station || !hasWaveGroups"
@click="printToStation"
>
打印到打印台
</el-button>
<el-button
:loading="browserPrinting"
:disabled="!payload || !hasWaveGroups"
@click="printReport"
>
浏览器打印
</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { WavePlatformPrintDataPayload } from '@/api/order.print/orderprint'
import { unlockWavePlatformPrintDataByGroup } from '@/api/order.print/orderprint'
import * as stationApi from '@/api/print/print'
import type { PrintSendParams } from '@/api/print/print'
import {
getBrowserPrintUsageHint,
getLoopbackPrinterAccessHint
} from '@/core/printerRuntime'
import { usePrinterComponentStore } from '@/stores/modules/printerComponent'
import {
buildWaveGroupsForNotifyLock,
parseExpressPrinterMapFromStationDetail,
sendWavePlatformBrowserPrint,
type BrowserWavePrintItemResult
} from '../config/print'
const WAVE_PRINT_STATION_STORAGE_KEY = 'wave_platform_print_station_id'
type AnyRecord = Record<string, unknown>
type WaveGroupPlatform = {
platformKey: string
platform: string
platform_display: string
platform_name: string
/** 快递 / 物流公司名称(与波次列表 sys_logistics_name 一致) */
sys_logistics_name: string
sys_logistics_code: string
order_ids: Array<number | string>
order_count: number
}
type WaveGroupView = {
waveKey: string
wave_id: string
wave_no: string
order_count: number
platforms: WaveGroupPlatform[]
}
const props = defineProps<{
modelValue: boolean
errorMessage: string
payload: WavePlatformPrintDataPayload | null
requestMeta: { warehouse_id: number; wave_ids: Array<number | string> } | null
}>()
const emit = defineEmits<{
'update:modelValue': [boolean]
refresh: []
'print-success': []
}>()
const printRootRef = ref<HTMLElement | null>(null)
/** 下拉值使用打印台主键 stationId(print.send express 的 printStationId);computer_id_legacy 用于迁移旧版本地存储 */
type StationOption = {
stationId: string
computer_id_legacy: string
name: string
default_printer_name: string
}
const stationOptions = ref<StationOption[]>([])
const stationLoading = ref(false)
const stationPrinting = ref(false)
const browserPrinting = ref(false)
/** print.send express 的 requestCode,同一次弹窗会话内保持不变 */
const expressRequestCode = ref('')
const unlockAllLoading = ref(false)
const unlockingPlatformKey = ref('')
const unlockedPlatformKeys = ref<Set<string>>(new Set())
const printSettings = reactive({
station: '' as string
})
const visibleProxy = computed({
get: () => props.modelValue,
set: (v: boolean) => emit('update:modelValue', v)
})
function buildWaveGroupList(groups: unknown[] | null | undefined, groupKeyPrefix = 'normal'): WaveGroupView[] {
if (!Array.isArray(groups)) return []
return groups
.filter((x) => x && typeof x === 'object')
.map((rawWave, waveIndex) => {
const wave = rawWave as AnyRecord
const wave_id = toText(wave.wave_id, `w-${waveIndex + 1}`)
const wave_no = toText(wave.wave_no, '—')
const rawPlatforms = Array.isArray(wave.platforms) ? wave.platforms : []
const platforms = rawPlatforms
.filter((x) => x && typeof x === 'object')
.map((rawPlatform, platformIndex) => {
const platform = rawPlatform as AnyRecord
const platformCode = toRawText(platform.platform)
const platformDisplay = platformCode || `platform-${platformIndex + 1}`
const platformName = toText(platform.platform_name, platformDisplay)
const logisticsRaw =
platform.sys_logistics_name ?? platform.logistics_name ?? platform.express_name ?? platform.logisticsName
const sys_logistics_name =
logisticsRaw != null && String(logisticsRaw).trim() !== '' ? String(logisticsRaw).trim() : ''
const sys_logistics_code = extractSysLogisticsCode(platform)
const order_ids = extractOrderIds(platform)
return {
platformKey: `${groupKeyPrefix}-${wave_id}-${platformDisplay}-${platformIndex}`,
platform: platformCode,
platform_display: platformDisplay,
platform_name: platformName,
sys_logistics_name,
sys_logistics_code,
order_ids,
order_count: toNum(platform.order_count, 0)
}
})
return {
waveKey: `${groupKeyPrefix}-${wave_id}-${wave_no}-${waveIndex}`,
wave_id,
wave_no,
order_count: toNum(wave.order_count, platforms.reduce((sum, p) => sum + p.order_count, 0)),
platforms
}
})
}
watch(
() => props.modelValue,
(visible) => {
if (visible) {
unlockedPlatformKeys.value = new Set()
unlockingPlatformKey.value = ''
unlockAllLoading.value = false
expressRequestCode.value = buildExpressRequestCode()
void loadStationOptions()
} else {
expressRequestCode.value = ''
}
}
)
watch(
() => props.payload,
() => {
// 父级刷新到新 payload 后,清空本地已解锁过滤,确保页面展示后端最新状态
unlockedPlatformKeys.value = new Set()
unlockingPlatformKey.value = ''
}
)
const waveGroupList = computed<WaveGroupView[]>(() => {
return buildWaveGroupList(props.payload?.waveGroups, 'normal')
})
const rawLockedWaveGroupList = computed<WaveGroupView[]>(() => {
return buildWaveGroupList(props.payload?.locked_wave_groups, 'locked')
})
const lockedWaveGroupList = computed<WaveGroupView[]>(() => {
const unlocked = unlockedPlatformKeys.value
if (!unlocked.size) return rawLockedWaveGroupList.value
return rawLockedWaveGroupList.value
.map((wave) => ({
...wave,
platforms: wave.platforms.filter((platform) => !unlocked.has(platform.platformKey))
}))
.filter((wave) => wave.platforms.length > 0)
})
const hasWaveGroups = computed(() => {
return waveGroupList.value.length > 0
})
const hasLockedWaveGroups = computed(() => {
return lockedWaveGroupList.value.length > 0
})
const browserPrintHint = computed(() => getBrowserPrintUsageHint())
function toText(v: unknown, fallback = '—'): string {
if (v === null || v === undefined) return fallback
const s = String(v).trim()
return s || fallback
}
function toRawText(v: unknown): string {
if (v === null || v === undefined) return ''
return String(v).trim()
}
function toNum(v: unknown, fallback = 0): number {
const n = Number(v)
return Number.isFinite(n) ? n : fallback
}
function extractOrderIds(platform: AnyRecord): Array<number | string> {
const direct = platform.order_ids
if (Array.isArray(direct)) {
return direct
.map(normalizeIdValue)
.filter((id) => !!id)
}
const rawOrders = platform.orders
if (!Array.isArray(rawOrders)) return []
return rawOrders
.map((item) => {
if (!item || typeof item !== 'object') return ''
const rec = item as AnyRecord
return normalizeIdValue(rec.order_id ?? rec.id ?? '')
})
.filter((id) => !!id)
}
function extractSysLogisticsCode(platform: AnyRecord): string {
const direct = toRawText(
platform.sys_logistics_code ??
platform.sysLogisticsCode ??
platform.logistics_code ??
platform.logisticsCode ??
platform.express_code ??
platform.expressCode
)
if (direct) return direct
const sysLogistics = platform.sys_logistics
if (sysLogistics && typeof sysLogistics === 'object') {
const code = toRawText((sysLogistics as AnyRecord).code)
if (code) return code
}
return ''
}
function normalizeIdValue(v: unknown): number | string {
const raw = String(v ?? '').trim()
if (!raw) return ''
if (/^\d+$/.test(raw)) {
const n = Number(raw)
if (Number.isSafeInteger(n)) {
return n
}
}
return raw
}
type UnlockGroupPayload = {
wave_id: number | string
platform?: string
sys_logistics_code?: string
order_ids?: Array<number | string>
}
type UnlockGroupMode = 'platform_express' | 'order'
function buildUnlockGroupsForPlatforms(wave: WaveGroupView, platforms: WaveGroupPlatform[]): UnlockGroupPayload[] {
return platforms.map((platform) => {
const item: UnlockGroupPayload = {
wave_id: normalizeIdValue(wave.wave_id),
platform: platform.platform || undefined,
sys_logistics_code: platform.sys_logistics_code || undefined
}
if (platform.order_ids.length > 0) {
item.order_ids = platform.order_ids
}
return item
})
}
function buildWaveIdsFromGroups(groups: UnlockGroupPayload[]): Array<number | string> {
const uniq = new Set<string>()
const result: Array<number | string> = []
groups.forEach((group) => {
const normalized = normalizeIdValue(group.wave_id)
const waveId = String(normalized ?? '').trim()
if (!waveId || uniq.has(waveId)) return
uniq.add(waveId)
result.push(normalized)
})
return result
}
function splitUnlockGroupsByMode(
wave: WaveGroupView,
platforms: WaveGroupPlatform[]
): {
platformExpressGroups: UnlockGroupPayload[]
orderGroups: UnlockGroupPayload[]
platformExpressKeys: string[]
orderKeys: string[]
} {
const platformExpressGroups: UnlockGroupPayload[] = []
const orderGroups: UnlockGroupPayload[] = []
const platformExpressKeys: string[] = []
const orderKeys: string[] = []
const waveId = normalizeIdValue(wave.wave_id)
platforms.forEach((platform) => {
if (platform.platform && platform.sys_logistics_code) {
platformExpressGroups.push({
wave_id: waveId,
platform: platform.platform,
sys_logistics_code: platform.sys_logistics_code
})
platformExpressKeys.push(platform.platformKey)
return
}
if (platform.order_ids.length > 0) {
orderGroups.push({
wave_id: waveId,
order_ids: platform.order_ids
})
orderKeys.push(platform.platformKey)
}
})
return {
platformExpressGroups,
orderGroups,
platformExpressKeys,
orderKeys
}
}
async function unlockGroupsByMode(
mode: UnlockGroupMode,
groups: UnlockGroupPayload[],
unlockedPlatformKeysToMark: string[]
) {
const warehouseId = Number(props.requestMeta?.warehouse_id || 0)
if (!warehouseId) {
ElMessage.warning('缺少仓库ID,无法解锁')
return false
}
if (!groups.length) {
return true
}
const waveIds = buildWaveIdsFromGroups(groups)
if (!waveIds.length) {
ElMessage.warning('缺少波次ID,无法解锁')
return false
}
const res: any = await unlockWavePlatformPrintDataByGroup({
warehouse_id: warehouseId,
wave_ids: waveIds,
group_type: mode,
unlock_scope: 'group',
groups
})
if (!isApiSuccess(res)) {
ElMessage.error(res?.message || '解锁失败')
return false
}
const next = new Set(unlockedPlatformKeys.value)
unlockedPlatformKeysToMark.forEach((key) => next.add(key))
unlockedPlatformKeys.value = next
const unlockedCount =
Number(res?.data?.unlocked_count ?? res?.data?.unlock_count ?? unlockedPlatformKeysToMark.length) ||
unlockedPlatformKeysToMark.length
ElMessage.success(`解锁成功,已解锁 ${unlockedCount} 组`)
return true
}
async function unlockSinglePlatform(wave: WaveGroupView, platform: WaveGroupPlatform) {
if (unlockAllLoading.value) return
const key = platform.platformKey
unlockingPlatformKey.value = key
try {
const { platformExpressGroups, orderGroups, platformExpressKeys, orderKeys } = splitUnlockGroupsByMode(wave, [platform])
if (!platformExpressGroups.length && !orderGroups.length) {
ElMessage.warning('当前分组缺少解锁条件:需提供平台+物流编码,或订单号')
return
}
if (platformExpressGroups.length) {
const ok = await unlockGroupsByMode('platform_express', platformExpressGroups, platformExpressKeys)
if (ok) emit('refresh')
return
}
const ok = await unlockGroupsByMode('order', orderGroups, orderKeys)
if (ok) emit('refresh')
} finally {
unlockingPlatformKey.value = ''
}
}
async function unlockAllLockedGroups() {
if (unlockAllLoading.value || !lockedWaveGroupList.value.length) return
unlockAllLoading.value = true
try {
const platformExpressGroups: UnlockGroupPayload[] = []
const orderGroups: UnlockGroupPayload[] = []
const platformExpressKeys: string[] = []
const orderKeys: string[] = []
lockedWaveGroupList.value.forEach((wave) => {
const split = splitUnlockGroupsByMode(wave, wave.platforms)
platformExpressGroups.push(...split.platformExpressGroups)
orderGroups.push(...split.orderGroups)
platformExpressKeys.push(...split.platformExpressKeys)
orderKeys.push(...split.orderKeys)
})
if (!platformExpressGroups.length && !orderGroups.length) {
ElMessage.warning('未找到可解锁分组,请检查物流编码或订单号数据')
return
}
let successCount = 0
if (platformExpressGroups.length) {
const ok = await unlockGroupsByMode('platform_express', platformExpressGroups, platformExpressKeys)
if (ok) successCount += 1
}
if (orderGroups.length) {
const ok = await unlockGroupsByMode('order', orderGroups, orderKeys)
if (ok) successCount += 1
}
if (!successCount) {
ElMessage.error('批量解锁失败')
return
}
emit('refresh')
} finally {
unlockAllLoading.value = false
}
}
function isApiSuccess(res: any) {
const c = res?.code
return !!res && (c === 0 || c === 200 || c === 1 || c === 20000)
}
/** print.getList:兼容 data.list 与 data.data.list(及 records) */
function extractPrintStationRows(res: any): any[] {
const root = res?.data
if (Array.isArray(root)) return root
if (!root || typeof root !== 'object') return []
if (Array.isArray(root.list)) return root.list
if (Array.isArray(root.records)) return root.records
if (Array.isArray(root.items)) return root.items
const inner = root.data
if (Array.isArray(inner)) return inner
if (inner && typeof inner === 'object') {
if (Array.isArray(inner.list)) return inner.list
if (Array.isArray(inner.records)) return inner.records
}
return []
}
/** 与 print.getList 行一致:stationId 为打印台 id;computer_id_legacy 为关联打印电脑(仅迁移/展示用) */
function mapStationRow(item: Record<string, any>): StationOption {
const rawSid = item.id ?? item.print_station_id ?? item.station_id
let stationId = rawSid != null && String(rawSid).trim() !== '' ? String(rawSid).trim() : ''
const rawComputer = item.computer_id ?? item.computerId
const computer_id_legacy =
rawComputer != null && String(rawComputer).trim() !== '' ? String(rawComputer).trim() : ''
if (!stationId && computer_id_legacy) {
stationId = computer_id_legacy
}
const nameRaw =
item.name ??
item.station_name ??
item.print_station_name ??
item.printName ??
item.stationName ??
item.label ??
''
const name = nameRaw != null && String(nameRaw).trim() !== '' ? String(nameRaw).trim() : stationId
const defPrinter =
item.default_printer_name ??
item.defaultPrinterName ??
item.printer_name ??
item.default_printer ??
''
const default_printer_name = String(defPrinter ?? '').trim()
return {
stationId,
computer_id_legacy,
name,
default_printer_name
}
}
async function loadStationOptions() {
stationLoading.value = true
try {
const stations: any = await stationApi.getList({ page: 1, pageSize: 100, where: {} })
if (!isApiSuccess(stations)) {
stationOptions.value = []
printSettings.station = ''
ElMessage.warning('加载打印台列表失败')
return
}
const rawList = extractPrintStationRows(stations)
stationOptions.value = rawList.filter((x) => x && typeof x === 'object').map((item: any) => mapStationRow(item))
// 初始化默认打印台:优先本地存储,其次当前值,最后回退到首项
const savedStation = getSavedStationId()
const currentStationId = String(printSettings.station || '').trim()
const hasSaved = !!savedStation && stationOptions.value.some((item) => item.stationId === savedStation)
const hasCurrent = !!currentStationId && stationOptions.value.some((item) => item.stationId === currentStationId)
/** 历史本地存的是关联电脑 ID,迁移为当前列表中的 stationId */
const legacyComputerMatch =
!!savedStation &&
!hasSaved &&
stationOptions.value.find((item) => {
const cid = item.computer_id_legacy
return cid != null && String(cid).trim() === savedStation
})
if (!stationOptions.value.length) {
printSettings.station = ''
clearSavedStationId()
return
}
if (hasSaved) {
printSettings.station = savedStation
} else if (legacyComputerMatch) {
printSettings.station = legacyComputerMatch.stationId
saveStationId(legacyComputerMatch.stationId)
} else if (hasCurrent) {
saveStationId(String(currentStationId))
} else {
const first = stationOptions.value[0]
if (first) {
printSettings.station = first.stationId
saveStationId(first.stationId)
}
}
} catch {
stationOptions.value = []
printSettings.station = ''
ElMessage.warning('加载打印台列表失败')
} finally {
stationLoading.value = false
}
}
function handleStationChange(val: string | number) {
const stationId = String(val || '').trim()
if (!stationId) {
clearSavedStationId()
return
}
saveStationId(stationId)
}
function buildExpressRequestCode(): string {
const wids = (props.requestMeta?.wave_ids || []).map(String).join('-')
const wh = props.requestMeta?.warehouse_id ?? ''
return `wave-print-${wh}-${wids}-${Date.now()}`
}
async function notifyLockAfterBrowserPrint(
waveGroups: unknown[],
items: BrowserWavePrintItemResult[],
): Promise<{ ok: boolean; message?: string }> {
const lockWaveGroups = buildWaveGroupsForNotifyLock(waveGroups, items)
if (!lockWaveGroups.length) {
return { ok: false, message: '无可锁定的打印分组' }
}
try {
const res: any = await stationApi.notifyLock({ waveGroups: lockWaveGroups })
if (isApiSuccess(res)) {
return { ok: true, message: res?.message }
}
return { ok: false, message: res?.message || res?.msg || '订单锁定失败' }
} catch (error) {
return {
ok: false,
message: error instanceof Error ? error.message : '订单锁定失败',
}
}
}
async function printToStation() {
if (!printSettings.station) {
ElMessage.warning('请选择打印台')
return
}
if (!props.payload) {
ElMessage.warning('暂无可打印数据')
return
}
const waveGroups = props.payload.waveGroups
if (!Array.isArray(waveGroups) || waveGroups.length === 0) {
ElMessage.warning('暂无可打印的波次分组数据(waveGroups 为空)')
return
}
const sid = String(printSettings.station).trim()
const requestCode = expressRequestCode.value || buildExpressRequestCode()
if (!expressRequestCode.value) {
expressRequestCode.value = requestCode
}
stationPrinting.value = true
try {
const printPayload: PrintSendParams = {
type: 'express',
printStationId: sid,
requestCode,
data: { waveGroups }
}
const res: any = await stationApi.sendPrint(printPayload)
if (res && (res.code === 0 || res.code === 200 || res.flag === 'success' || res.status === 'success')) {
ElMessage.success(res?.message || '已发送到打印台')
emit('refresh')
emit('print-success')
return
}
ElMessage.error(res?.msg || res?.message || '发送打印失败')
} catch {
ElMessage.error('发送打印失败,请检查打印台连接状态')
} finally {
stationPrinting.value = false
}
}
function getSavedStationId() {
try {
return String(localStorage.getItem(WAVE_PRINT_STATION_STORAGE_KEY) || '').trim()
} catch {
return ''
}
}
function saveStationId(stationId: string) {
try {
localStorage.setItem(WAVE_PRINT_STATION_STORAGE_KEY, stationId)
} catch {
// ignore
}
}
function clearSavedStationId() {
try {
localStorage.removeItem(WAVE_PRINT_STATION_STORAGE_KEY)
} catch {
// ignore
}
}
function unwrapPrintStationRecord(data: unknown): Record<string, unknown> {
if (!data || typeof data !== 'object') return {}
const root = data as Record<string, unknown>
if (root.data && typeof root.data === 'object' && !Array.isArray(root.data)) {
return root.data as Record<string, unknown>
}
return root
}
async function loadStationPrinterBindings(stationId: string) {
console.log('[wave browser print] loadStationPrinterBindings: 开始', { stationId })
const fallback = stationOptions.value.find((item) => item.stationId === stationId)
const fallbackDefault = fallback?.default_printer_name ?? ''
try {
const res: any = await stationApi.getItem(stationId)
if (!isApiSuccess(res)) {
console.log('[wave browser print] loadStationPrinterBindings: API 失败,使用 fallback', {
stationId,
fallbackDefault,
})
return {
defaultPrinter: fallbackDefault,
expressPrinterMap: {} as Record<string, string>
}
}
const parsed = parseExpressPrinterMapFromStationDetail(unwrapPrintStationRecord(res?.data ?? res))
console.log('[wave browser print] loadStationPrinterBindings: 成功', {
stationId,
defaultPrinter: parsed.defaultPrinter || fallbackDefault,
expressPrinterMap: parsed.expressPrinterMap,
})
return {
defaultPrinter: parsed.defaultPrinter || fallbackDefault,
expressPrinterMap: parsed.expressPrinterMap
}
} catch (error) {
console.log('[wave browser print] loadStationPrinterBindings: 异常,使用 fallback', {
stationId,
fallbackDefault,
error,
})
return {
defaultPrinter: fallbackDefault,
expressPrinterMap: {} as Record<string, string>
}
}
}
async function printReport() {
console.log('[wave browser print] printReport: 用户点击浏览器打印')
const accessHint = getLoopbackPrinterAccessHint()
if (accessHint) {
console.log('[wave browser print] printReport: 中止 — loopback 访问受限', { accessHint })
ElMessage.warning(accessHint)
return
}
if (!props.payload) {
console.log('[wave browser print] printReport: 中止 — 无 payload')
ElMessage.warning('暂无可打印数据')
return
}
const waveGroups = props.payload.waveGroups
if (!Array.isArray(waveGroups) || waveGroups.length === 0) {
console.log('[wave browser print] printReport: 中止 — waveGroups 为空')
ElMessage.warning('暂无可打印的波次分组数据(waveGroups 为空)')
return
}
const warehouseId = Number(props.requestMeta?.warehouse_id || 0)
if (!warehouseId) {
console.log('[wave browser print] printReport: 中止 — 缺少仓库 ID')
ElMessage.warning('缺少仓库 ID')
return
}
const requestCode = expressRequestCode.value || buildExpressRequestCode()
if (!expressRequestCode.value) {
expressRequestCode.value = requestCode
}
console.log('[wave browser print] printReport: 前置校验通过', {
warehouseId,
stationId: printSettings.station || '',
waveGroupCount: waveGroups.length,
requestCode,
})
browserPrinting.value = true
try {
console.log('[wave browser print] printReport: 刷新打印组件 runtime 状态')
usePrinterComponentStore().refreshFromRuntime()
const hasStation = String(printSettings.station || '').trim().length > 0
const { defaultPrinter, expressPrinterMap } = hasStation
? await loadStationPrinterBindings(printSettings.station)
: { defaultPrinter: '', expressPrinterMap: {} as Record<string, string> }
console.log('[wave browser print] printReport: 打印机映射来源', {
hasStation,
defaultPrinter,
expressPrinterMapKeys: Object.keys(expressPrinterMap),
})
console.log('[wave browser print] printReport: 调用 sendWavePlatformBrowserPrint')
const result = await sendWavePlatformBrowserPrint({
warehouseId,
waveGroups,
requestCode,
defaultPrinter,
expressPrinterMap
})
console.log('[wave browser print] printReport: sendWavePlatformBrowserPrint 返回', result)
if (result.flag === 'success' || result.flag === 'partial') {
const isPartial = result.flag === 'partial'
console.log(
`[wave browser print] printReport: ${isPartial ? '部分成功' : '全部成功'}`,
isPartial ? { failed: result.items.filter((item) => item.flag === 'failure') } : undefined,
)
const lockResult = await notifyLockAfterBrowserPrint(waveGroups, result.items)
console.log('[wave browser print] printReport: notifyLock 返回', lockResult)
if (lockResult.ok) {
if (isPartial) {
ElMessage.warning(`${result.message};${lockResult.message || '已成功分组订单已锁定'}`)
console.warn('[wave browser print] failed groups:', result.items.filter((item) => item.flag === 'failure'))
} else {
ElMessage.success(lockResult.message || result.message)
}
} else if (isPartial) {
ElMessage.warning(`${result.message};${lockResult.message || '订单锁定失败'}`)
console.warn('[wave browser print] failed groups:', result.items.filter((item) => item.flag === 'failure'))
} else {
ElMessage.warning(`${result.message};${lockResult.message || '订单锁定失败'}`)
}
emit('refresh')
emit('print-success')
return
}
console.log('[wave browser print] printReport: 失败', { message: result.message })
ElMessage.error(result.message || '浏览器打印失败')
} catch (error) {
console.error('[wave browser print] printReport: 异常', error)
const msg = error instanceof Error ? error.message : ''
ElMessage.error(
msg.includes('本地网络') || msg.includes('HTTPS')
? msg
: '浏览器打印失败,请确认本机打印组件已连接(HTTPS 下需在浏览器中允许访问本地网络)',
)
} finally {
browserPrinting.value = false
console.log('[wave browser print] printReport: 结束')
}
}
</script>
<style scoped lang="scss">
.wave-platform-print-dialog :deep(.el-dialog) {
max-height: 80vh;
display: flex;
flex-direction: column;
}
.wave-platform-print-dialog :deep(.el-dialog__body) {
flex: 1;
min-height: 0;
overflow: hidden;
padding-top: 10px;
padding-bottom: 10px;
}
.wave-print-meta {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 8px;
font-size: 12px;
color: #606266;
&__hint {
flex: 1 1 100%;
color: #909399;
font-size: 12px;
line-height: 1.5;
}
code {
background: #f4f4f5;
padding: 2px 6px;
border-radius: 4px;
font-size: 12px;
}
}
.wave-print-settings-bar {
display: flex;
gap: 10px;
margin-bottom: 8px;
.el-select {
min-width: 240px;
max-width: 320px;
}
}
.wave-print-body {
height: 100%;
overflow: auto;
}
.wave-print-error {
padding: 6px 0 10px;
}
.wave-group-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.wave-group-card {
border: 1px solid #e4e7ed;
border-radius: 6px;
background: #fff;
overflow: hidden;
&--locked {
border-color: #f3d19e;
background: #fffcf5;
}
&__header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
padding: 7px 10px;
background: #f8fafc;
border-bottom: 1px solid #ebeef5;
}
&__title {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: #303133;
code {
background: #f4f4f5;
padding: 2px 6px;
border-radius: 4px;
font-size: 11px;
}
}
&__sep {
color: #c0c4cc;
margin: 0 4px;
}
&__meta {
display: inline-flex;
gap: 8px;
}
}
.wave-platform-list {
padding: 8px 10px;
display: flex;
flex-direction: column;
gap: 6px;
}
.wave-platform-card {
border: 1px solid #ebeef5;
border-radius: 4px;
padding: 6px 8px;
&--locked {
border-color: #f8d2d2;
background: #fff7f7;
}
&__header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0;
}
&__actions {
display: inline-flex;
align-items: center;
gap: 6px;
}
&__title {
font-size: 12px;
color: #303133;
font-weight: 500;
}
&__logistics {
font-weight: 600;
color: #303133;
}
&__sep-inline {
color: #c0c4cc;
margin: 0 6px;
font-weight: 400;
}
&__code {
margin-left: 6px;
color: #909399;
font-size: 11px;
}
}
.wave-print-section {
margin-bottom: 18px;
&__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 6px;
}
&__title {
margin: 0;
font-size: 13px;
font-weight: 600;
color: #303133;
}
&__sub {
margin: 0 0 8px;
}
}
.wave-print-muted {
margin: 0;
font-size: 12px;
color: #909399;
}
</style>