祖安之光
2025-12-03 52bd5557cb7a3eeb467f75a2b9101bf7f097754f
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
// 引入工具
import PizZip from 'pizzip';
import Docxtemplater from 'docxtemplater';
import JSZipUtils from 'jszip-utils';
import { saveAs } from 'file-saver';
import ImageModule from 'docxtemplater-image-module-free'
// 加载 .docx 模板文件
function loadFile(url, callback) {
    JSZipUtils.getBinaryContent(url, callback);
}
 
// 下载生成的文档
export function download(file, name) {
    saveAs(file, name);
}
 
// 处理富文本,提取段落和缩进信息
function processRichText(html) {
    if (!html) return '';
 
    // 将HTML字符串转换为DOM对象
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');
 
    let result = [];
 
    // 处理普通段落
    const paragraphs = doc.querySelectorAll('p');
    paragraphs.forEach(p => {
        const style = p.getAttribute('style') || '';
        const indentMatch = style.match(/text-indent:\s*(\d+)pt/);
        const indent = indentMatch ? parseInt(indentMatch[1]) / 24 : 0;
        const text = p.textContent.trim();
 
        if (text) {
            const indentStr = indent > 0 ? '    '.repeat(indent) : '';
            result.push(indentStr + text);
        }
    });
 
    // 处理列表(ul/li)
    const lists = doc.querySelectorAll('ul');
    lists.forEach(ul => {
        const lis = ul.querySelectorAll('li');
        lis.forEach(li => {
            // 计算缩进层级
            let parent = li.parentElement;
            let indentLevel = 0;
            while (parent && parent !== ul) {
                if (parent.tagName === 'UL') indentLevel++;
                parent = parent.parentElement;
            }
 
            const text = li.textContent.trim();
            if (text) {
                // 使用不同符号表示不同层级
                const bullets = ['▪', '•', '▫', '◦'];
                const bullet = bullets[Math.min(indentLevel, bullets.length - 1)];
                const indentStr = '    '.repeat(indentLevel);
                result.push(indentStr + bullet + ' ' + text);
            }
        });
    });
 
    return result.join('\n'); // 用两个换行符分隔段落
}
 
function convertTreeToHtml(data) {
    let html = '';
 
    function buildList(items) {
        let listHtml = '<ul style="font-family: 宋体; font-size: 12pt; line-height: 1.5;">';
        items.forEach(item => {
            listHtml += `<li style="margin-bottom: 6pt;">${item.deptName}`;
 
            if (item.children && item.children.length > 0) {
                listHtml += buildList(item.children);
            }
            listHtml += '</li>';
        });
 
        listHtml += '</ul>';
        return listHtml;
    }
 
    html = buildList(data);
    return html;
}
 
function generateTableXML(clauses, deptList) {
    const allDeptNames = [...new Set(deptList.map(item => item.deptName))];
 
    // 构建数据映射
    const dataMap = {};
    deptList.forEach(item => {
        if (!dataMap[item.clauseNum]) dataMap[item.clauseNum] = {};
        dataMap[item.clauseNum][item.deptName] = item.chooseLab;
    });
 
    return `
    <w:tbl xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
      <w:tblPr>
        <w:tblW w:w="10000" w:type="pct"/>
        <!-- 边框设置 -->
        <w:tblBorders>
          <w:top w:val="single" w:sz="4" w:space="0" w:color="000000"/>
          <w:left w:val="single" w:sz="4" w:space="0" w:color="000000"/>
          <w:bottom w:val="single" w:sz="4" w:space="0" w:color="000000"/>
          <w:right w:val="single" w:sz="4" w:space="0" w:color="000000"/>
          <w:insideH w:val="single" w:sz="4" w:space="0" w:color="000000"/>
          <w:insideV w:val="single" w:sz="4" w:space="0" w:color="000000"/>
        </w:tblBorders>
        <w:tblLook w:val="04A0"/>
      </w:tblPr>
      
      <!-- 列宽定义 -->
      <w:tblGrid>
        <w:gridCol w:w="1500"/> <!-- 条款号列 -->
        <w:gridCol w:w="3500"/> <!-- 内容列 -->
        ${allDeptNames.map(() => '<w:gridCol w:w="2000"/>').join('')}
      </w:tblGrid>
      
      <!-- 表头 -->
      <w:tr>
        <w:tc>
          <w:tcPr><w:tcW w:w="1500" w:type="dxa"/></w:tcPr>
          <w:p><w:r><w:rPr><w:b/></w:rPr><w:t>条款号</w:t></w:r></w:p>
        </w:tc>
        <w:tc>
          <w:tcPr><w:tcW w:w="3500" w:type="dxa"/></w:tcPr>
          <w:p><w:r><w:rPr><w:b/></w:rPr><w:t>内容描述</w:t></w:r></w:p>
        </w:tc>
        ${allDeptNames.map(dept => `
          <w:tc>
            <w:tcPr><w:tcW w:w="2000" w:type="dxa"/></w:tcPr>
            <w:p><w:r><w:rPr><w:b/></w:rPr><w:t>${dept}</w:t></w:r></w:p>
          </w:tc>
        `).join('')}
      </w:tr>
      
      <!-- 数据行 -->
      ${clauses.map(clause => `
        <w:tr>
          <w:tc><w:p><w:r><w:t>${clause.clauseNum}</w:t></w:r></w:p></w:tc>
          <w:tc><w:p><w:r><w:t>${clause.content}</w:t></w:r></w:p></w:tc>
          ${allDeptNames.map(dept => `
            <w:tc>
              <w:p><w:r><w:t>${dataMap[clause.clauseNum]?.[dept] ?? 0}</w:t></w:r></w:p>
            </w:tc>
          `).join('')}
        </w:tr>
      `).join('')}
    </w:tbl>
  `;
}
 
 
function processTableHtml(html) {
    if (!html) return '';
 
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');
    const table = doc.querySelector('table');
    if (!table) return '';
 
    // 提取表格结构
    const rows = table.querySelectorAll('tr');
    const result = [];
 
    // 处理表头
    const headers = Array.from(rows[0].querySelectorAll('th'))
        .map(th => `${th.textContent.trim()}`)
        .join('\t');
    result.push(headers);
 
    // 处理数据行
    for (let i = 1; i < rows.length; i++) {
        const cells = rows[i].querySelectorAll('td');
        const rowData = Array.from(cells).map(cell => {
            const indent = cell.style.paddingLeft ? ' '.repeat(parseInt(cell.style.paddingLeft)/4) : '';
            const content = cell.textContent.trim();
            return indent + content;
        }).join('\t');
        result.push(rowData);
    }
 
    return result.join('\n');
}
 
function generateTableHtml(clauses, deptList) {
    const allDeptNames = [...new Set(deptList.map(item => item.deptName))];
    const dataMap = {};
 
    // 构建数据映射
    deptList.forEach(item => {
        if (!dataMap[item.clauseNum]) dataMap[item.clauseNum] = {};
        dataMap[item.clauseNum][item.deptName] = item.chooseLab? (item.chooseLab==1?'●':'○'):'○'
    });
 
    return `
    <table style="width: 100%;border-collapse: collapse;font-family: 'Microsoft YaHei', sans-serif;font-size: 10.5pt;margin-bottom: 12pt;border: 1px solid #ccc">
      <thead>
        <tr style="background-color: #f5f5f5;width: 100%">
          <th style="padding: 6pt 8pt;border: 1px solid #ccc;text-align: center;font-weight: bold;min-width: 60pt">条款号</th>
          <th style="padding: 6pt 8pt;border: 1px solid #cccccc;text-align: left;font-weight: bold">内容描述</th>
          ${allDeptNames.map(dept => `
            <th style="padding: 6pt 8pt;border: 1pt solid #cccccc;text-align: center;font-weight: bold;min-width: 50pt">${dept}</th>
          `).join('')}
        </tr>
      </thead>
      <tbody>
        ${clauses.map(clause => `
          <tr>
            <td style="padding: 5pt 8pt;
              border: 1pt solid #e0e0e0;
              text-align: center;
              vertical-align: top">${clause.clauseNum}</td>
            <td style="
              padding: 5pt 8pt;
              border: 1pt solid #e0e0e0;
              text-align: left;
              vertical-align: top">${clause.content}</td>
            ${allDeptNames.map(dept => `
              <td style="
                padding: 5pt 8pt;
                border: 1pt solid #e0e0e0;
                text-align: center;
                vertical-align: top">
                ${dataMap[clause.clauseNum]?.[dept] ?? '○'}
              </td>
            `).join('')}
          </tr>
        `).join('')}
      </tbody>
    </table>
  `;
}
const base64Regex =
    /^(?:data:)?image\/(png|jpg|jpeg|svg|svg\+xml);base64,/;
 
const validBase64 =
    /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
function base64Parser(tagValue) {
    if (
        typeof tagValue !== "string" ||
        !base64Regex.test(tagValue)
    ) {
        return false;
    }
 
    const stringBase64 = tagValue.replace(base64Regex, "");
 
    if (!validBase64.test(stringBase64)) {
        throw new Error(
            "Error parsing base64 data, your data contains invalid characters"
        );
    }
 
    // For nodejs, return a Buffer
    if (typeof Buffer !== "undefined" && Buffer.from) {
        return Buffer.from(stringBase64, "base64");
    }
 
    // For browsers, return a string (of binary content) :
    const binaryString = window.atob(stringBase64);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes.buffer;
}
 
function getDimensionsFromBase64Sync(base64Str) {
    try {
        // 去除 data:image/...;base64, 前缀
        const base64Data = base64Str.replace(/^data:image\/\w+;base64,/, '');
 
        // 将base64转换为二进制
        const binaryString = atob(base64Data);
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
            bytes[i] = binaryString.charCodeAt(i);
        }
 
        return parseImageDimensions(bytes);
    } catch (error) {
        console.warn('解析图片尺寸失败:', error);
        return { width: 550, height: 400 };
    }
}
 
function parseImageDimensions(bytes) {
    if (bytes.length < 8) {
        return { width: 550, height: 400 };
    }
 
    // 检查 PNG 格式 (89 50 4E 47 0D 0A 1A 0A)
    if (bytes[0] === 0x89 && bytes[1] === 0x50 &&
        bytes[2] === 0x4E && bytes[3] === 0x47) {
        return parsePNGDimensions(bytes);
    }
 
    // 检查 JPEG 格式 (FF D8)
    if (bytes[0] === 0xFF && bytes[1] === 0xD8) {
        return parseJPEGDimensions(bytes);
    }
 
    return { width: 550, height: 400 };
}
 
// 解析 PNG 尺寸
function parsePNGDimensions(bytes) {
    // PNG 的宽高在 IHDR chunk 中(偏移 16-24 字节)
    if (bytes.length >= 24) {
        const view = new DataView(bytes.buffer);
        const width = view.getUint32(16, false);  // 大端序
        const height = view.getUint32(20, false);
        return { width, height };
    }
    return { width: 550, height: 400 };
}
 
// 解析 JPEG 尺寸
function parseJPEGDimensions(bytes) {
    let i = 2; // 跳过 FFD8
 
    while (i < bytes.length - 1) {
        // JPEG 标记开始
        if (bytes[i] === 0xFF) {
            const marker = bytes[i + 1];
 
            // SOF0, SOF1, SOF2 (Start of Frame markers)
            if ((marker >= 0xC0 && marker <= 0xC3) ||
                (marker >= 0xC5 && marker <= 0xC7) ||
                (marker >= 0xC9 && marker <= 0xCB) ||
                (marker >= 0xCD && marker <= 0xCF)) {
 
                if (i + 7 < bytes.length) {
                    const height = (bytes[i + 5] << 8) | bytes[i + 6];
                    const width = (bytes[i + 7] << 8) | bytes[i + 8];
                    return { width, height };
                }
                break;
            }
 
            // 跳过当前段
            const length = (bytes[i + 2] << 8) | bytes[i + 3];
            i += length + 2;
        } else {
            i++;
        }
    }
 
    return { width: 550, height: 400 };
}
 
const imageOptions = {
    getImage(tagValue) {
        return base64Parser(tagValue);
    },
    getSize(img, tagValue, tagName, context) {
        const dimensions = getDimensionsFromBase64Sync(tagValue);
        const { width, height } = dimensions;
        const targetWidth = 550;
        const scale = targetWidth / width;
        let targetHeight = height * scale;
        targetHeight = Math.max(100, Math.min(800, targetHeight));
        return [targetWidth, Math.round(targetHeight)];
    },
};
 
const base64DataURLToArrayBuffer = (dataURL) => {
    // 返回包含 ArrayBuffer 和原始 base64 字符串的对象
    const base64Regex = /^data:image\/(png|jpg|jpeg|svg|svg\+xml);base64,/;
    if (!base64Regex.test(dataURL)) {
        return { buffer: null, base64: dataURL };
    }
 
    const stringBase64 = dataURL.replace(base64Regex, "");
    let binaryString = window.atob(stringBase64);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
 
    return {
        buffer: bytes.buffer,  // 图片模块需要的 ArrayBuffer
        base64: stringBase64   // 保留原始 base64 字符串(不带前缀)
    };
};
 
// 生成并下载 Word 文档
export function generateWordDocument(templatePath, data, name) {
    // 处理部门表格数据
    // if (data.clauses && data.duties) {
    //     const tableHtml = generateTableHtml(data.clauses, data.duties);
    //     data.departmentsTable = processTableHtml(tableHtml);
    // }
 
    if (data.productServiceImages && Array.isArray(data.productServiceImages)) {
        // 确保是纯 base64 字符串数组
        data.productServiceImageArray = data.productServiceImages.map(item =>
            typeof item === 'object' ? item.image : item
        ).filter(img => img && typeof img === 'string');
 
        // 为前10张图片创建单独的图片变量
        data.productServiceImageArray.slice(0, 10).forEach((img, index) => {
            data[`productServiceImage${index + 1}`] = img;
        });
 
        // 创建带元数据的对象数组
        data.productServiceImageObjects = data.productServiceImageArray.map((img, index) => ({
            image: img,  // 这个字段会作为图片插入
            index: index + 1,
            description: `产品和服务实现过程图 ${index + 1}`
        }));
 
        data.productServiceCount = data.productServiceImageArray.length;
        data.hasProductServiceImages = data.productServiceImageArray.length > 0;
    }
    // 处理富文本字段(如果有)
    if (data.summaries && typeof data.summaries === 'string') {
        data.summaries = processRichText(data.summaries);
    }
    if (data.policies && typeof data.policies === 'string') {
        data.policies = processRichText(data.policies);
    }
 
    // 处理树形结构数据(如果有)
    if (data.deptList && Array.isArray(data.deptList)) {
        data.departmentsHtml = processRichText(convertTreeToHtml(data.deptList));
    }
    if (data.orgChart && typeof data.orgChart !== 'string') {
        console.warn("orgChart 不是字符串,可能被意外转换:", data.orgChart);
        delete data.orgChart; // 避免传递无效数据
    }
 
    loadFile(templatePath, function (error, content) {
        if (error) {
            throw error;
        }
 
        try {
            // 加载模板文件内容到 PizZip
            const zip = new PizZip(content);
            const imageModule = new ImageModule(imageOptions);
            const doc = new Docxtemplater(zip, {
                paragraphLoop: true,
                linebreaks: true,
                modules: [imageModule]
            });
 
            // 设置模板中的占位符数据
            doc.setData(data);
 
            // 渲染文档
            doc.render();
 
            // 替换占位符
            // let xml = zip.files['word/document.xml'].asText();
            // xml = xml.replace('<!-- TABLE_PLACEHOLDER -->', data.tableXML);
            // zip.file('word/document.xml', xml);
 
            // 生成最终的文档 Blob
            const fileWord = doc.getZip().generate({
                type: 'blob',
                mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            });
 
            saveAs(fileWord, name);
        } catch (error) {
            console.error('Error rendering document:', error);
            throw error;
        }
    });
}