yyb
昨天 ea7142e7ec94d4896c8d0c9af85656edb24e32e1
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
import QRCode from "qrcode";
 
const PRINT_TITLE = "销售发货单";
 
const escapeHtml = (value) =>
  String(value ?? "")
    .replaceAll("&", "&")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#39;");
 
const toNumber = (value) => {
  const num = Number(value);
  return Number.isFinite(num) ? num : 0;
};
 
const formatDisplayDate = (value) => {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return String(value);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}/${month}/${day}`;
};
 
const getItemArea = (item) => toNumber(item?.area || item?.settleTotalArea || item?.actualTotalArea);
 
const getOrderNo = (data, row, item) =>
  item?.salesContractNo || item?.orderNo || data?.salesContractNo || row?.salesContractNo || "";
 
const PRODUCT_NAME_FIELD_KEYS = [
  "productDescription",
  "productName",
  "name",
  "title",
  "goodsName",
  "materialName",
  "glassName",
];
 
const PRODUCT_NAME_LIST_FIELD_KEYS = [
  "productDescriptionList",
  "productNameList",
  "productDescriptions",
  "productNames",
  "nameList",
  "goodsNameList",
  "detailProductNames",
  "productInfoList",
];
 
const SPECIFICATION_FIELD_KEYS = ["specificationModel", "specification", "model", "spec"];
 
const normalizeNameList = (value) => {
  if (Array.isArray(value)) {
    return value
      .flatMap((item) => normalizeNameList(item))
      .map((item) => String(item).trim())
      .filter(Boolean);
  }
  if (value && typeof value === "object") {
    const objectListNames = PRODUCT_NAME_LIST_FIELD_KEYS.flatMap((key) => normalizeNameList(value?.[key]));
    if (objectListNames.length) return objectListNames;
    return PRODUCT_NAME_FIELD_KEYS.flatMap((key) => normalizeNameList(value?.[key]));
  }
  if (typeof value === "string") {
    const text = value.trim();
    if (!text) return [];
    const parts = text
      .split(/[,\n,、;;]/)
      .map((item) => item.trim())
      .filter(Boolean);
    return parts.length > 1 ? parts : [text];
  }
  if (value === null || value === undefined) return [];
  const text = String(value).trim();
  return text ? [text] : [];
};
 
const extractNameListByKeys = (source, keys) => {
  if (!source || typeof source !== "object") return [];
  return keys.flatMap((key) => normalizeNameList(source?.[key]));
};
 
const resolveProductName = (item, fallbackNames, index) => {
  const itemNames = [
    ...extractNameListByKeys(item, PRODUCT_NAME_LIST_FIELD_KEYS),
    ...extractNameListByKeys(item, PRODUCT_NAME_FIELD_KEYS),
  ];
  if (itemNames.length > 1) {
    return itemNames[index] || itemNames[0] || "";
  }
  return itemNames[0] || fallbackNames[index] || fallbackNames[0] || "";
};
 
const resolveSpecificationModel = (...sources) => {
  for (const source of sources) {
    if (!source || typeof source !== "object") continue;
    for (const key of SPECIFICATION_FIELD_KEYS) {
      const value = source?.[key];
      if (value !== undefined && value !== null && String(value).trim()) {
        return String(value).trim();
      }
    }
  }
  return "";
};
 
const splitItemsByPage = (items, pageSize) => {
  const list = Array.isArray(items) ? items : [];
  if (list.length === 0) return [[]];
  const pages = [];
  for (let i = 0; i < list.length; i += pageSize) {
    pages.push(list.slice(i, i + pageSize));
  }
  return pages;
};
 
const normalizeInvoiceData = (raw, selectedRow) => {
  const data = raw ?? {};
  const groups = Array.isArray(data.groups)
    ? data.groups
    : Array.isArray(data.groupList)
      ? data.groupList
      : [];
  const dataLevelNames = [
    ...extractNameListByKeys(data, PRODUCT_NAME_LIST_FIELD_KEYS),
    ...extractNameListByKeys(data, PRODUCT_NAME_FIELD_KEYS),
  ];
 
  const items = groups.length
    ? groups.flatMap((group) => {
        const groupItems = Array.isArray(group?.items) ? group.items : [];
        const groupNames = [
          ...extractNameListByKeys(group, PRODUCT_NAME_LIST_FIELD_KEYS),
          ...extractNameListByKeys(group, PRODUCT_NAME_FIELD_KEYS),
        ];
        return groupItems.map((item, index) => ({
          ...item,
          // 优先使用明细自身产品名,兼容“名称数组/分隔字符串”的接口格式
          productDescription: resolveProductName(item, groupNames, index),
          specificationModel: resolveSpecificationModel(item, group, data),
          salesContractNo: group?.salesContractNo || item?.salesContractNo || "",
          widthHeight: item?.widthHeight || "",
        }));
      })
    : (Array.isArray(data.items) ? data.items : []).map((item, index) => ({
        ...item,
        productDescription: resolveProductName(item, dataLevelNames, index),
        specificationModel: resolveSpecificationModel(item, data, selectedRow),
        widthHeight: item?.widthHeight || "",
      }));
 
  return {
    ...data,
    items,
    customerName: data.customerName || selectedRow?.customerName || "",
    contactPerson: data.contactPerson || selectedRow?.contactPerson || "",
    contactPhone: data.contactPhone || selectedRow?.contactPhone || "",
    deliveryAddress:
      data.companyAddress || data.deliveryAddress || data.shippingAddress || selectedRow?.deliveryAddress || "",
    shipmentNo: data.externalOrderNo || data.shipmentNo || "",
    register: data.orderMaker || data.register || selectedRow?.entryPersonName || "",
    registerDate: data.executionDate || data.registerDate || data.entryDate || selectedRow?.entryDate || "",
  };
};
 
const groupByProduct = (items, data, row) => {
  const list = Array.isArray(items) ? items : [];
  const map = new Map();
  list.forEach((item) => {
    const key = `${item?.productDescription || ""}__${item?.specificationModel || ""}__${getOrderNo(
      data,
      row,
      item
    )}`;
    if (!map.has(key)) {
      map.set(key, {
        productName: item?.productDescription || "",
        specificationModel: item?.specificationModel || "",
        orderNo: getOrderNo(data, row, item),
        items: [],
      });
    }
    map.get(key).items.push(item);
  });
  return Array.from(map.values());
};
 
const renderItemRows = (items, startIndex) =>
  items
    .map((item, idx) => {
      const sizeText = item?.widthHeight
        ? escapeHtml(item.widthHeight)
        : item?.width || item?.height
          ? `${escapeHtml(item?.width)} * ${escapeHtml(item?.height)}`
          : "";
      return `
      <tr>
        <td>${startIndex + idx + 1}</td>
        <td class="left">${escapeHtml(item?.floorCode)}</td>
        <td>${sizeText}</td>
        <td>${toNumber(item?.quantity) || ""}</td>
        <td>${getItemArea(item) ? getItemArea(item).toFixed(2) : ""}</td>
        <td class="left">${escapeHtml(item?.remark)}</td>
        <td class="left">${escapeHtml(item?.processRequirement)}</td>
      </tr>
    `;
    })
    .join("");
 
export const printSalesDeliveryNote = async (rawData, selectedRow = {}, ledgerIds = null) => {
  const data = normalizeInvoiceData(rawData, selectedRow);
  const allItems = Array.isArray(data.items) ? data.items : [];
  const pageSize = 18;
  const itemPages = splitItemsByPage(allItems, pageSize);
  const totalPages = itemPages.length;
 
  const ids =
    Array.isArray(ledgerIds) && ledgerIds.length > 0
      ? ledgerIds
      : selectedRow?.id !== undefined && selectedRow?.id !== null && selectedRow?.id !== ""
        ? [selectedRow.id]
        : [];
  const shipmentRef = String(
    data.shipmentNo || data.deliveryNo || data.externalOrderNo || selectedRow?.expressNumber || ""
  ).trim();
  const qrPayload = JSON.stringify({
    type: "FH",
    shipmentNo: shipmentRef,
    ledgerIds: ids,
  });
  let qrDataUrl = "";
  try {
    qrDataUrl = await QRCode.toDataURL(qrPayload, { width: 160, margin: 1 });
  } catch {
    qrDataUrl = "";
  }
 
  const printWindow = window.open("", "_blank", "width=1200,height=900");
  if (!printWindow) {
    throw new Error("浏览器拦截了弹窗,请允许弹窗后重试");
  }
 
  const html = `
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>${PRINT_TITLE}</title>
    <style>
      body { margin: 0; padding: 0; font-family: "SimSun", serif; color: #222; }
      .page { width: 198mm; margin: 0 auto; padding: 4mm 4mm 6mm; box-sizing: border-box; page-break-after: always; }
      .page:last-child { page-break-after: auto; }
      .head-top {
        display: grid;
        grid-template-columns: 1fr auto 1fr;
        align-items: end;
        margin-bottom: 1px;
      }
      .factory {
        grid-column: 2;
        text-align: center;
        font-size: 20px;
        font-weight: 700;
        line-height: 1.2;
      }
      .page-mark {
        grid-column: 3;
        justify-self: end;
        font-size: 12px;
        margin-right: 8mm;
        margin-bottom: 1px;
        position: relative;
        top: 6mm;
      }
      .head-mid {
        display: grid;
        grid-template-columns: 1fr auto 1fr;
        align-items: center;
        margin-top: 6mm;
        margin-bottom: 0;
        position: relative;
      }
      .head-mid-left { font-size: 13px; text-align: left; }
      .head-mid-title-wrap { grid-column: 2; }
      .head-mid-title { font-size: 20px; font-weight: 700; text-align: center; line-height: 1; }
      .head-qr {
        width: 18mm;
        height: 18mm;
        object-fit: contain;
        display: block;
        position: absolute;
        left: calc(50% + 30mm);
        top: calc(50% - 4mm);
        transform: translateY(-50%);
      }
      .head-mid-right { font-size: 13px; text-align: right; padding-right: 8mm; }
      table { width: 100%; margin-top: 3mm; border-collapse: collapse; table-layout: fixed; border: 1px solid #222; }
      td, th { border: 1px solid #222; padding: 2px 4px; font-size: 13px; text-align: center; vertical-align: middle; }
      .left { text-align: left; }
      .group-title td { font-weight: 700; }
      .subtotal td, .total-row td { font-weight: 700; }
      .empty td { height: 120px; color: #666; }
      .footer { margin-top: 6px; display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 6px; font-size: 13px; }
      @media print {
        @page { size: A4 portrait; margin: 8mm; }
        .page { width: 100%; margin: 0; padding: 0; }
      }
    </style>
  </head>
  <body>
  ${itemPages
    .map((pageItems, pageIndex) => {
      const pageGroups = groupByProduct(pageItems, data, selectedRow);
      let serial = pageIndex * pageSize;
      const totalQty = toNumber(data.totalQuantity) || allItems.reduce((s, it) => s + toNumber(it?.quantity), 0);
      const totalArea = toNumber(data.totalArea) || allItems.reduce((s, it) => s + getItemArea(it), 0);
      return `
    <div class="page">
      <div class="head-top">
        <div></div>
        <div class="factory">鹤壁天沐钢化玻璃厂</div>
        <div class="page-mark">第${pageIndex + 1}页,共${totalPages}页</div>
      </div>
      <div class="head-mid">
        <div class="head-mid-left">对方单号: ${escapeHtml(data.deliveryNo || data.shippingNo || selectedRow.expressNumber || "")}</div>
        <div class="head-mid-title-wrap">
          <div class="head-mid-title">销售发货单</div>
        </div>
        ${qrDataUrl ? `<img class="head-qr" src="${qrDataUrl}" alt="二维码" />` : ""}
        <div class="head-mid-right">发货单号: ${escapeHtml(data.shipmentNo || data.deliveryNo || "")}</div>
      </div>
      <table>
        <tr>
          <td class="left" colspan="4">客户名称: ${escapeHtml(data.customerName || selectedRow.customerName || "")}</td>
          <td class="left" colspan="3">联系人: ${escapeHtml(data.contactPerson || selectedRow.contactPerson || "")}</td>
        </tr>
        <tr>
          <td class="left" colspan="4">发货地址: ${escapeHtml(data.deliveryAddress || data.shippingAddress || selectedRow.deliveryAddress || "")}</td>
          <td class="left" colspan="3">联系电话: ${escapeHtml(data.contactPhone || selectedRow.contactPhone || "")}</td>
        </tr>
        <tr>
          <th style="width:8%;">序号</th>
          <th style="width:22%;">楼层编号</th>
          <th style="width:20%;">宽(弧长)*高</th>
          <th style="width:10%;">数量</th>
          <th style="width:12%;">面积</th>
          <th style="width:10%;">备注</th>
          <th style="width:18%;">加工要求</th>
        </tr>
        ${
          pageGroups.length
            ? pageGroups
                .map((group) => {
                  const subQty = group.items.reduce((s, it) => s + toNumber(it?.quantity), 0);
                  const subArea = group.items.reduce((s, it) => s + getItemArea(it), 0);
                  const rows = renderItemRows(group.items, serial);
                  serial += group.items.length;
                  return `
          <tr class="group-title">
            <td colspan="5" class="left">产品名称: ${escapeHtml(group.productName)}${group.specificationModel ? ` 规格型号: ${escapeHtml(group.specificationModel)}` : ""}</td>
            <td colspan="2" class="left">订单编号: ${escapeHtml(group.orderNo)}</td>
          </tr>
          ${rows}
          <tr class="subtotal">
            <td colspan="3">小计:</td>
            <td>${subQty || ""}</td>
            <td>${subArea ? subArea.toFixed(2) : ""}</td>
            <td colspan="2"></td>
          </tr>
                  `;
                })
                .join("")
            : `<tr class="empty"><td colspan="7">暂无明细</td></tr>`
        }
        ${
          pageIndex === totalPages - 1
            ? `
        <tr class="total-row">
          <td colspan="3">合计:</td>
          <td>${totalQty || ""}</td>
          <td>${totalArea ? totalArea.toFixed(2) : ""}</td>
          <td colspan="2"></td>
        </tr>
            `
            : ""
        }
      </table>
      ${
        pageIndex === totalPages - 1
          ? `
      <div class="footer">
        <div>制 单 员: ${escapeHtml(data.register || selectedRow.entryPersonName || "")}</div>
        <div>制单日期: ${escapeHtml(formatDisplayDate(data.registerDate || data.entryDate || selectedRow.entryDate))}</div>
        <div>客户签字:</div>
        <div>签收日期:</div>
      </div>
          `
          : ""
      }
    </div>
      `;
    })
    .join("")}
  </body>
</html>
`;
 
  printWindow.document.write(html);
  printWindow.document.close();
  printWindow.onload = () => {
    setTimeout(() => {
      printWindow.focus();
      printWindow.print();
      printWindow.close();
    }, 300);
  };
};