useCheckin.js
19.2 KB
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showLoadingToast } from 'vant'
import { qiniuTokenAPI, qiniuUploadAPI, saveFileAPI } from '@/api/common'
import { addUploadTaskAPI, getUploadTaskInfoAPI, editUploadTaskInfoAPI } from "@/api/checkin"
import { qiniuFileHash } from '@/utils/qiniuFileHash';
import { useAuth } from '@/contexts/auth'
/**
* 打卡功能的composable
* @returns {Object} 打卡相关的状态和方法
*/
export function useCheckin() {
const route = useRoute()
const router = useRouter()
const { currentUser } = useAuth()
// 基础状态
const uploading = ref(false)
const loading = ref(false)
const message = ref('')
const fileList = ref([])
const activeType = ref('') // 当前选中的打卡类型
const subTaskId = ref('') // 当前选中的任务ID
const selectedTaskText = ref('') // 选中的任务文本
const selectedTaskValue = ref([]) // 选中的任务值(Picker使用)
const isMakeup = ref(false) // 是否为补录作业
const maxCount = ref(5)
const maxFileSizeMbMap = ref({
image: 20,
video: 20,
audio: 20
})
const maxFileSizeMb = computed(() => {
const type = String(activeType.value || '')
const raw = maxFileSizeMbMap.value?.[type]
const size = Number(raw)
if (Number.isFinite(size) && size > 0) return size
return 20
})
/**
* 设置最大文件大小映射
* @param {Object} map - 包含 image, video, audio 键的对象
*/
const setMaxFileSizeMbMap = (map = {}) => {
if (!map || typeof map !== 'object') return
const next = { ...(maxFileSizeMbMap.value || {}) }
for (const key of ['image', 'video', 'audio']) {
const raw = map[key]
const size = Number(raw)
if (Number.isFinite(size) && size > 0) {
next[key] = size
}
}
maxFileSizeMbMap.value = next
}
// 打卡类型
const checkinType = computed(() => route.query.task_type)
// 用于记忆不同类型的文件列表
const fileListMemory = ref({
text: [],
image: [],
video: [],
audio: []
})
/**
* 是否可以提交
*/
const canSubmit = computed(() => {
// 如果是计数打卡,交由组件内部校验
if (checkinType.value === 'count') {
return true
}
if (activeType.value === 'text') {
// 文字打卡:必须填写内容且长度不少于10个字符
return message.value.trim() !== '' && message.value.trim().length >= 10
} else {
// 图片、视频、音频打卡:必须有文件,内容可选
return fileList.value.length > 0
}
})
/**
* 获取文件哈希(与七牛云ETag一致)
* @param {File} file 文件对象
* @returns {Promise<string>} 哈希字符串
* 注释:使用 qiniuFileHash 进行计算,替代浏览器MD5方案。
*/
const getFileMD5 = async (file) => {
return await qiniuFileHash(file)
}
/**
* 上传文件到七牛云
* @param {File} file - 文件对象
* @param {string} token - 七牛云token
* @param {string} fileName - 文件名
* @returns {Promise<Object>} 上传结果
*/
const uploadToQiniu = async (file, token, fileName) => {
const formData = new FormData()
formData.append('file', file)
formData.append('token', token)
formData.append('key', fileName)
const config = {
headers: { 'Content-Type': 'multipart/form-data' }
}
// 根据协议选择上传地址
const qiniuUploadUrl = window.location.protocol === 'https:'
? 'https://up.qbox.me'
: 'http://upload.qiniu.com'
return await qiniuUploadAPI(qiniuUploadUrl, formData, config)
}
/**
* 处理单个文件上传
* @param {Object} file - 文件对象
* @returns {Promise<Object|null>} 上传结果
*/
const handleUpload = async (file) => {
loading.value = true
try {
// 获取MD5值
const md5 = await getFileMD5(file.file)
// 获取七牛token
const tokenResult = await qiniuTokenAPI({
name: file.file.name,
hash: md5
})
// 文件已存在,直接返回
if (tokenResult.data) {
return tokenResult.data
}
// 新文件上传
if (tokenResult.token) {
const suffix = /.[^.]+$/.exec(file.file.name) || ''
let fileName = ''
if (activeType.value === 'image') {
fileName = `mlaj/upload/checkin/${currentUser.value.mobile}/img/${md5}${suffix}`
} else {
fileName = `mlaj/upload/checkin/${currentUser.value.mobile}/file/${md5}${suffix}`
}
const uploadResult = await uploadToQiniu(
file.file,
tokenResult.token,
fileName
)
if (uploadResult.filekey) {
// 保存文件信息
const saveData = {
name: file.file.name,
filekey: uploadResult.filekey,
hash: md5
}
// 图片类型需要保存尺寸信息
if (activeType.value === 'image' && uploadResult.image_info) {
saveData.height = uploadResult.image_info.height
saveData.width = uploadResult.image_info.width
}
const { data } = await saveFileAPI(saveData)
return data
}
}
return null
} catch (error) {
console.error('Upload error:', error)
return null
} finally {
loading.value = false
}
}
/**
* 文件上传前的校验
* @param {File|File[]} file - 文件或文件数组
* @returns {boolean} 是否通过校验
*/
const beforeRead = (file) => {
let flag = true
const files = Array.isArray(file) ? file : [file]
// 检查文件数量
if (fileList.value.length + files.length > maxCount.value) {
flag = false
showToast(`最大上传数量为${maxCount.value}个`)
return flag
}
// 检查文件类型和大小
for (const item of files) {
const fileType = item.type.toLowerCase()
// 文件大小检查
const file_size_mb = item.size / 1024 / 1024
if (Number.isFinite(file_size_mb) && file_size_mb > maxFileSizeMb.value) {
flag = false
showToast(`最大文件体积为${maxFileSizeMb.value}MB`)
break
}
// 文件类型检查
if (activeType.value === 'image') {
const imageTypes = ['jpg', 'jpeg', 'png']
const validImageTypes = imageTypes.map(type => `image/${type}`)
if (!validImageTypes.some(type => fileType.includes(type.split('/')[1]))) {
flag = false
showToast('请上传指定格式图片')
break
}
} else if (activeType.value === 'video') {
if (!fileType.startsWith('video/')) {
flag = false
showToast('请上传视频文件')
break
}
} else if (activeType.value === 'audio') {
if (!fileType.startsWith('audio/')) {
flag = false
showToast('请上传音频文件')
break
}
}
}
return flag
}
/**
* 文件读取后的处理
* @param {File|File[]} file - 文件或文件数组
*/
const afterRead = async (file) => {
const files = Array.isArray(file) ? file : [file]
for (const item of files) {
item.status = 'uploading'
item.message = '上传中...'
const result = await handleUpload(item)
if (result) {
item.status = 'done'
item.message = '上传成功'
item.url = result.url
item.meta_id = result.meta_id
item.name = result.name || item.file.name
} else {
item.status = 'failed'
item.message = '上传失败'
showToast('上传失败,请重试')
}
}
}
/**
* 删除文件
* @param {Object} file - 要删除的文件对象
*/
const onDelete = (file) => {
const index = fileList.value.findIndex(item => item === file)
if (index > -1) {
fileList.value.splice(index, 1)
}
}
/**
* 删除文件项
* @param {Object} item - 要删除的文件项
*/
const delItem = (item) => {
const index = fileList.value.findIndex(file => file === item)
if (index > -1) {
fileList.value.splice(index, 1)
}
}
/**
* 提交打卡
* @param {Object} extraData - 额外提交数据
*/
const get_new_checkin_id = (data) => {
if (!data) return null
if (typeof data === 'string' || typeof data === 'number') return data
if (typeof data !== 'object') return null
const direct_keys = ['id', 'checkin_id', 'post_id', 'i']
for (const key of direct_keys) {
const value = data?.[key]
if (typeof value === 'string' || typeof value === 'number') return value
}
const visited = new Set()
const deep_find = (obj, max_depth) => {
if (!obj || typeof obj !== 'object') return null
if (visited.has(obj)) return null
visited.add(obj)
for (const [key, value] of Object.entries(obj)) {
if ((typeof value === 'string' || typeof value === 'number') && /(^|_)(id)$/.test(String(key))) {
return value
}
}
if (max_depth <= 0) return null
for (const value of Object.values(obj)) {
if (value && typeof value === 'object') {
const found = deep_find(value, max_depth - 1)
if (found) return found
}
}
return null
}
const found_id = deep_find(data, 2)
if (found_id) return found_id
return null
}
const onSubmit = async (extraData = {}) => {
if (uploading.value) return
// 表单验证
if (checkinType.value !== 'count') {
if (activeType.value === 'text') {
if (message.value.trim().length < 10) {
showToast('打卡内容至少需要10个字符')
return
}
} else {
if (fileList.value.length === 0) {
showToast('请先上传文件')
return
}
}
}
uploading.value = true
showLoadingToast({
message: '提交中...',
forbidClick: true,
})
try {
// 准备提交数据
const submitData = {
note: message.value,
file_type: activeType.value,
meta_id: [],
makeup_time: isMakeup.value ? route.query.date : '',
...extraData
}
// 如果有文件,添加文件ID
if (fileList.value.length > 0) {
submitData.meta_id = fileList.value
.filter(item => item.status === 'done' && item.meta_id)
.map(item => item.meta_id)
}
let result
if (route.query.status === 'edit') {
// 编辑打卡
const editData = {
i: route.query.post_id,
subtask_id: submitData.subtask_id || route.query.subtask_id,
note: submitData.note,
meta_id: submitData.meta_id,
file_type: submitData.file_type,
}
// 如果有计数对象列表,也需要传递
if (submitData.gratitude_form_list) {
editData.gratitude_form_list = submitData.gratitude_form_list
}
if (submitData.gratitude_count) {
editData.gratitude_count = submitData.gratitude_count
}
result = await editUploadTaskInfoAPI(editData)
} else {
// 新增打卡
result = await addUploadTaskAPI(submitData)
}
if (result.code === 1) {
showToast('提交成功')
// 设置刷新标记,用于列表页更新数据
const refreshType = route.query.status === 'edit' ? 'edit' : 'add';
sessionStorage.setItem('checkin_refresh_flag', refreshType);
if (refreshType === 'edit') {
sessionStorage.setItem('checkin_refresh_id', route.query.post_id);
} else if (result.data) {
const new_id = get_new_checkin_id(result.data)
if (new_id) sessionStorage.setItem('checkin_refresh_id', new_id)
}
router.back()
}
} catch (error) {
showToast('提交失败,请重试')
} finally {
uploading.value = false
}
}
/**
* 切换打卡类型
* @param {string} type - 打卡类型
*/
const switchType = (type) => {
if (activeType.value !== type) {
// 保存当前类型的文件列表到记忆中
fileListMemory.value[activeType.value] = [...fileList.value]
// 切换到新类型
activeType.value = type
// 恢复新类型的文件列表
fileList.value = [...fileListMemory.value[type]]
}
}
/**
* 重置表单
*/
const resetForm = () => {
message.value = ''
fileList.value = []
activeType.value = 'text'
uploading.value = false
loading.value = false
// 清空文件列表记忆
fileListMemory.value = {
text: [],
image: [],
video: [],
audio: []
}
}
// 计数打卡相关数据
const gratitudeCount = ref(0)
const gratitudeFormList = ref([])
/**
* 初始化编辑数据
* @param {Array} taskOptions - 任务选项列表
* @param {Object} handlers - 回调处理函数
*/
const initEditData = async (taskOptions = [], handlers = {}) => {
if (route.query.status === 'edit') {
try {
const { code, data } = await getUploadTaskInfoAPI({ i: route.query.post_id })
if (code === 1) {
message.value = data?.note || ''
activeType.value = data?.file_type || 'text'
// 小作业ID
subTaskId.value = data?.subtask_id
// 恢复计数打卡数据
if (data?.gratitude_count) {
gratitudeCount.value = data.gratitude_count
}
// if (data?.gratitude_form_list && Array.isArray(data.gratitude_form_list)) {
// gratitudeFormList.value = data.gratitude_form_list
// }
// 更新选中的任务显示
if (subTaskId.value) {
selectedTaskValue.value = [subTaskId.value]
if (taskOptions && taskOptions.length > 0) {
const option = taskOptions.find(o => o.value === subTaskId.value)
selectedTaskText.value = option ? option.text : ''
// 找到任务选项后的通用回调
if (option && handlers.onTaskFound) {
handlers.onTaskFound(option)
}
// 处理计数打卡的回调
if (route.query.task_type === 'count' && option) {
// 1. 确保目标列表已加载
if (handlers.ensureTargetList) {
await handlers.ensureTargetList(subTaskId.value)
}
// 2. 恢复选中的对象
// if (gratitudeFormList.value.length > 0 && handlers.setTargets) {
// handlers.setTargets(gratitudeFormList.value)
// }
// 3. 恢复次数
if (gratitudeCount.value && handlers.setCount) {
handlers.setCount(gratitudeCount.value)
}
}
}
}
// 如果有文件数据,初始化文件列表 - 使用data.files而不是data.meta
if (data?.files && data.files.length > 0) {
const files = data.files.map(item => {
const fileItem = {
url: item.value,
status: 'done',
message: '已上传',
meta_id: item.meta_id,
name: item.name || ''
}
// 对于图片类型,添加isImage标记确保正确显示
if (activeType.value === 'image') {
fileItem.isImage = true
}
// 为了支持文件名显示,创建一个File对象
if (item.name) {
fileItem.file = new File([], item.name, { type: item.type || '' })
}
return fileItem
})
// 将文件列表保存到当前类型的记忆中
fileList.value = files
fileListMemory.value[activeType.value] = [...files]
}
}
} catch (error) {
console.error('初始化编辑数据失败:', error)
}
}
}
return {
uploading,
loading,
message,
fileList,
activeType,
subTaskId,
selectedTaskText,
selectedTaskValue,
isMakeup,
maxCount,
maxFileSizeMb,
canSubmit,
gratitudeCount,
gratitudeFormList,
// 方法
setMaxFileSizeMbMap,
beforeRead,
afterRead,
onDelete,
delItem,
onSubmit,
switchType,
resetForm,
initEditData
}
}