刘光辉
3 小时以前 cf11e63b659afcc9792ab3e395f1b45d844431a8
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
<script lang="ts" setup>
import type { ListPrintColumn, ListPrintPage } from '../helpers/listPrint';
 
import { computed, reactive, ref } from 'vue';
 
import { useMessage } from '@jnpf/hooks';
import { BasicModal, useModalInner } from '@jnpf/ui/modal';
 
import { onlineUtils } from '#/utils/jnpf';
 
import { buildListPrintDocument, getListPrintTotalPages, validateListPrintPageRange } from '../helpers/listPrint';
 
interface FetchPageResult {
  auditRows?: Record<string, any>[];
  list: Record<string, any>[];
  total: number;
}
 
interface ListPrintModalOptions {
  columns: ListPrintColumn[];
  defaultPageSize?: number;
  direction?: 'landscape' | 'portrait';
  fetchPage: (currentPage: number, pageSize: number) => Promise<FetchPageResult>;
  onPrint?: (rows: Record<string, any>[], title: string) => void;
  paperType?: 'A3' | 'A4';
  title?: string;
}
 
interface State {
  columns: ListPrintColumn[];
  direction: 'landscape' | 'portrait';
  endPage: number;
  fetchPage: ListPrintModalOptions['fetchPage'] | null;
  loading: boolean;
  onPrint: ListPrintModalOptions['onPrint'];
  pageSize: number;
  paperType: 'A3' | 'A4';
  startPage: number;
  title: string;
  total: number;
}
 
const { createMessage } = useMessage();
const [registerModal, { changeOkLoading, closeModal }] = useModalInner(init);
const state = reactive<State>({
  columns: [],
  direction: 'portrait',
  endPage: 1,
  fetchPage: null,
  loading: false,
  onPrint: undefined,
  pageSize: 20,
  paperType: 'A4',
  startPage: 1,
  title: '列表报表',
  total: 0,
});
const requestId = ref(0);
const pageSizeOptions = [10, 20, 30, 50, 100].map((value) => ({ label: `${value} 条/页`, value }));
const totalPages = computed(() => getListPrintTotalPages(state.total, state.pageSize));
 
async function init(options: ListPrintModalOptions) {
  const currentRequestId = ++requestId.value;
  state.columns = options.columns || [];
  state.direction = options.direction || 'portrait';
  state.fetchPage = options.fetchPage;
  state.onPrint = options.onPrint;
  state.pageSize = options.defaultPageSize || 20;
  state.paperType = options.paperType || 'A4';
  state.startPage = 1;
  state.endPage = 1;
  state.title = options.title || '列表报表';
  state.total = 0;
  state.loading = true;
  changeOkLoading(true);
 
  try {
    const result = await state.fetchPage(1, state.pageSize);
    if (currentRequestId !== requestId.value) return;
    state.total = Number(result.total) || 0;
    state.endPage = getListPrintTotalPages(state.total, state.pageSize);
  } catch {
    if (currentRequestId === requestId.value) createMessage.error('读取打印数据失败');
  } finally {
    if (currentRequestId === requestId.value) {
      state.loading = false;
      changeOkLoading(false);
    }
  }
}
 
function handlePageSizeChange() {
  state.startPage = 1;
  state.endPage = totalPages.value;
}
 
async function handleSubmit() {
  if (!state.fetchPage) return;
  if (!state.columns.length) return createMessage.warning('当前列表没有可打印字段');
  if (!state.total) return createMessage.warning('当前查询没有可打印数据');
 
  const rangeError = validateListPrintPageRange(state.startPage, state.endPage, totalPages.value);
  if (rangeError) return createMessage.warning(rangeError);
 
  state.loading = true;
  changeOkLoading(true);
  let awaitingPrintResult = false;
  try {
    const pages: ListPrintPage[] = [];
    const auditRows: Record<string, any>[] = [];
    for (let pageNumber = state.startPage; pageNumber <= state.endPage; pageNumber++) {
      const result = await state.fetchPage(pageNumber, state.pageSize);
      pages.push({ pageNumber, rows: result.list || [] });
      auditRows.push(...(result.auditRows || result.list || []));
    }
 
    const html = buildListPrintDocument({
      columns: state.columns,
      direction: state.direction,
      pageSize: state.pageSize,
      pages,
      paperType: state.paperType,
      title: state.title,
      total: state.total,
    });
    const result = await onlineUtils.hiprint({
      clientOptions: { printer: '', title: state.title },
      html,
      onError: () => {
        state.loading = false;
        changeOkLoading(false);
      },
      onPrint: () => {
        try {
          state.onPrint?.(auditRows, state.title);
        } catch (error) {
          console.error('[ListPrintModal] 打印审计回调执行失败:', error);
        }
        state.loading = false;
        changeOkLoading(false);
        closeModal();
      },
    });
    awaitingPrintResult = Boolean(result);
  } catch (error) {
    console.error('[ListPrintModal] 打印失败:', error);
    createMessage.error('生成打印报表失败');
  } finally {
    if (!awaitingPrintResult) {
      state.loading = false;
      changeOkLoading(false);
    }
  }
}
</script>
 
<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="打印设置"
    ok-text="打印"
    :width="560"
    :confirm-loading="state.loading"
    destroy-on-close
    @ok="handleSubmit">
    <a-form :model="state" :colon="false" :label-col="{ style: { width: '96px' } }">
      <a-form-item label="报表名称">
        <a-input v-model:value="state.title" :maxlength="100" />
      </a-form-item>
      <a-form-item label="每页条数">
        <a-select v-model:value="state.pageSize" :options="pageSizeOptions" @change="handlePageSizeChange" />
      </a-form-item>
      <a-form-item label="打印页码">
        <div class="page-range">
          <a-input-number v-model:value="state.startPage" :min="1" :max="totalPages" :precision="0" />
          <span>至</span>
          <a-input-number v-model:value="state.endPage" :min="1" :max="totalPages" :precision="0" />
          <span class="page-total">共 {{ totalPages }} 页,{{ state.total }} 条</span>
        </div>
      </a-form-item>
      <a-form-item label="纸张类型">
        <a-radio-group v-model:value="state.paperType" button-style="solid">
          <a-radio-button value="A4">A4</a-radio-button>
          <a-radio-button value="A3">A3</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="纸张方向">
        <a-radio-group v-model:value="state.direction" button-style="solid">
          <a-radio-button value="portrait">纵向</a-radio-button>
          <a-radio-button value="landscape">横向</a-radio-button>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </BasicModal>
</template>
 
<style lang="scss" scoped>
.page-range {
  display: flex;
  align-items: center;
  gap: 10px;
}
 
.page-total {
  color: var(--text-color-secondary);
  white-space: nowrap;
}
</style>