办学质量监测教学评价系统
shenrongliang
2025-06-13 11d86cc6c26bb4f709e407acadf4805c2024e79f
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
import type { VbenFormProps } from '#/adapter/form';
 
import { $t } from '@vben/locales';
import { cloneDeep, formatDate } from '@vben/utils';
 
import { message } from 'ant-design-vue';
import { isFunction } from 'lodash-es';
 
import { dataURLtoBlob, urlToBase64 } from './base64Conver';
 
/**
 *
 * @deprecated 无法处理区间选择器数据 请使用commonDownloadExcel
 *
 * 下载excel文件
 * @param [func] axios函数
 * @param [fileName] 文件名称 不需要带xlsx后缀
 * @param [requestData] 请求参数
 * @param [withRandomName] 是否带随机文件名
 *
 * @return void
 */
export async function downloadExcel(
  func: (data?: any) => Promise<Blob>,
  fileName: string,
  requestData: any = {},
  withRandomName = true,
) {
  const hideLoading = message.loading($t('pages.common.downloadLoading'), 0);
  try {
    const data = await func(requestData);
    downloadExcelFile(data, fileName, withRandomName);
  } catch (error) {
    console.error(error);
  } finally {
    hideLoading();
  }
}
 
/**
 * 源码同packages\@core\ui-kit\form-ui\src\components\form-actions.vue
 * @param values 表单值
 * @param fieldMappingTime 区间选择器 字段映射
 * @returns 格式化后的值
 */
function handleRangeTimeValue(
  values: Record<string, any>,
  fieldMappingTime: VbenFormProps['fieldMappingTime'],
) {
  // 需要深拷贝 可能是readonly的
  values = cloneDeep(values);
  if (!fieldMappingTime || !Array.isArray(fieldMappingTime)) {
    return values;
  }
 
  fieldMappingTime.forEach(
    ([field, [startTimeKey, endTimeKey], format = 'YYYY-MM-DD']) => {
      if (startTimeKey && endTimeKey && values[field] === null) {
        Reflect.deleteProperty(values, startTimeKey);
        Reflect.deleteProperty(values, endTimeKey);
        // delete values[startTimeKey];
        // delete values[endTimeKey];
      }
 
      if (!values[field]) {
        Reflect.deleteProperty(values, field);
        // delete values[field];
        return;
      }
 
      const [startTime, endTime] = values[field];
      if (format === null) {
        values[startTimeKey] = startTime;
        values[endTimeKey] = endTime;
      } else if (isFunction(format)) {
        values[startTimeKey] = format(startTime, startTimeKey);
        values[endTimeKey] = format(endTime, endTimeKey);
      } else {
        const [startTimeFormat, endTimeFormat] = Array.isArray(format)
          ? format
          : [format, format];
 
        values[startTimeKey] = startTime
          ? formatDate(startTime, startTimeFormat)
          : undefined;
        values[endTimeKey] = endTime
          ? formatDate(endTime, endTimeFormat)
          : undefined;
      }
      // delete values[field];
      Reflect.deleteProperty(values, field);
    },
  );
  return values;
}
 
export interface DownloadExcelOptions {
  // 是否随机文件名(带时间戳)
  withRandomName?: boolean;
  // 区间选择器 字段映射
  fieldMappingTime?: VbenFormProps['fieldMappingTime'];
}
 
/**
 * 通用下载excel方法
 * @param api 后端下载接口
 * @param fileName 文件名 不带拓展名
 * @param requestData 请求参数
 * @param options 下载选项
 */
export async function commonDownloadExcel(
  api: (data?: any) => Promise<Blob>,
  fileName: string,
  requestData: any = {},
  options: DownloadExcelOptions = {},
) {
  const hideLoading = message.loading($t('pages.common.downloadLoading'), 0);
  try {
    const { withRandomName = true, fieldMappingTime } = options;
    // 需要处理时间字段映射
    const data = await api(handleRangeTimeValue(requestData, fieldMappingTime));
    downloadExcelFile(data, fileName, withRandomName);
  } catch (error) {
    console.error(error);
  } finally {
    hideLoading();
  }
}
 
export function downloadExcelFile(
  data: BlobPart,
  filename: string,
  withRandomName = true,
) {
  let realFileName = filename;
  if (withRandomName) {
    realFileName = `${filename}-${Date.now()}.xlsx`;
  }
  downloadByData(data, realFileName);
}
 
/**
 * Download online pictures
 * @param url
 * @param filename
 * @param mime
 * @param bom
 */
export function downloadByOnlineUrl(
  url: string,
  filename: string,
  mime?: string,
  bom?: BlobPart,
) {
  urlToBase64(url).then((base64) => {
    downloadByBase64(base64, filename, mime, bom);
  });
}
 
/**
 * Download pictures based on base64
 * @param buf
 * @param filename
 * @param mime
 * @param bom
 */
export function downloadByBase64(
  buf: string,
  filename: string,
  mime?: string,
  bom?: BlobPart,
) {
  const base64Buf = dataURLtoBlob(buf);
  downloadByData(base64Buf, filename, mime, bom);
}
 
/**
 * Download according to the background interface file stream
 * @param {*} data
 * @param {*} filename
 * @param {*} mime
 * @param {*} bom
 */
export function downloadByData(
  data: BlobPart,
  filename: string,
  mime?: string,
  bom?: BlobPart,
) {
  const blobData = bom === undefined ? [data] : [bom, data];
  const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });
 
  const blobURL = window.URL.createObjectURL(blob);
  const tempLink = document.createElement('a');
  tempLink.style.display = 'none';
  tempLink.href = blobURL;
  tempLink.setAttribute('download', filename);
  if (tempLink.download === undefined) {
    tempLink.setAttribute('target', '_blank');
  }
  document.body.append(tempLink);
  tempLink.click();
  tempLink.remove();
  window.URL.revokeObjectURL(blobURL);
}
 
export function openWindow(
  url: string,
  opt?: {
    noopener?: boolean;
    noreferrer?: boolean;
    target?: '_blank' | '_self' | string;
  },
) {
  const { noopener = true, noreferrer = true, target = '__blank' } = opt || {};
  const feature: string[] = [];
 
  noopener && feature.push('noopener=yes');
  noreferrer && feature.push('noreferrer=yes');
 
  window.open(url, target, feature.join(','));
}
 
/**
 * Download file according to file address
 * @param {*} sUrl
 */
export function downloadByUrl({
  fileName,
  target = '_blank',
  url,
}: {
  fileName?: string;
  target?: '_blank' | '_self';
  url: string;
}): boolean {
  const isChrome = window.navigator.userAgent.toLowerCase().includes('chrome');
  const isSafari = window.navigator.userAgent.toLowerCase().includes('safari');
 
  if (/iP/.test(window.navigator.userAgent)) {
    console.error('Your browser does not support download!');
    return false;
  }
  if (isChrome || isSafari) {
    const link = document.createElement('a');
    link.href = url;
    link.target = target;
 
    if (link.download !== undefined) {
      link.download =
        // eslint-disable-next-line unicorn/prefer-string-slice
        fileName || url.substring(url.lastIndexOf('/') + 1, url.length);
    }
 
    if (document.createEvent) {
      const e = document.createEvent('MouseEvents');
      e.initEvent('click', true, true);
      link.dispatchEvent(e);
      return true;
    }
  }
  if (!url.includes('?')) {
    url += '?download';
  }
 
  openWindow(url, { target });
  return true;
}