Merge discussion comments into the existing printed approval flow on Web and mobile OA, preserving detail timeline order and hiding revoked content. Include mentions and absolute attachment URLs, and add PDF link annotations so rasterized exports retain usable links. Add regression tests for ordering, attachments, mentions and revoked comments. Related to Gitea issue #30.
790 lines
26 KiB
JavaScript
790 lines
26 KiB
JavaScript
import { attachmentFullUrl } from '../../utils/attachment.js'
|
||
/**
|
||
* OA 审批单移动端打印(S6)
|
||
* 对齐 web-admin `oa-approval-print.ts` 字段/流程结构;支持 html2canvas + jsPDF 导出。
|
||
*/
|
||
import html2canvas from 'html2canvas'
|
||
import { jsPDF } from 'jspdf'
|
||
import { uploadAttachment } from '../../api/oa.js'
|
||
import { formatDeptDisplay } from '../kit/oa-dept-value.js'
|
||
import { formatPersonDisplay } from '../kit/oa-person-value.js'
|
||
import { formatIdNameDisplay } from '../../utils/id-name-value.js'
|
||
import {
|
||
formatReceiveAccountLine,
|
||
normalizeReceiveAccountModelValue
|
||
} from '../../utils/receive-account-value.js'
|
||
import { toRmbUpper } from '../../utils/rmb-upper.js'
|
||
import { resolveStamp } from '../oa-status-stamp.js'
|
||
import { buildOaPrintFilename } from './oa-print-filename.js'
|
||
import { buildFlowItems } from './oa-print-flow.js'
|
||
import {
|
||
isWeChatMiniWebView,
|
||
navigateToHostPdfPreview,
|
||
printNavLog
|
||
} from './oa-pdf-preview-nav.js'
|
||
|
||
export { resolveStamp }
|
||
|
||
export const OA_PRINT_COMPANY_NAME = '安徽中科兴皖医学研究有限公司'
|
||
|
||
const UPLOAD_TYPES = new Set([
|
||
'upload',
|
||
'fcUpload',
|
||
'elUpload',
|
||
'el-upload',
|
||
'attachment',
|
||
'file',
|
||
'files'
|
||
])
|
||
|
||
const SKIP_RULE_TYPES = new Set([
|
||
'div',
|
||
'fcRow',
|
||
'fcCol',
|
||
'fcTable',
|
||
'fcTableGrid',
|
||
'col',
|
||
'row',
|
||
'group',
|
||
'tab',
|
||
'tabs',
|
||
'space',
|
||
'divider',
|
||
'html',
|
||
'vanCellGroup',
|
||
'leaveKit',
|
||
'confirmationKit',
|
||
'overtimeKit',
|
||
'resignationKit',
|
||
'tripKit'
|
||
])
|
||
|
||
function escapeHtml(s) {
|
||
return String(s ?? '')
|
||
.replace(/&/g, '&')
|
||
.replace(/</g, '<')
|
||
.replace(/>/g, '>')
|
||
.replace(/"/g, '"')
|
||
}
|
||
|
||
function formatDateOnly(createTime) {
|
||
const raw = String(createTime || '').trim()
|
||
if (!raw) return '-'
|
||
return raw.slice(0, 10)
|
||
}
|
||
|
||
function formatNow() {
|
||
const d = new Date()
|
||
const pad = (n) => String(n).padStart(2, '0')
|
||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
|
||
}
|
||
|
||
function ensurePlainObject(raw) {
|
||
if (raw == null) return {}
|
||
if (typeof raw === 'string') {
|
||
try {
|
||
const parsed = JSON.parse(raw)
|
||
return parsed && typeof parsed === 'object' ? parsed : {}
|
||
} catch {
|
||
return {}
|
||
}
|
||
}
|
||
if (typeof raw === 'object') return raw
|
||
return {}
|
||
}
|
||
|
||
function formatScalar(value, sep = '、') {
|
||
if (value == null || value === '') return '-'
|
||
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
||
return String(value)
|
||
}
|
||
if (Array.isArray(value)) {
|
||
return (
|
||
value
|
||
.map((x) => formatScalar(x, sep))
|
||
.filter((x) => x && x !== '-')
|
||
.join(sep) || '-'
|
||
)
|
||
}
|
||
if (typeof value === 'object') {
|
||
if (value.name != null) return String(value.name)
|
||
if (value.label != null) return String(value.label)
|
||
try {
|
||
return JSON.stringify(value)
|
||
} catch {
|
||
return String(value)
|
||
}
|
||
}
|
||
return String(value)
|
||
}
|
||
|
||
function formatRegionLikeDisplay(value) {
|
||
if (value == null || value === '') return ''
|
||
if (Array.isArray(value)) {
|
||
return value
|
||
.map((x) => {
|
||
if (x && typeof x === 'object') return String(x.name || x.label || x.text || '').trim()
|
||
return String(x || '').trim()
|
||
})
|
||
.filter(Boolean)
|
||
.join(' / ')
|
||
}
|
||
if (typeof value === 'object') {
|
||
return String(value.name || value.label || value.text || '').trim()
|
||
}
|
||
return String(value).trim()
|
||
}
|
||
|
||
function fileNameFromUrl(url) {
|
||
const u = String(url || '').trim()
|
||
if (!u) return '未命名文件'
|
||
try {
|
||
const path = u.split('?')[0] || u
|
||
const last = path.split('/').pop() || ''
|
||
return decodeURIComponent(last) || '未命名文件'
|
||
} catch {
|
||
return '未命名文件'
|
||
}
|
||
}
|
||
|
||
function formatUploadNames(value) {
|
||
if (value == null || value === '') return []
|
||
if (Array.isArray(value)) {
|
||
const out = []
|
||
for (const item of value) {
|
||
if (typeof item === 'string') {
|
||
item
|
||
.split(',')
|
||
.map((x) => x.trim())
|
||
.filter(Boolean)
|
||
.forEach((p) => out.push(fileNameFromUrl(p)))
|
||
} else if (item && typeof item === 'object') {
|
||
const name = String(item.name || '').trim()
|
||
out.push(name || fileNameFromUrl(item.url || item.fileUrl || item.path))
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
if (typeof value === 'string') {
|
||
return value
|
||
.split(',')
|
||
.map((x) => x.trim())
|
||
.filter(Boolean)
|
||
.map((p) => fileNameFromUrl(p))
|
||
}
|
||
if (typeof value === 'object') {
|
||
const name = String(value.name || '').trim()
|
||
return [name || fileNameFromUrl(value.url || value.fileUrl || value.path)]
|
||
}
|
||
return []
|
||
}
|
||
|
||
function formatMoney(value, showUpper) {
|
||
const n =
|
||
value == null || value === ''
|
||
? null
|
||
: typeof value === 'number'
|
||
? value
|
||
: Number(String(value).replace(/,/g, ''))
|
||
if (n == null || !Number.isFinite(n)) return '-'
|
||
const numText = n.toLocaleString('zh-CN', {
|
||
minimumFractionDigits: 2,
|
||
maximumFractionDigits: 2
|
||
})
|
||
if (showUpper === false) return numText
|
||
const upper = toRmbUpper(n)
|
||
return upper ? `${numText}(${upper})` : numText
|
||
}
|
||
|
||
function formatReceiveAccounts(value) {
|
||
const list = normalizeReceiveAccountModelValue(value)
|
||
if (!list.length) return ''
|
||
return list.map(formatReceiveAccountLine).join('\n')
|
||
}
|
||
|
||
function formatTripLeg(leg, index) {
|
||
const transport = String(leg.transport || '').trim() || '-'
|
||
const tripType = String(leg.tripType || '').trim()
|
||
const fromCity = String(leg.fromCity || '').trim() || '-'
|
||
const toCity = String(leg.toCity || '').trim() || '-'
|
||
const startDate = String(leg.startDate || '').trim()
|
||
const startHalf = String(leg.startHalf || '').trim()
|
||
const endDate = String(leg.endDate || '').trim()
|
||
const endHalf = String(leg.endHalf || '').trim()
|
||
const duration = leg.duration
|
||
const durationText =
|
||
duration == null || duration === '' ? '-' : `${Number(duration)}天`
|
||
const route = `${fromCity} → ${toCity}`
|
||
const period =
|
||
startDate && endDate
|
||
? `${startDate}${startHalf ? ` ${startHalf}` : ''} ~ ${endDate}${endHalf ? ` ${endHalf}` : ''}`
|
||
: '-'
|
||
const typePart = tripType ? ` · ${tripType}` : ''
|
||
return `行程${index + 1}:${transport}${typePart} · ${route} · ${period} · ${durationText}`
|
||
}
|
||
|
||
function formatTripItinerary(value) {
|
||
if (!Array.isArray(value) || !value.length) return '-'
|
||
const lines = value
|
||
.filter((leg) => leg && typeof leg === 'object')
|
||
.map((leg, idx) => formatTripLeg(leg, idx))
|
||
return lines.length ? lines.join('\n') : '-'
|
||
}
|
||
|
||
function isRangeFieldRule(rule) {
|
||
const type = String(rule?.type || '').trim()
|
||
const props = rule?.props && typeof rule.props === 'object' ? rule.props : {}
|
||
if (type === 'datePicker' || type === 'date' || type === 'dateRange') {
|
||
return /range$/i.test(String(props.type || type))
|
||
}
|
||
if (type === 'timePicker' || type === 'time' || type === 'timeRange') {
|
||
return props.isRange === true || type === 'timeRange'
|
||
}
|
||
return false
|
||
}
|
||
|
||
function normalizeRelatedIds(value) {
|
||
if (value == null || value === '') return []
|
||
if (Array.isArray(value)) {
|
||
return value.map((x) => String(x || '').trim()).filter(Boolean)
|
||
}
|
||
if (typeof value === 'string') {
|
||
const t = value.trim()
|
||
if (!t) return []
|
||
try {
|
||
const parsed = JSON.parse(t)
|
||
if (Array.isArray(parsed)) {
|
||
return parsed.map((x) => String(x || '').trim()).filter(Boolean)
|
||
}
|
||
} catch {
|
||
/* comma list */
|
||
}
|
||
return t
|
||
.split(',')
|
||
.map((x) => x.trim())
|
||
.filter(Boolean)
|
||
}
|
||
return []
|
||
}
|
||
|
||
function walkRules(rules, formData, out) {
|
||
if (!Array.isArray(rules)) return
|
||
for (const rule of rules) {
|
||
if (!rule || typeof rule !== 'object') continue
|
||
const type = String(rule.type || '').trim()
|
||
const children = rule.children || rule.props?.rule
|
||
if (Array.isArray(children) && children.length) {
|
||
walkRules(children, formData, out)
|
||
}
|
||
if (SKIP_RULE_TYPES.has(type)) continue
|
||
const field = String(rule.field || '').trim()
|
||
if (!field) continue
|
||
const label =
|
||
String(rule.title || rule.label || rule.props?.label || field).trim() || field
|
||
const value = formData?.[field]
|
||
|
||
if (type === 'relatedApproval') {
|
||
const ids = normalizeRelatedIds(value)
|
||
out.push({
|
||
label,
|
||
text: ids.length ? `已关联 ${ids.length} 条` : '-'
|
||
})
|
||
continue
|
||
}
|
||
|
||
if (type === 'dept' || type === 'ownerDept') {
|
||
out.push({ label, text: formatDeptDisplay(value) || '-' })
|
||
continue
|
||
}
|
||
if (type === 'person' || type === 'ownerPerson') {
|
||
out.push({ label, text: formatPersonDisplay(value) || '-' })
|
||
continue
|
||
}
|
||
if (type === 'post') {
|
||
out.push({ label, text: formatIdNameDisplay(value) || '-' })
|
||
continue
|
||
}
|
||
if (type === 'money') {
|
||
const showUpper = rule.props?.showUpper !== false
|
||
out.push({ label, text: formatMoney(value, showUpper) })
|
||
continue
|
||
}
|
||
if (type === 'receiveAccount') {
|
||
out.push({ label, text: formatReceiveAccounts(value) || '-' })
|
||
continue
|
||
}
|
||
if (type === 'region' || type === 'cascader') {
|
||
out.push({ label, text: formatRegionLikeDisplay(value) || '-' })
|
||
continue
|
||
}
|
||
if (type === 'tripItinerary') {
|
||
out.push({ label, text: formatTripItinerary(value) })
|
||
continue
|
||
}
|
||
|
||
const dragTag = String(rule._fc_drag_tag || '').trim()
|
||
if (
|
||
UPLOAD_TYPES.has(type) ||
|
||
UPLOAD_TYPES.has(dragTag) ||
|
||
String(rule.name || '')
|
||
.toLowerCase()
|
||
.includes('upload') ||
|
||
dragTag.toLowerCase().includes('upload')
|
||
) {
|
||
const names = formatUploadNames(value)
|
||
out.push({
|
||
label,
|
||
urls: names.length ? names : undefined,
|
||
text: names.length ? undefined : '-'
|
||
})
|
||
continue
|
||
}
|
||
|
||
if (Array.isArray(value) && isRangeFieldRule(rule)) {
|
||
out.push({ label, text: formatScalar(value, '~') })
|
||
continue
|
||
}
|
||
out.push({ label, text: formatScalar(value) })
|
||
}
|
||
}
|
||
|
||
function buildFormRows(detail) {
|
||
const schema = ensurePlainObject(detail?.formSchemaJson)
|
||
const formData = ensurePlainObject(detail?.formDataJson || detail?.formData)
|
||
const rule = Array.isArray(schema?.rule)
|
||
? schema.rule
|
||
: Array.isArray(detail?.formSchemaJson)
|
||
? detail.formSchemaJson
|
||
: []
|
||
const out = []
|
||
walkRules(rule, formData, out)
|
||
if (out.length) return out
|
||
for (const [k, v] of Object.entries(formData)) {
|
||
const names = formatUploadNames(v)
|
||
if (names.length) {
|
||
out.push({ label: k, urls: names })
|
||
continue
|
||
}
|
||
out.push({ label: k, text: formatScalar(v) })
|
||
}
|
||
return out
|
||
}
|
||
|
||
export { buildFlowItems }
|
||
|
||
export function buildOaPrintModel(detail, opts = {}) {
|
||
const { stampClass, stampText } = resolveStamp(detail?.status)
|
||
const appName = String(detail?.appName || '').trim()
|
||
const titleFallback = String(detail?.title || '').trim()
|
||
const title = appName || titleFallback || '审批单'
|
||
const printerName = String(opts.printerName || '').trim() || '-'
|
||
const printTime = opts.printTime || formatNow()
|
||
const headerRows = [
|
||
{ label: '审批编号', text: String(detail?.id || '-').trim() || '-' },
|
||
{
|
||
label: '创建人',
|
||
text:
|
||
String(detail?.initiatorUserName || detail?.initiatorUserId || '-').trim() || '-'
|
||
},
|
||
{
|
||
label: '创建人部门',
|
||
text:
|
||
String(detail?.initiatorDeptName || detail?.initiatorDept || '-').trim() || '-'
|
||
}
|
||
]
|
||
return {
|
||
title,
|
||
companyName: OA_PRINT_COMPANY_NAME,
|
||
createDate: formatDateOnly(detail?.createTime),
|
||
stampClass,
|
||
stampText,
|
||
rows: [...headerRows, ...buildFormRows(detail)],
|
||
flowItems: buildFlowItems(detail, (url) => {
|
||
try {
|
||
return new URL(attachmentFullUrl(url), window.location.origin).href
|
||
} catch {
|
||
return ''
|
||
}
|
||
}),
|
||
printTime,
|
||
printerName,
|
||
watermarkName: printerName === '-' ? '审批' : printerName
|
||
}
|
||
}
|
||
|
||
function cellInnerHtml(row) {
|
||
if (Array.isArray(row.urls) && row.urls.length) {
|
||
return row.urls.map((u) => `<div class="oa-print-url">${escapeHtml(u)}</div>`).join('')
|
||
}
|
||
const raw = String(row.text != null ? row.text : '-')
|
||
const html = raw
|
||
.split('\n')
|
||
.map((line) => escapeHtml(line))
|
||
.join('<br/>')
|
||
return `<span class="oa-print-text">${html}</span>`
|
||
}
|
||
|
||
function flowCellHtml(f) {
|
||
let html = `<div class="oa-print-flow__row"><div class="oa-print-flow__left">${escapeHtml(f.left)}</div>`
|
||
if (f.right) {
|
||
html += `<div class="oa-print-flow__right">${escapeHtml(f.right)}</div>`
|
||
}
|
||
html += '</div>'
|
||
if (Array.isArray(f.personLines) && f.personLines.length) {
|
||
html += '<div class="oa-print-flow__person-lines">'
|
||
for (const line of f.personLines) {
|
||
html += `<div class="oa-print-flow__row oa-print-flow__person-line"><div class="oa-print-flow__left">${escapeHtml(line.left)}</div>`
|
||
if (line.right) {
|
||
html += `<div class="oa-print-flow__right">${escapeHtml(line.right)}</div>`
|
||
}
|
||
html += '</div>'
|
||
}
|
||
html += '</div>'
|
||
} else if (f.comment) {
|
||
html += `<div class="oa-print-flow__comment">意见:${escapeHtml(f.comment)}</div>`
|
||
}
|
||
for (const url of f.attachmentLinks || []) {
|
||
html += `<div class="oa-print-url"><a data-oa-print-link href="${escapeHtml(url)}">${escapeHtml(url)}</a></div>`
|
||
}
|
||
return html
|
||
}
|
||
|
||
function buildPrintStylesContent() {
|
||
return `
|
||
* { box-sizing: border-box; }
|
||
body { margin: 0; background: #fff; color: #1f2329;
|
||
font-family: "PingFang SC","Microsoft YaHei","Helvetica Neue",Arial,sans-serif; }
|
||
.oa-print-page {
|
||
position: relative;
|
||
width: 794px;
|
||
max-width: 794px;
|
||
margin: 0 auto;
|
||
min-height: 1123px;
|
||
padding: 48px 56px 56px;
|
||
overflow: hidden;
|
||
background: #fff;
|
||
color: #1f2329;
|
||
font-family: "PingFang SC","Microsoft YaHei","Helvetica Neue",Arial,sans-serif;
|
||
box-sizing: border-box;
|
||
}
|
||
.oa-print-wm { position: absolute; inset: 0; pointer-events: none; z-index: 0; overflow: hidden; }
|
||
.oa-print-wm__item { position: absolute; font-size: 14px; color: rgba(0,0,0,.045);
|
||
white-space: nowrap; transform: rotate(-30deg); letter-spacing: 2px; }
|
||
.oa-print-inner { position: relative; z-index: 1; }
|
||
.oa-print-title { margin: 0 0 14px; text-align: center; font-size: 28px;
|
||
font-weight: 700; letter-spacing: 2px; line-height: 1.3; }
|
||
.oa-print-meta { display: flex; flex-wrap: wrap; gap: 16px 48px; margin-bottom: 12px;
|
||
font-size: 12px; line-height: 1.5; }
|
||
.oa-print-table-wrap { position: relative; }
|
||
.oa-print-table { width: 100%; border-collapse: separate; border-spacing: 0;
|
||
table-layout: fixed; font-size: 13px; border-top: 1px solid #1f2329; border-left: 1px solid #1f2329; }
|
||
.oa-print-table th, .oa-print-table td { border: none; border-right: 1px solid #1f2329;
|
||
border-bottom: 1px solid #1f2329; padding: 9px 12px; vertical-align: middle;
|
||
line-height: 1.5; word-break: break-all; }
|
||
.oa-print-table th { width: 118px; font-weight: 400; text-align: left; background: #fff; }
|
||
.oa-print-text { white-space: pre-wrap; }
|
||
.oa-print-url a { color: inherit; }
|
||
.oa-print-url { color: #3370ff; word-break: break-all; }
|
||
.oa-print-flow__row { display: flex; justify-content: space-between; gap: 12px; }
|
||
.oa-print-flow__left { white-space: pre-wrap; overflow-wrap: anywhere; flex: 1; min-width: 0; }
|
||
.oa-print-flow__right { flex: 0 0 auto; color: #646464; white-space: nowrap; }
|
||
.oa-print-flow__person-lines { margin-top: 4px; padding-left: 8px; }
|
||
.oa-print-flow__person-line { margin-top: 2px; font-size: 12px; }
|
||
.oa-print-flow__comment { margin-top: 4px; color: #646464; font-size: 12px; }
|
||
.oa-stamp { --stamp: #3ec9a8; position: absolute; top: -10px; right: 18px;
|
||
width: 118px; height: 118px; z-index: 5; pointer-events: none;
|
||
transform: rotate(-18deg); opacity: 0.88; color: var(--stamp); }
|
||
.oa-stamp.ok { --stamp: #3ec9a8; }
|
||
.oa-stamp.run { --stamp: #f0a020; }
|
||
.oa-stamp.rej { --stamp: #e85d5d; }
|
||
.oa-stamp.ret { --stamp: #e07070; }
|
||
.oa-stamp.can { --stamp: #9aa0a6; }
|
||
.oa-stamp .outer { position: absolute; inset: 0; border-radius: 50%;
|
||
border: 5px solid currentColor; box-sizing: border-box; }
|
||
.oa-stamp .arc-top, .oa-stamp .arc-bottom { position: absolute; left: 14px; right: 14px;
|
||
border: 2px solid currentColor; opacity: 0.95; pointer-events: none; }
|
||
.oa-stamp .arc-top { top: 11px; height: 36px; border-bottom: none;
|
||
border-left-color: transparent; border-right-color: transparent;
|
||
border-radius: 50% 50% 0 0 / 100% 100% 0 0; }
|
||
.oa-stamp .arc-bottom { bottom: 11px; height: 36px; border-top: none;
|
||
border-left-color: transparent; border-right-color: transparent;
|
||
border-radius: 0 0 50% 50% / 0 0 100% 100%; }
|
||
.oa-stamp .label-top { position: absolute; top: 22px; left: 0; right: 0;
|
||
text-align: center; font-size: 10px; font-weight: 500; letter-spacing: 2px;
|
||
line-height: 1; color: currentColor; opacity: 0.95; }
|
||
.oa-stamp .label-bottom { position: absolute; bottom: 20px; left: 0; right: 0;
|
||
text-align: center; font-size: 9px; font-weight: 500; letter-spacing: 0.5px;
|
||
line-height: 1; color: currentColor; opacity: 0.9;
|
||
font-family: Arial, "Helvetica Neue", sans-serif; }
|
||
.oa-stamp .main { position: absolute; inset: 0; display: flex; align-items: center;
|
||
justify-content: center; font-size: 32px; font-weight: 700; letter-spacing: 2px;
|
||
line-height: 1; color: currentColor; }
|
||
.oa-stamp .main.is-chars3 { font-size: 26px; letter-spacing: 1px; }
|
||
.oa-print-footer { display: flex; gap: 28px; margin-top: 14px; font-size: 12px; }`
|
||
}
|
||
|
||
function buildPrintPageContent(model) {
|
||
const stampChars3 = model.stampText.length >= 3 ? ' is-chars3' : ''
|
||
const wmItems = Array.from({ length: 24 }, (_, i) => {
|
||
const row = Math.floor(i / 3)
|
||
const col = i % 3
|
||
const top = 40 + row * 100
|
||
const left = -20 + col * 240 + (row % 2) * 40
|
||
return `<span class="oa-print-wm__item" style="top:${top}px;left:${left}px">${escapeHtml(model.watermarkName)} ${escapeHtml(model.watermarkName)}</span>`
|
||
}).join('')
|
||
|
||
let rowsHtml = ''
|
||
for (const row of model.rows) {
|
||
rowsHtml += `<tr><th>${escapeHtml(row.label)}</th><td>${cellInnerHtml(row)}</td></tr>`
|
||
}
|
||
|
||
let flowHtml = ''
|
||
if (model.flowItems.length) {
|
||
model.flowItems.forEach((f, fi) => {
|
||
flowHtml += '<tr class="oa-print-flow">'
|
||
if (fi === 0) {
|
||
flowHtml += `<th class="oa-print-flow__label" rowspan="${model.flowItems.length}">审批流程</th>`
|
||
}
|
||
flowHtml += `<td class="oa-print-flow__cell">${flowCellHtml(f)}</td></tr>`
|
||
})
|
||
} else {
|
||
flowHtml =
|
||
'<tr class="oa-print-flow"><th class="oa-print-flow__label">审批流程</th><td class="oa-print-flow__cell"><span class="oa-print-text">-</span></td></tr>'
|
||
}
|
||
|
||
return `<div class="oa-print-page">
|
||
<div class="oa-print-wm" aria-hidden="true">${wmItems}</div>
|
||
<div class="oa-print-inner">
|
||
<h1 class="oa-print-title">${escapeHtml(model.title)}</h1>
|
||
<div class="oa-print-meta">
|
||
<span>${escapeHtml(model.companyName)}</span>
|
||
<span>创建时间:${escapeHtml(model.createDate)}</span>
|
||
</div>
|
||
<div class="oa-print-table-wrap">
|
||
<div class="oa-stamp ${escapeHtml(model.stampClass)}" aria-label="${escapeHtml(model.stampText)}">
|
||
<div class="outer"></div>
|
||
<div class="arc-top"></div>
|
||
<div class="arc-bottom"></div>
|
||
<div class="label-top">OA审批</div>
|
||
<div class="main${stampChars3}">${escapeHtml(model.stampText)}</div>
|
||
<div class="label-bottom">approval</div>
|
||
</div>
|
||
<table class="oa-print-table">
|
||
<tbody>${rowsHtml}${flowHtml}</tbody>
|
||
</table>
|
||
</div>
|
||
<div class="oa-print-footer">
|
||
<span>打印时间:${escapeHtml(model.printTime)}</span>
|
||
<span>打印人:${escapeHtml(model.printerName)}</span>
|
||
</div>
|
||
</div>
|
||
</div>`
|
||
}
|
||
|
||
export function buildPrintBodyHtml(model) {
|
||
return `<style>${buildPrintStylesContent()}</style>${buildPrintPageContent(model)}`
|
||
}
|
||
|
||
/** 用 canvas 绘制中文页码(jsPDF 内置字体不支持汉字,会乱码) */
|
||
function renderPageLabelCanvas(text) {
|
||
const font = '20px "PingFang SC", "Microsoft YaHei", "Heiti SC", sans-serif'
|
||
const measure = document.createElement('canvas')
|
||
const mctx = measure.getContext('2d')
|
||
if (!mctx) {
|
||
const empty = document.createElement('canvas')
|
||
empty.width = 1
|
||
empty.height = 1
|
||
return empty
|
||
}
|
||
mctx.font = font
|
||
const tw = Math.ceil(mctx.measureText(text).width) + 8
|
||
const th = 28
|
||
const scale = 2
|
||
const c = document.createElement('canvas')
|
||
c.width = tw * scale
|
||
c.height = th * scale
|
||
const ctx = c.getContext('2d')
|
||
if (!ctx) return c
|
||
ctx.scale(scale, scale)
|
||
ctx.clearRect(0, 0, tw, th)
|
||
ctx.font = font
|
||
ctx.fillStyle = '#646464'
|
||
ctx.textBaseline = 'middle'
|
||
ctx.fillText(text, 4, th / 2)
|
||
return c
|
||
}
|
||
|
||
async function canvasToPdfBlob(canvas, sheet) {
|
||
const pdf = new jsPDF({ orientation: 'p', unit: 'mm', format: 'a4' })
|
||
const pageWidth = pdf.internal.pageSize.getWidth()
|
||
const pageHeight = pdf.internal.pageSize.getHeight()
|
||
const imgWidth = pageWidth
|
||
const imgHeight = (canvas.height * imgWidth) / canvas.width
|
||
|
||
const EPS_MM = 1.5
|
||
const totalPages = Math.min(40, Math.max(1, Math.ceil((imgHeight - EPS_MM) / pageHeight)))
|
||
|
||
const pageData = canvas.toDataURL('image/jpeg', 0.95)
|
||
const labelMmH = 4.5
|
||
|
||
for (let pageIndex = 0; pageIndex < totalPages; pageIndex++) {
|
||
if (pageIndex > 0) pdf.addPage()
|
||
const position = -pageIndex * pageHeight
|
||
pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
|
||
|
||
// html2canvas 只保留像素,单独把附件链接写为 PDF 注解;跨页部分按页裁切。
|
||
const sheetRect = sheet.getBoundingClientRect()
|
||
const ratio = pageWidth / sheetRect.width
|
||
for (const link of sheet.querySelectorAll('a[data-oa-print-link]')) {
|
||
if (!/^https?:\/\//i.test(link.href)) continue
|
||
for (const rect of link.getClientRects()) {
|
||
const top = (rect.top - sheetRect.top) * ratio - pageIndex * pageHeight
|
||
const bottom = Math.min(pageHeight, top + rect.height * ratio)
|
||
const y = Math.max(0, top)
|
||
if (bottom > y) {
|
||
pdf.link((rect.left - sheetRect.left) * ratio, y, rect.width * ratio, bottom - y, {
|
||
url: link.href
|
||
})
|
||
}
|
||
}
|
||
}
|
||
|
||
const label = `第${pageIndex + 1}页`
|
||
const labelCanvas = renderPageLabelCanvas(label)
|
||
if (labelCanvas.width > 1) {
|
||
const labelMmW = (labelCanvas.width / labelCanvas.height) * labelMmH
|
||
pdf.addImage(
|
||
labelCanvas.toDataURL('image/png'),
|
||
'PNG',
|
||
(pageWidth - labelMmW) / 2,
|
||
pageHeight - 10,
|
||
labelMmW,
|
||
labelMmH
|
||
)
|
||
}
|
||
}
|
||
|
||
return pdf.output('blob')
|
||
}
|
||
|
||
export async function generateOaApprovalPdfBlob(detail, opts = {}) {
|
||
if (!detail) throw new Error('暂无审批详情,无法导出')
|
||
const model = buildOaPrintModel(detail, {
|
||
printerName: opts.printerName || ''
|
||
})
|
||
const filename = buildOaPrintFilename(detail)
|
||
const host = document.createElement('div')
|
||
host.setAttribute('data-oa-print-host', '1')
|
||
host.style.cssText =
|
||
'position:fixed;left:-100000px;top:0;width:794px;z-index:-1;opacity:1;pointer-events:none;'
|
||
document.body.appendChild(host)
|
||
host.innerHTML = buildPrintBodyHtml(model)
|
||
try {
|
||
await new Promise((r) => requestAnimationFrame(() => r()))
|
||
await new Promise((r) => setTimeout(r, 50))
|
||
const el = host.querySelector('.oa-print-page')
|
||
if (!el) throw new Error('print sheet missing')
|
||
const canvas = await html2canvas(el, {
|
||
scale: 2,
|
||
useCORS: true,
|
||
allowTaint: true,
|
||
backgroundColor: '#ffffff',
|
||
logging: false,
|
||
windowWidth: el.scrollWidth,
|
||
windowHeight: el.scrollHeight
|
||
})
|
||
const blob = await canvasToPdfBlob(canvas, el)
|
||
return { blob, filename }
|
||
} finally {
|
||
host.remove()
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @returns {Promise<{ ok: boolean, message?: string, mode?: 'preview' | 'download' }>}
|
||
*/
|
||
export async function exportOaApprovalPdf(detail, opts = {}) {
|
||
if (!detail) {
|
||
return { ok: false, message: '暂无审批详情,无法导出 PDF' }
|
||
}
|
||
|
||
const inMini = isWeChatMiniWebView()
|
||
printNavLog('export start', {
|
||
inMini,
|
||
instanceId: detail && (detail.id || detail.instanceId),
|
||
title: detail && (detail.title || detail.appName)
|
||
})
|
||
|
||
let blob
|
||
let filename
|
||
try {
|
||
;({ blob, filename } = await generateOaApprovalPdfBlob(detail, opts))
|
||
printNavLog('pdf blob ready', {
|
||
filename,
|
||
blobSize: blob && typeof blob.size === 'number' ? blob.size : -1
|
||
})
|
||
} catch (e) {
|
||
printNavLog('pdf generate fail', String(e && e.message ? e.message : e))
|
||
return {
|
||
ok: false,
|
||
message: (e && e.message) || '生成 PDF 失败'
|
||
}
|
||
}
|
||
|
||
if (inMini) {
|
||
try {
|
||
const file = new File([blob], filename, { type: 'application/pdf' })
|
||
printNavLog('upload start', { filename, fileSize: file.size })
|
||
const res = await uploadAttachment(file)
|
||
const fileUrl = String(res?.fileUrl || res?.data?.fileUrl || '').trim()
|
||
printNavLog('upload done', {
|
||
hasFileUrl: !!fileUrl,
|
||
fileUrlPreview: fileUrl.slice(0, 160),
|
||
resKeys: res && typeof res === 'object' ? Object.keys(res) : []
|
||
})
|
||
if (!fileUrl) {
|
||
return { ok: false, message: '上传 PDF 失败:无文件地址' }
|
||
}
|
||
|
||
const nav = await navigateToHostPdfPreview({
|
||
fileUrl,
|
||
fileName: filename
|
||
})
|
||
printNavLog('navigate result', nav)
|
||
if (!nav || !nav.ok) {
|
||
return {
|
||
ok: false,
|
||
message:
|
||
(nav && nav.message) || '无法跳转预览页,请升级微信后重试'
|
||
}
|
||
}
|
||
return { ok: true, mode: 'preview' }
|
||
} catch (e) {
|
||
printNavLog('upload/navigate fail', String(e && e.message ? e.message : e))
|
||
return {
|
||
ok: false,
|
||
message: (e && e.message) || '上传或打开 PDF 失败'
|
||
}
|
||
}
|
||
}
|
||
|
||
try {
|
||
printNavLog('browser download path', { filename })
|
||
const href = URL.createObjectURL(blob)
|
||
const a = document.createElement('a')
|
||
a.href = href
|
||
a.download = filename
|
||
document.body.appendChild(a)
|
||
a.click()
|
||
a.remove()
|
||
setTimeout(() => URL.revokeObjectURL(href), 2000)
|
||
return { ok: true, mode: 'download' }
|
||
} catch (e) {
|
||
printNavLog('browser download fail', String(e && e.message ? e.message : e))
|
||
return {
|
||
ok: false,
|
||
message: (e && e.message) || '下载 PDF 失败'
|
||
}
|
||
}
|
||
}
|