From b86df39a1530f12b467a65fe50da801510ff94c9 Mon Sep 17 00:00:00 2001
From: zhangwencui <1064582902@qq.com>
Date: 星期四, 26 十一月 2026 14:06:02 +0800
Subject: [PATCH] 标签机打印支持

---
 src/views/mes/dv/machinery/index.vue                |  337 ++++++++++++++++++++++++-----------------------
 src/views/wls/productsales/modules/qrcode-modal.vue |   25 ++-
 2 files changed, 191 insertions(+), 171 deletions(-)

diff --git a/src/views/mes/dv/machinery/index.vue b/src/views/mes/dv/machinery/index.vue
index 6b8476d..0f1f93d 100644
--- a/src/views/mes/dv/machinery/index.vue
+++ b/src/views/mes/dv/machinery/index.vue
@@ -1,41 +1,39 @@
 <script lang="ts" setup>
-import type { VxeTableGridOptions } from '#/adapter/vxe-table';
-import type { MesDvMachineryApi } from '#/api/mes/dv/machinery';
-import type { MesDvMachineryTypeApi } from '#/api/mes/dv/machinery/type';
+  import type { VxeTableGridOptions } from "#/adapter/vxe-table";
+  import type { MesDvMachineryApi } from "#/api/mes/dv/machinery";
+  import type { MesDvMachineryTypeApi } from "#/api/mes/dv/machinery/type";
 
-import { ref } from 'vue';
+  import { ref } from "vue";
 
-import { Page, useVbenModal } from '@vben/common-ui';
-import { downloadFileFromBlobPart } from '@vben/utils';
+  import { Page, useVbenModal } from "@vben/common-ui";
+  import { downloadFileFromBlobPart } from "@vben/utils";
 
-import { Button, message } from 'ant-design-vue';
-import QRCode from 'qrcode';
+  import { Button, message } from "ant-design-vue";
+  import QRCode from "qrcode";
 
-import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
-import {
-  deleteMachinery,
-  deleteMachineryList,
-  exportMachinery,
-  getMachineryPage,
-} from '#/api/mes/dv/machinery';
-import { $t } from '#/locales';
-import { MachineryTypeTree } from '#/views/mes/dv/machinery/type/components';
+  import { ACTION_ICON, TableAction, useVbenVxeGrid } from "#/adapter/vxe-table";
+  import {
+    deleteMachinery,
+    deleteMachineryList,
+    exportMachinery,
+    getMachineryPage,
+  } from "#/api/mes/dv/machinery";
+  import { $t } from "#/locales";
+  import { MachineryTypeTree } from "#/views/mes/dv/machinery/type/components";
 
-import { useGridColumns, useGridFormSchema } from './data';
-import Form from './modules/form.vue';
-import ImportForm from './modules/import-form.vue';
+  import { useGridColumns, useGridFormSchema } from "./data";
+  import Form from "./modules/form.vue";
+  import ImportForm from "./modules/import-form.vue";
 
-const selectedMachineryTypeId = ref<number>(); // 閫変腑璁惧绫诲瀷缂栧彿
-const checkedIds = ref<number[]>([]);
-const checkedRows = ref<MesDvMachineryApi.Machinery[]>([]);
+  const selectedMachineryTypeId = ref<number>(); // 閫変腑璁惧绫诲瀷缂栧彿
+  const checkedIds = ref<number[]>([]);
 function handleRowCheckboxChange({
   records,
-}: {
-  records: MesDvMachineryApi.Machinery[];
-}) {
-  checkedIds.value = records.map((item) => item.id!);
-  checkedRows.value = records;
-}
+  }: {
+    records: MesDvMachineryApi.Machinery[];
+  }) {
+    checkedIds.value = records.map(item => item.id!);
+  }
 
 /**
  * 琛ㄦ牸鏁版嵁閲嶈浇鍚庯紙鏌ヨ/缈婚〉/鍒锋柊/鍒囨崲璁惧绫诲瀷锛夋竻绌哄嬀閫夛紝
@@ -60,100 +58,115 @@
   gridApi.query();
 }
 
-/** 鍒涘缓璁惧 */
-function handleCreate() {
-  formModalApi.setData({ formType: 'create' }).open();
-}
+  /** 鍒涘缓璁惧 */
+  function handleCreate() {
+    formModalApi.setData({ formType: "create" }).open();
+  }
 
-/** 鎵撳嵃璁惧浜岀淮鐮侊紙A4 鏍囩锛岄粯璁� 3 鍒� 脳 4 琛岋紱鏍囩绾稿昂瀵稿悗缁彲璋冿級 */
-async function handlePrintQrcode(rows: MesDvMachineryApi.Machinery[]) {
-  if (!rows || rows.length === 0) {
-    message.warning('璇峰厛鍕鹃�夎鎵撳嵃浜岀淮鐮佺殑璁惧');
-    return;
+  /** 浣跨敤绯荤粺鎵撳嵃椹卞姩鎸� 40脳40 mm 鏍囩閫愬紶鎵撳嵃璁惧浜岀淮鐮侊紙閫傞厤 DT-360 USB锛� */
+  async function handlePrintQrcode(rows: MesDvMachineryApi.Machinery[]) {
+    if (!rows || rows.length === 0) {
+      message.warning("璇峰厛鍕鹃�夎鎵撳嵃浜岀淮鐮佺殑璁惧");
+      return;
+    }
+    const labels = await Promise.all(
+      rows.map(async row => ({
+        code: row.code ?? "",
+        name: row.name ?? "",
+        workshop: row.workshopName ?? "",
+        workstation: row.workstationName ?? "",
+        img: await QRCode.toDataURL(row.code ?? "", {
+          width: 240,
+          margin: 1,
+          errorCorrectionLevel: "M",
+        }),
+      }))
+    );
+    const labelHtml = labels
+      .map(
+        item => `<div class="label">
+          <img src="${item.img}" alt="浜岀淮鐮�" />
+          <div class="name">${escapeHtml(item.name)}</div>
+          <div class="meta">缂栧彿锛�${escapeHtml(item.code)}</div>
+          <div class="meta">${escapeHtml(
+            [item.workshop, item.workstation].filter(Boolean).join(" / ")
+          )}</div>
+        </div>`
+      )
+      .join("");
+    const html = `<!doctype html>
+  <html>
+  <head>
+  <meta charset="utf-8" />
+  <title>璁惧浜岀淮鐮佹爣绛�</title>
+  <style>
+    @page { size: 40mm 40mm; margin: 0; }
+    * { box-sizing: border-box; margin: 0; padding: 0; }
+    html, body, .sheet { width: 40mm; margin: 0; padding: 0; color: #000; }
+    body { font-family: SimSun, "瀹嬩綋", serif; }
+    .label { width: 40mm; height: 40mm; padding: 1mm 1.5mm; overflow: hidden; text-align: center;
+      display: flex; flex-direction: column; align-items: center; page-break-after: always; break-after: page; }
+    .label:last-child { page-break-after: auto; break-after: auto; }
+    .label img { width: 24mm; height: 24mm; flex: 0 0 auto; }
+    .name { width: 37mm; margin-top: .5mm; overflow: hidden; font-size: 9pt; font-weight: bold;
+      line-height: 1.2; text-overflow: ellipsis; white-space: nowrap; }
+    .meta { width: 37mm; overflow: hidden; font-size: 7pt; line-height: 1.2;
+      text-overflow: ellipsis; white-space: nowrap; }
+  </style>
+  </head>
+  <body><div class="sheet">${labelHtml}</div></body>
+  </html>`;
+    const win = window.open("", "_blank");
+    if (!win) {
+      message.warning("娴忚鍣ㄦ嫤鎴簡鎵撳嵃绐楀彛锛岃鍏佽寮圭獥鍚庨噸璇�");
+      return;
+    }
+    win.document.write(html);
+    win.document.close();
+    win.onload = () => {
+      setTimeout(() => {
+        win.focus();
+        win.print();
+      }, 300);
+    };
   }
-  const labels = await Promise.all(
-    rows.map(async (row) => ({
-      code: row.code ?? '',
-      name: row.name ?? '',
-      workshop: row.workshopName ?? '',
-      workstation: row.workstationName ?? '',
-      img: await QRCode.toDataURL(row.code ?? '', {
-        width: 240,
-        margin: 1,
-        errorCorrectionLevel: 'M',
-      }),
-    })),
-  );
-  const labelHtml = labels
-    .map(
-      (item) => `<div class="label">
-        <img src="${item.img}" alt="浜岀淮鐮�" />
-        <div class="name">${escapeHtml(item.name)}</div>
-        <div class="meta">缂栧彿锛�${escapeHtml(item.code)}</div>
-        <div class="meta">${escapeHtml([item.workshop, item.workstation].filter(Boolean).join(' / '))}</div>
-      </div>`,
-    )
-    .join('');
-  const html = `<!doctype html>
-<html>
-<head>
-<meta charset="utf-8" />
-<title>璁惧浜岀淮鐮佹爣绛�</title>
-<style>
-  body { font-family: SimSun, "瀹嬩綋", serif; margin: 0; padding: 8mm; color: #000; }
-  .sheet { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4mm; }
-  .label { border: 1px dashed #999; border-radius: 2mm; padding: 3mm 2mm; text-align: center; page-break-inside: avoid; }
-  .label img { width: 30mm; height: 30mm; }
-  .name { font-size: 13px; font-weight: bold; margin-top: 1mm; }
-  .meta { font-size: 11px; line-height: 1.4; }
-  @page { size: A4; margin: 8mm; }
-</style>
-</head>
-<body><div class="sheet">${labelHtml}</div></body>
-</html>`;
-  const win = window.open('', '_blank');
-  if (!win) {
-    message.warning('娴忚鍣ㄦ嫤鎴簡鎵撳嵃绐楀彛锛岃鍏佽寮圭獥鍚庨噸璇�');
-    return;
-  }
-  win.document.write(html);
-  win.document.close();
-  win.onload = () => {
-    win.focus();
-    win.print();
-  };
+
+  /** Print rows selected in the grid instead of relying on cached selection data. */
+function handlePrintCheckedQrcode() {
+  const rows = gridApi.grid.getCheckboxRecords() as MesDvMachineryApi.Machinery[];
+  return handlePrintQrcode(rows);
 }
 
 function escapeHtml(value: any): string {
-  return String(value ?? '')
-    .replace(/&/g, '&amp;')
-    .replace(/</g, '&lt;')
-    .replace(/>/g, '&gt;')
-    .replace(/"/g, '&quot;');
-}
+    return String(value ?? "")
+      .replace(/&/g, "&amp;")
+      .replace(/</g, "&lt;")
+      .replace(/>/g, "&gt;")
+      .replace(/"/g, "&quot;");
+  }
 
-/** 鏌ョ湅璁惧 */
-function handleDetail(row: MesDvMachineryApi.Machinery) {
-  formModalApi.setData({ id: row.id, formType: 'detail' }).open();
-}
+  /** 鏌ョ湅璁惧 */
+  function handleDetail(row: MesDvMachineryApi.Machinery) {
+    formModalApi.setData({ id: row.id, formType: "detail" }).open();
+  }
 
-/** 缂栬緫璁惧 */
-function handleEdit(row: MesDvMachineryApi.Machinery) {
-  formModalApi.setData({ id: row.id, formType: 'update' }).open();
-}
+  /** 缂栬緫璁惧 */
+  function handleEdit(row: MesDvMachineryApi.Machinery) {
+    formModalApi.setData({ id: row.id, formType: "update" }).open();
+  }
 
-/** 鍒犻櫎璁惧 */
-async function handleDelete(row: MesDvMachineryApi.Machinery) {
-  const hideLoading = message.loading({
-    content: $t('ui.actionMessage.deleting', [row.name]),
-    duration: 0,
-  });
-  try {
-    await deleteMachinery(row.id!);
-    message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
-    handleRefresh();
-  } finally {
-    hideLoading();
+  /** 鍒犻櫎璁惧 */
+  async function handleDelete(row: MesDvMachineryApi.Machinery) {
+    const hideLoading = message.loading({
+      content: $t("ui.actionMessage.deleting", [row.name]),
+      duration: 0,
+    });
+    try {
+      await deleteMachinery(row.id!);
+      message.success($t("ui.actionMessage.deleteSuccess", [row.name]));
+      handleRefresh();
+    } finally {
+      hideLoading();
   }
 }
 
@@ -161,51 +174,51 @@
 async function handleDeleteBatch() {
   if (checkedIds.value.length === 0) {
     return;
-  }
-  const count = checkedIds.value.length;
-  const hideLoading = message.loading({
-    content: $t('ui.actionMessage.deleting', [`${count} 鍙癭]),
-    duration: 0,
-  });
-  try {
-    await deleteMachineryList(checkedIds.value);
-    message.success($t('ui.actionMessage.deleteSuccess', [`${count} 鍙癭]));
-  } finally {
-    hideLoading();
-    handleDataChange();
+    }
+    const count = checkedIds.value.length;
+    const hideLoading = message.loading({
+      content: $t("ui.actionMessage.deleting", [`${count} 鍙癭]),
+      duration: 0,
+    });
+    try {
+      await deleteMachineryList(checkedIds.value);
+      message.success($t("ui.actionMessage.deleteSuccess", [`${count} 鍙癭]));
+    } finally {
+      hideLoading();
+      handleDataChange();
     handleRefresh();
   }
 }
 
-/** 瀵煎嚭璁惧 */
-async function handleExport() {
-  const data = await exportMachinery(await gridApi.formApi.getValues());
-  downloadFileFromBlobPart({ fileName: '璁惧鍙拌处.xls', source: data });
-}
+  /** 瀵煎嚭璁惧 */
+  async function handleExport() {
+    const data = await exportMachinery(await gridApi.formApi.getValues());
+    downloadFileFromBlobPart({ fileName: "璁惧鍙拌处.xls", source: data });
+  }
 
-/** 瀵煎叆璁惧 */
+  /** 瀵煎叆璁惧 */
 function handleImport() {
   importModalApi.open();
 }
 
-/** 鎸夎澶囩被鍨嬬瓫閫� */
-function handleTypeNodeClick(
-  row: MesDvMachineryTypeApi.MachineryType | undefined,
-) {
-  selectedMachineryTypeId.value = row?.id;
-  handleRefresh();
+  /** 鎸夎澶囩被鍨嬬瓫閫� */
+  function handleTypeNodeClick(
+    row: MesDvMachineryTypeApi.MachineryType | undefined
+  ) {
+    selectedMachineryTypeId.value = row?.id;
+    handleRefresh();
 }
 
 const [Grid, gridApi] = useVbenVxeGrid({
   formOptions: {
     schema: useGridFormSchema(),
-  },
-  gridOptions: {
-    columns: useGridColumns(),
-    height: 'auto',
-    keepSource: true,
-    proxyConfig: {
-      ajax: {
+    },
+    gridOptions: {
+      columns: useGridColumns(),
+      height: "auto",
+      keepSource: true,
+      proxyConfig: {
+        ajax: {
         query: async ({ page }, formValues) =>
           await getMachineryPage({
             pageNo: page.currentPage,
@@ -213,13 +226,13 @@
             ...formValues,
             machineryTypeId: selectedMachineryTypeId.value,
           }),
+        },
       },
-    },
-    rowConfig: {
-      keyField: 'id',
-      isHover: true,
-    },
-    toolbarConfig: {
+      rowConfig: {
+        keyField: "id",
+        isHover: true,
+      },
+      toolbarConfig: {
       refresh: true,
       search: true,
     },
@@ -233,7 +246,8 @@
 </script>
 
 <template>
-  <Page auto-content-height><FormModal @success="handleRefresh" />
+  <Page auto-content-height>
+    <FormModal @success="handleRefresh" />
     <ImportModal @success="handleRefresh" />
     <div class="flex h-full w-full">
       <div class="mr-4 h-full w-1/6">
@@ -242,8 +256,7 @@
       <div class="w-5/6">
         <Grid table-title="璁惧鍙拌处鍒楄〃">
           <template #toolbar-tools>
-            <TableAction
-              :actions="[
+            <TableAction :actions="[
                 {
                   label: $t('ui.actionTitle.create', ['璁惧']),
                   type: 'primary',
@@ -286,19 +299,18 @@
                   icon: 'ant-design:qrcode-outlined',
                   auth: ['mes:dv-machinery:query'],
                   disabled: checkedIds.length === 0,
-                  onClick: () => handlePrintQrcode(checkedRows.value),
+                  onClick: handlePrintCheckedQrcode,
                 },
-              ]"
-            />
+              ]" />
           </template>
           <template #code="{ row }">
-            <Button type="link" @click="handleDetail(row)">
+            <Button type="link"
+                    @click="handleDetail(row)">
               {{ row.code }}
             </Button>
           </template>
           <template #actions="{ row }">
-            <TableAction
-              :actions="[
+            <TableAction :actions="[
                 {
                   label: $t('common.edit'),
                   type: 'link',
@@ -331,8 +343,7 @@
                   auth: ['mes:dv-machinery:query'],
                   onClick: handleDetail.bind(null, row),
                 },
-              ]"
-            />
+              ]" />
           </template>
         </Grid>
       </div>
diff --git a/src/views/wls/productsales/modules/qrcode-modal.vue b/src/views/wls/productsales/modules/qrcode-modal.vue
index a7203c2..a9059a0 100644
--- a/src/views/wls/productsales/modules/qrcode-modal.vue
+++ b/src/views/wls/productsales/modules/qrcode-modal.vue
@@ -32,15 +32,21 @@
     message.error('鏃犳硶鎵撳紑鎵撳嵃绐楀彛锛岃妫�鏌ユ祻瑙堝櫒璁剧疆');
     return;
   }
-  win.document.write(`<!DOCTYPE html><html><head><meta charset="UTF-8"><title>鍑哄簱鍗曟潯鐮�</title>
-<style>*{margin:0;padding:0}body{font-family:Arial,sans-serif;padding:20px;text-align:center}
-img{width:240px;height:240px}.code{font-size:16px;margin-top:12px;font-weight:bold}</style></head>
-<body><img src="${base64}" alt="浜岀淮鐮�"/><div class="code">${row.value.code}</div></body></html>`);
+  win.document.write(`<!DOCTYPE html><html><head><meta charset="UTF-8"><title>閿�鍞嚭搴撲簩缁寸爜鏍囩</title>
+<style>
+@page{size:40mm 40mm;margin:0}
+*{box-sizing:border-box;margin:0;padding:0}
+html,body{width:40mm;height:40mm;overflow:hidden}
+body{display:flex;flex-direction:column;align-items:center;justify-content:center;font-family:Arial,sans-serif;padding:1.5mm;text-align:center}
+img{display:block;width:28mm;height:28mm}.code{max-width:37mm;margin-top:1.5mm;overflow:hidden;font-size:10pt;font-weight:700;line-height:1.2;white-space:nowrap}
+</style></head><body><img src="${base64}" alt="浜岀淮鐮�"/><div class="code">${row.value.code}</div></body></html>`);
   win.document.close();
   win.addEventListener('load', () => {
-    setTimeout(() => win.print(), 400);
-  });
-}
+    setTimeout(() => {
+      win.focus();
+      win.print();
+    }, 300);
+  });}
 
 defineExpose({ open });
 </script>
@@ -60,7 +66,10 @@
       </div>
       <div class="text-base font-medium">{{ row?.code }}</div>
       <div class="text-xs text-gray-400">鎵爜鍙畾浣嶈鍑哄簱鍗曞苟鍦ㄧЩ鍔ㄧ纭鍑哄簱</div>
-      <Button type="primary" @click="handlePrint">鎵撳嵃</Button>
+      <div class="text-center text-xs text-gray-400">
+        璇烽�夋嫨 40脳40 mm 鏍囩绾搞�佺缉鏀� 100%銆佹棤杈硅窛
+      </div>
+      <Button type="primary" @click="handlePrint">鎵撳嵃浜岀淮鐮佹爣绛�</Button>
     </div>
   </Modal>
 </template>

--
Gitblit v1.9.3