ny
昨天 282fbc6488f4e8ceb5fda759f963ee88fbf7b999
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
<script lang="ts" setup>
import { computed, nextTick, onMounted, onUnmounted, reactive, ref, toRefs, unref, watch } from 'vue';
import { useRoute } from 'vue-router';
 
import { useGlobSetting, useMessage } from '@jnpf/hooks';
import { BasicForm, useForm } from '@jnpf/ui/form';
import { useModal } from '@jnpf/ui/modal';
import { JnpfUniver, JnpfUniverCellEchart, JnpfUniverFloatEchartVM } from '@jnpf/univer';
import { cloneDeep, downloadByUrlReport } from '@jnpf/utils';
 
import { usePreferences } from '@vben/preferences';
 
import { exportFileExcel, getPreviewTemplate } from '#/api/onlineDev/report';
import { ReportPrint } from '#/components/Report';
import { getFloatUrl } from '#/components/Report/src/helper';
import { useReport } from '#/components/Report/src/hooks/useReport';
import { $t } from '#/locales';
 
defineOptions({ name: 'DynamicReport' });
 
const { createConfirm } = useMessage();
 
interface State {
  id: string;
  reportData: any;
  pageLoading: boolean;
  jnpfUniverAPI: any;
  allowExport: number;
  allowPrint: number;
  sheetId: string;
  jnpfUniverKey: number;
  queryList: any[];
  jnpfUniverStore: any;
  echartsImageCache: any;
  watermarkCache: any;
  isFromApp: boolean;
}
 
const jnpfUniverRef = ref();
const jnpfUniverFloatEchartVMRef = ref();
const jnpfUniverCellEchartRef = ref();
const state = reactive<State>({
  id: '',
  reportData: {},
  pageLoading: false,
  jnpfUniverAPI: null,
  allowExport: 0,
  allowPrint: 0,
  sheetId: '',
  jnpfUniverKey: 0,
  queryList: [],
  jnpfUniverStore: null,
  echartsImageCache: {},
  watermarkCache: {},
  isFromApp: false,
});
const { pageLoading, allowExport, allowPrint, jnpfUniverKey } = toRefs(state);
const { isDark } = usePreferences();
const [registerReportPrint, { openModal: openPrintModal }] = useModal();
const [registerSearchForm, { updateSchema, submit: searchFormSubmit, getFieldsValue }] = useForm({
  baseColProps: { span: 6 },
  showActionButtonGroup: true,
  showAdvancedButton: true,
  compact: true,
});
const formApi = { updateSchema, getFieldsValue };
const { getRealEchart, getSearchSchema, searchSchemas, clearSearchSchema } = useReport(formApi);
const globSetting = useGlobSetting();
const getHasBtn = computed(() => !state.isFromApp && (state.allowExport || state.allowPrint));
 
watch(
  () => isDark.value,
  (val) => {
    state.jnpfUniverAPI?.toggleDarkMode(val);
  },
);
 
// 初始化
function init() {
  const route = useRoute();
  state.isFromApp = route?.query?.from === 'app';
  state.id = state.isFromApp ? (route?.query?.id as string) : (route?.meta?.relationId as string);
  if (!state.id) return;
  // state.pageLoading = true;
  state.jnpfUniverStore = null;
  state.echartsImageCache = {};
  state.watermarkCache = {};
  initData();
}
function initData(data = {}) {
  // state.pageLoading = true;
  getPreviewTemplate(state.id, data).then((res) => {
    state.reportData = res.data;
    state.queryList = res.data.queryList ? JSON.parse(res.data.queryList) : [];
 
    const snapshot = res.data.snapshot ? JSON.parse(res.data.snapshot) : null;
    const cells = res.data.cells ? JSON.parse(res.data.cells) : {};
    const chartData = res.data.chartData ? JSON.parse(res.data.chartData) : [];
 
    const floatEcharts = getRealEchart(cells.floatEcharts ?? null, chartData);
 
    const cellEcharts = getRealEchart(cells.cellEcharts ?? null, chartData);
    const cellEchartsArray = cellEchartsObjectToArray(cellEcharts ?? {});
 
    let floatImages = cells.floatImages ?? {};
    const item = getFloatUrl(snapshot.resources, globSetting.reportApiURL, floatImages);
    snapshot.resources = item.list;
    floatImages = item.floatImages ?? {};
 
    state.watermarkCache = {
      show: res.data?.allowWatermark === 1,
      config: { ...res.data?.watermarkConfig },
    };
 
    state.allowExport = res.data.allowExport || 0;
    state.allowPrint = res.data.allowPrint || 0;
    const watermarkConfig = res.data?.watermarkConfig ? JSON.parse(res.data.watermarkConfig) : {};
    if (watermarkConfig?.showTime) {
      watermarkConfig.content = `${watermarkConfig.content} ${getDateTimeTextByType(watermarkConfig.timeFormat)}`;
    }
    state.watermarkCache = {
      show: res.data?.allowWatermark === 1,
      config: watermarkConfig,
    };
 
    // clearSearchSchema();
    nextTick(() => {
      getSearchSchema(state.queryList, state.sheetId || '');
    });
    state.jnpfUniverKey = Date.now();
 
    nextTick(() => {
      const updateSheets = cloneDeep(snapshot?.sheets ?? {});
 
      // 单元格图表转单元格图片
      cellEchartsArray.forEach((cellEchartOption) => {
        const { option: echartOption, width: echartWidth, height: echartHeight, sheetKey, rowKey, colKey, drawingId } = cellEchartOption;
        const echartImg = unref(jnpfUniverCellEchartRef).render(echartOption, echartWidth, echartHeight);
        try {
          const targetDrawing = updateSheets?.[sheetKey]?.cellData?.[rowKey]?.[colKey]?.p?.drawings?.[drawingId];
          updateSheets[sheetKey].cellData[rowKey][colKey].p.drawings[drawingId] = {
            ...targetDrawing,
            source: echartImg,
          };
        } catch {
          // console.log('渲染单元格图表失败');
        }
      });
 
      // 将单元格图表的图片更新到快照中
      snapshot.sheets = cloneDeep(updateSheets);
      handleCreate(snapshot, floatEcharts, floatImages);
    });
  });
}
// 创建报表实例
function handleCreate(snapshot, floatEcharts, floatImages) {
  const res = unref(jnpfUniverRef)?.handleCreateDesignUnit({
    mode: 'preview',
    snapshot,
    floatEcharts,
    floatImages,
    watermark: state.watermarkCache,
    uiHeader: false,
    uiContextMenu: false,
    readonly: true,
    defaultActiveSheetId: state.sheetId || '',
    loading: true,
    darkMode: isDark.value,
  });
  state.jnpfUniverAPI = res ? res?.jnpfUniverAPI : null;
  // 创建悬浮图表的图片
  createFloatEchartsImage(floatEcharts);
 
  onReportCommandExecuted();
  state.jnpfUniverAPI?.getHooks()?.onSteady(() => {
    // state.pageLoading = false;
  });
}
function onReportCommandExecuted() {
  state.jnpfUniverAPI?.onCommandExecuted((command: any) => {
    const { id: commandId } = command ?? {};
    // 切换sheet
    if (commandId === 'sheet.operation.set-worksheet-active') {
      if (state.sheetId != command.params.subUnitId && state.queryList?.length) {
        nextTick(() => {
          clearSearchSchema();
 
          initData({ sheetId: command.params.subUnitId });
        });
      }
      state.sheetId = command.params.subUnitId;
      getSearchSchema(state.queryList, state.sheetId);
    }
  });
}
// 获取单元格图表的数组
function cellEchartsObjectToArray(cellEcharts: any) {
  const res: any[] = [];
 
  for (const key in cellEcharts) {
    const { sheet, row, col, drawingId, height, width, option } = cellEcharts[key];
 
    res.push({
      sheetKey: sheet,
      rowKey: row,
      colKey: col,
      drawingId,
      width,
      height,
      option,
    });
  }
 
  return res;
}
// 创建悬浮图表的图片信息
function createFloatEchartsImage(echarts: any) {
  state.jnpfUniverStore = unref(jnpfUniverRef)?.getDynamicStore();
  if (!state.jnpfUniverStore) {
    return;
  }
 
  const caches = { ...unref(state.jnpfUniverStore.floatEchartToUniverImgDataCaches) };
 
  for (const sheetKey in echarts) {
    const target = echarts[sheetKey];
 
    const { domId, option, width, height } = target;
 
    const res = unref(jnpfUniverFloatEchartVMRef).render(domId, option, width, height);
    caches[res.domId] = res?.source ?? {};
 
    Object.assign(state.echartsImageCache, caches); // 直接修改原对象,保持响应性
  }
}
// 获取水印时间文本
function getDateTimeTextByType(type: string) {
  let currentTime = new Date(Date.now() + 8 * 3600 * 1000).toJSON().slice(0, 19).replace('T', ' ');
 
  switch (type) {
    case 'yyyy': {
      currentTime = currentTime.slice(0, 4);
      break;
    }
    case 'yyyy-MM': {
      currentTime = currentTime.slice(0, 7);
      break;
    }
    case 'yyyy-MM-dd': {
      currentTime = currentTime.slice(0, 10);
      break;
    }
    case 'yyyy-MM-dd HH:mm': {
      currentTime = currentTime.slice(0, 16);
      break;
    }
    default: {
      break;
    }
  }
  return currentTime;
}
// 销毁示例
function handleDisposeUnit() {
  unref(jnpfUniverRef)?.handleDisposeUnit();
}
function handleSearchSubmit(data) {
  initData({ sheetId: state.sheetId, ...data });
}
// 打印
function handlePrint() {
  state.jnpfUniverStore?.setFloatEchartToUniverImgDataCaches(state.echartsImageCache);
  const { snapshot } = unref(jnpfUniverRef)?.getPreviewWorkbookData() || {};
 
  const sheetId = state.jnpfUniverAPI.getActiveWorkbook()?.getActiveSheet()?.getSheetId();
  const sheetCellData = snapshot.sheets[sheetId].cellData ?? {};
 
  let sheetCellImageNumber = 0;
  for (const rowKey in sheetCellData) {
    const row = sheetCellData[rowKey];
 
    for (const colKey in row) {
      const cellData = row[colKey] ?? {};
      const p = cellData?.p;
 
      if (p && Object.keys(p).length > 0 && p.constructor === Object) {
        const orders = p?.drawingsOrder ?? [];
 
        orders.forEach((orderKey: string) => {
          if (p.drawings?.[orderKey]?.imageSourceType === 'BASE64') {
            sheetCellImageNumber++;
          }
        });
      }
    }
  }
 
  if (sheetCellImageNumber > 100) {
    createConfirm({
      iconType: 'warning',
      title: $t('common.tipTitle'),
      content: '数据过大,请导出后使用其他工具打印',
      okText: $t('common.exportText'),
      onOk: () => {
        handleDownload();
      },
    });
    return;
  }
 
  openPrintModal(true, { id: state.reportData.versionId, fullName: state.reportData.fullName, sheetId, snapshot, watermark: state.watermarkCache });
}
// 导出
function handleDownload(sheetId?: string) {
  state.jnpfUniverStore?.setFloatEchartToUniverImgDataCaches(state.echartsImageCache);
  const { snapshot } = unref(jnpfUniverRef)?.getPreviewWorkbookData() || {};
 
  const targetSheets = sheetId || snapshot.sheetOrder.join(','); // 多个工作本导出sheetId以逗号连接
  const data = unref(searchSchemas).length ? getFieldsValue() : {};
  const query = { ...data, sheetId: targetSheets, fullName: state.reportData.fullName, snapshot: snapshot ? JSON.stringify(snapshot) : null };
  exportFileExcel(state.reportData.versionId, query).then((res) => {
    downloadByUrlReport({ url: res.data.url });
  });
}
 
onMounted(() => {
  init();
});
 
onUnmounted(() => {
  handleDisposeUnit();
});
</script>
 
<template>
  <div class="jnpf-content-wrapper jnpf-dynamicReport-wrapper" v-loading="pageLoading">
    <div class="tool-wrap" v-if="getHasBtn">
      <a-tooltip title="打印" v-if="allowPrint">
        <a-button type="text" :disabled="pageLoading" class="action-bar-btn" @click="handlePrint">
          <i class="icon-ym icon-ym-printExample"></i>
        </a-button>
      </a-tooltip>
      <a-tooltip title="导出" v-if="allowExport">
        <a-button type="text" :disabled="pageLoading" class="action-bar-btn" @click="handleDownload()">
          <i class="icon-ym icon-ym-btn-export1"></i>
        </a-button>
      </a-tooltip>
    </div>
    <div class="query-wrap" v-if="searchSchemas?.length">
      <BasicForm @register="registerSearchForm" :schemas="searchSchemas" @submit="handleSearchSubmit" @reset="searchFormSubmit" class="search-form" />
    </div>
    <div class="content-main">
      <JnpfUniver ref="jnpfUniverRef" :key="jnpfUniverKey" />
      <div id="floatEchartVMContent" class="cell-echarts-vm-content">
        <JnpfUniverFloatEchartVM ref="jnpfUniverFloatEchartVMRef" univer-create-mode="preview" />
      </div>
      <div id="cellEchartsContent" class="cell-echarts-content">
        <JnpfUniverCellEchart ref="jnpfUniverCellEchartRef" univer-create-mode="preview" />
      </div>
    </div>
    <ReportPrint @register="registerReportPrint" />
  </div>
</template>
 
<style lang="scss">
.jnpf-dynamicReport-wrapper {
  display: flex;
  flex-direction: column;
  background-color: var(--component-background);
 
  .tool-wrap {
    height: 53px;
    padding: 10px;
    border-bottom: 1px solid var(--border-color-base1);
  }
 
  .query-wrap {
    padding: 10px 10px 0;
    border-bottom: 1px solid #f0f0f0;
  }
 
  .content-main {
    position: relative;
    flex: 1;
    width: 100%;
    height: 100%;
 
    .cell-echarts-content {
      position: absolute;
      inset: 0;
      z-index: -1;
    }
 
    .cell-echarts-vm-content {
      position: absolute;
      inset: 0;
      z-index: -2;
    }
  }
}
</style>