刘光辉
11 小时以前 0dfe84494048ce27ba8449831782128412d3eb13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
<script lang="ts" setup>
import { computed, onUnmounted, ref, watch } from 'vue';
 
import { Button, Empty, Result, Spin } from 'ant-design-vue';
 
import type { CustomPrintConfig, CustomPrintPreviewExpose } from './types';
 
const props = defineProps<{
  config: CustomPrintConfig;
}>();
 
const emit = defineEmits<{
  error: [message: string];
  loaded: [];
  loading: [loading: boolean];
}>();
 
// 预加载所有打印模板
const templateModules = import.meta.glob('/src/print-templates/**/*.html', {
  eager: true,
  import: 'default',
  query: '?raw',
});
 
// 构建模板路径映射
const templateMap = Object.entries(templateModules).reduce(
  (map, [path, content]) => {
    const publicPath = path.replace('/src', '');
    map[publicPath] = content as string;
    map[publicPath.replace('.html', '')] = content as string;
    return map;
  },
  {} as Record<string, string>,
);
 
const htmlContent = ref('');
const iframeRef = ref<HTMLIFrameElement | null>(null);
const loading = ref(false);
const errorMessage = ref<null | string>(null);
const requestId = ref(0);
 
const effectiveType = computed<NonNullable<CustomPrintConfig['type']>>(() => props.config.type || 'html-file');
const isHtmlFileMode = computed(() => effectiveType.value === 'html-file');
 
watch(
  () => props.config,
  () => {
    reload();
  },
  { deep: true, immediate: true },
);
 
onUnmounted(() => {
  requestId.value++;
});
 
function normalizeTemplatePath(filePath: string) {
  let normalizedPath = filePath;
  const match = filePath.match(/(\/[^/]+_app_[^/]+)(\/print-templates\/)/);
  const appPrefix = match?.[1];
  if (appPrefix) {
    normalizedPath = filePath.replace(appPrefix, '');
  }
 
  if (!normalizedPath.includes('/')) {
    normalizedPath = `/print-templates/${normalizedPath}`;
  } else if (!normalizedPath.startsWith('/')) {
    normalizedPath = `/${normalizedPath}`;
  }
 
  return normalizedPath;
}
 
function findTemplate(filePath: string) {
  const normalizedPath = normalizeTemplatePath(filePath);
  const html = templateMap[normalizedPath] || templateMap[`${normalizedPath}.html`];
 
  if (!html) {
    throw new Error(`模板文件不存在: ${normalizedPath},请确保文件放在 src/print-templates/ 目录下`);
  }
 
  return html;
}
 
function setLoading(value: boolean) {
  loading.value = value;
  emit('loading', value);
}
 
async function loadHtmlFile(filePath: string, currentRequestId: number) {
  setLoading(true);
  errorMessage.value = null;
 
  try {
    const html = findTemplate(filePath);
    const dataScript = `<script>window.templateData = ${JSON.stringify(props.config.data || {})};<\/script>`;
    let renderedHtml = dataScript + html;
    renderedHtml = await convertImagesToBase64(renderedHtml);
 
    if (currentRequestId !== requestId.value) return;
 
    htmlContent.value = renderedHtml;
    setLoading(false);
    emit('loaded');
  } catch (error: any) {
    if (currentRequestId !== requestId.value) return;
 
    console.error('[CustomPrintPreviewPane] 加载HTML模板失败:', error);
    const message = error.message || '加载模板失败';
    errorMessage.value = message;
    setLoading(false);
    emit('error', message);
  }
}
 
// 将图片转换为 base64(用于 iframe 内联显示)
async function convertImagesToBase64(html: string): Promise<string> {
  const imgRegex = /src=["'](\/[^"']+\.(?:png|jpg|jpeg|gif|svg))["']/gi;
  const matches = [...html.matchAll(imgRegex)];
 
  if (matches.length === 0) return html;
 
  const baseUrl = window.location.origin;
  let result = html;
  for (const match of matches) {
    const fullMatch = match[0];
    const imagePath = match[1];
 
    try {
      const imageUrl = `${baseUrl}${imagePath}`;
      const base64Data = await fetchImageAsBase64(imageUrl);
 
      if (base64Data) {
        result = result.replace(fullMatch, `src="${base64Data}"`);
      }
    } catch (error) {
      console.warn(`[CustomPrintPreviewPane] 无法加载图片: ${imagePath}`, error);
    }
  }
 
  return result;
}
 
async function fetchImageAsBase64(url: string): Promise<null | string> {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
 
    const blob = await response.blob();
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.addEventListener('loadend', () => resolve(reader.result as string));
      reader.addEventListener('error', () => reject(new Error('FileReader error')));
      reader.readAsDataURL(blob);
    });
  } catch (error) {
    console.error(`[CustomPrintPreviewPane] 获取图片失败: ${url}`, error);
    return null;
  }
}
 
function print() {
  if (!iframeRef.value?.contentWindow) return;
 
  try {
    iframeRef.value.contentWindow.print();
  } catch (error) {
    console.error('[CustomPrintPreviewPane] iframe 打印失败:', error);
  }
}
 
function reload() {
  const currentRequestId = requestId.value + 1;
  requestId.value = currentRequestId;
  htmlContent.value = '';
  errorMessage.value = null;
 
  if (isHtmlFileMode.value && props.config.template) {
    loadHtmlFile(props.config.template, currentRequestId);
    return;
  }
 
  htmlContent.value = props.config.template || '';
  setLoading(false);
  emit('loaded');
}
 
defineExpose<CustomPrintPreviewExpose>({ print, reload });
</script>
 
<template>
  <div class="custom-print-preview-pane">
    <div v-if="loading" class="loading-state">
      <Spin size="large" tip="加载模板中..." />
    </div>
 
    <div v-else-if="errorMessage" class="error-state">
      <Result status="error" title="加载模板失败" :sub-title="errorMessage">
        <template #extra>
          <Button type="primary" @click="reload">重新加载</Button>
        </template>
      </Result>
    </div>
 
    <div v-else-if="isHtmlFileMode && htmlContent" class="iframe-container">
      <iframe ref="iframeRef" class="print-iframe" :srcdoc="htmlContent" frameborder="0"></iframe>
    </div>
 
    <div v-else-if="effectiveType === 'html' && htmlContent" class="html-template-wrapper" v-html="htmlContent"></div>
 
    <div v-else class="empty-state">
      <Empty description="未配置打印模板" />
    </div>
  </div>
</template>
 
<style lang="scss" scoped>
.custom-print-preview-pane {
  width: 100%;
  height: 100%;
 
  .iframe-container {
    width: 100%;
    height: 100%;
    background: white;
  }
 
  .print-iframe {
    width: 100%;
    height: 100%;
    background: white;
    border: none;
  }
 
  :deep(.html-template-wrapper) {
    min-height: 100%;
    background: white;
 
    table {
      border-collapse: collapse;
    }
 
    img {
      max-width: 100%;
    }
  }
 
  .loading-state,
  .error-state {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    background: white;
  }
 
  .empty-state {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 400px;
    background: white;
  }
}
</style>