useCheckin.js 24.5 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 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
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'

/**
 * 打卡核心逻辑封装
 * @module useCheckin
 * @description
 * 该 Hook 封装了打卡页面的核心业务逻辑,包括:
 * 1. 状态管理:上传状态、文件列表、打卡类型、计数器等。
 * 2. 文件处理:文件选择、校验(类型/大小)、MD5计算、七牛云上传。
 * 3. 提交逻辑:表单校验、数据组装、新增/编辑API调用。
 * 4. 数据回显:编辑模式下的数据初始化与恢复。
 *
 * @returns {Object} 包含响应式状态和操作方法的对象
 */
export function useCheckin() {
    const route = useRoute()
    const router = useRouter()
    const { currentUser } = useAuth()

    // ==================== 状态定义 ====================

    /** @type {import('vue').Ref<boolean>} 上传中状态 */
    const uploading = ref(false)
    /** @type {import('vue').Ref<boolean>} 加载中状态 */
    const loading = ref(false)
    /** @type {import('vue').Ref<string>} 打卡文本内容 */
    const message = ref('')
    /** @type {import('vue').Ref<Array>} 文件列表 */
    const fileList = ref([])
    /** @type {import('vue').Ref<string>} 当前选中的打卡类型 (text/image/video/audio) */
    const activeType = ref('')
    /** @type {import('vue').Ref<string>} 当前选中的子任务ID */
    const subTaskId = ref('')
    /** @type {import('vue').Ref<string>} 选中的任务文本显示 */
    const selectedTaskText = ref('')
    /** @type {import('vue').Ref<Array>} 选中的任务值(Picker使用) */
    const selectedTaskValue = ref([])
    /** @type {import('vue').Ref<boolean>} 是否为补录作业 */
    const isMakeup = ref(false)
    /** @type {import('vue').Ref<number>} 最大上传数量 */
    const maxCount = ref(5)

    /**
     * 各类型文件的最大体积限制 (MB)
     * @type {import('vue').Ref<Object>}
     */
    const maxFileSizeMbMap = ref({
        image: 20,
        video: 20,
        audio: 20
    })

    // ==================== 计算属性 ====================

    /**
     * 当前类型文件的最大体积限制
     * @returns {number} 体积限制(MB)
     */
    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
    }

    /**
     * 从路由获取打卡类型
     * @returns {string} 打卡类型
     */
    const checkinType = computed(() => route.query.task_type)

    /**
     * 用于记忆不同类型的文件列表,切换类型时恢复
     * @type {import('vue').Ref<Object>}
     */
    // const fileListMemory = ref({
    //     text: [],
    //     image: [],
    //     video: [],
    //     audio: []
    // })

    /**
     * 是否可以提交
     * @description
     * 校验逻辑:
     * 1. 计数打卡:直接通过,由组件内部校验
     * 2. 文字打卡:必须有内容且长度 >= 10
     * 3. 多媒体打卡:必须有文件上传
     * @returns {boolean}
     */
    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>} 哈希字符串
     * @description 使用 qiniuFileHash 进行计算,替代浏览器MD5方案,确保与七牛云存储一致性。
     */
    const getFileMD5 = async (file) => {
        return await qiniuFileHash(file)
    }

    /**
     * 上传文件到七牛云
     * @param {File} file - 文件对象
     * @param {string} token - 七牛云token
     * @param {string} fileName - 文件名
     * @returns {Promise<Object>} 上传结果
     * @description
     * 数据流:
     * 1. 构建 FormData,包含 file, token, key
     * 2. 根据协议(http/https)选择上传域名
     * 3. 调用 qiniuUploadAPI 执行上传
     */
    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>} 上传结果
     * @description
     * 完整上传流程:
     * 1. 计算文件 MD5
     * 2. 调用 qiniuTokenAPI 获取上传凭证或秒传检测
     * 3. 如果已存在(秒传),直接返回文件信息
     * 4. 如果不存在,构造文件名并上传到七牛云
     * 5. 上传成功后调用 saveFileAPI 保存文件记录到后端
     */
    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 = ''

                // 根据当前 activeType 或文件类型判断
                let currentFileType = activeType.value
                if (!['image', 'video', 'audio'].includes(currentFileType)) {
                    // 如果 activeType 不是这三种(比如 text),尝试从文件类型推断
                    if (file.file.type.startsWith('image/')) currentFileType = 'image'
                    else if (file.file.type.startsWith('video/')) currentFileType = 'video'
                    else if (file.file.type.startsWith('audio/')) currentFileType = 'audio'
                    else currentFileType = 'file' // 默认
                }

                if (currentFileType === '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 (currentFileType === 'image' && uploadResult.image_info) {
                        saveData.height = uploadResult.image_info.height
                        saveData.width = uploadResult.image_info.width
                    }

                    const { data } = await saveFileAPI(saveData)
                    return { ...data, file_type: currentFileType }
                }
            }
            return null
        } catch (error) {
            console.error('Upload error:', error)
            return null
        } finally {
            loading.value = false
        }
    }

    /**
     * 文件上传前的校验
     * @param {File|File[]} file - 文件或文件数组
     * @returns {boolean} 是否通过校验
     * @description
     * 校验规则:
     * 1. 数量限制:当前已选 + 新选 <= maxCount
     * 2. 大小限制:每个文件 <= maxFileSizeMb
     * 3. 类型限制:根据 activeType 校验 MIME type
     */
    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 - 文件或文件数组
     * @description 遍历文件列表,逐个执行上传,并更新状态
     */
    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
                item.file_type = result.file_type || activeType.value // 记录文件类型
            } 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)
        }
    }

    // ==================== 提交逻辑 ====================

    /**
     * 递归查找新生成的打卡ID
     * @param {Object} data API返回的数据对象
     * @returns {string|null} 找到的ID或null
     */
    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
    }

    /**
     * 提交打卡
     * @param {Object} extraData - 额外提交数据
     * @description
     * 提交流程:
     * 1. 表单校验(内容长度、是否上传文件)
     * 2. 组装数据(note, file_type, meta_id等)
     * 3. 根据 route.query.status 判断是新增还是编辑
     * 4. 调用对应 API (addUploadTaskAPI / editUploadTaskInfoAPI)
     * 5. 成功后设置 sessionStorage 刷新标记并返回上一页
     */
    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 {
            // 准备提交数据
            // 构造 files 数组
            const files = fileList.value
                .filter(item => item.status === 'done' && item.meta_id)
                .map(item => ({
                    meta_id: item.meta_id,
                    file_type: item.file_type || activeType.value // 优先使用 item 自己的 type
                }))

            const submitData = {
                note: message.value,
                // file_type: activeType.value, // 不再依赖顶层 file_type
                // meta_id: [], // 废弃
                files: files,
                makeup_time: isMakeup.value ? route.query.date : '',
                ...extraData
            }

            // 如果没有 files,尝试推断 file_type (仅为了兼容旧逻辑或文本打卡)
            if (files.length === 0 && activeType.value === 'text') {
                submitData.file_type = 'text'
            } else if (files.length > 0) {
                // 如果有文件,file_type 可能是 'mixed' 或者取第一个文件的类型作为主类型
                // 这里暂时保留 file_type 字段以防后端必须校验,取第一个文件的类型,或者传 'mixed'
                // 如果后端已更新为只看 files 数组,则此字段可能无效
                const types = new Set(files.map(f => f.file_type))
                if (types.size > 1) {
                    submitData.file_type = 'mixed' // 假设后端支持 mixed
                } else {
                    submitData.file_type = files[0].file_type
                }
            }

            // 如果有文件,添加文件ID (为了兼容可能还在用 meta_id 的旧接口逻辑,如果确定废弃可删除)
            // submitData.meta_id = files.map(f => f.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,
                    files: submitData.files,
                    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 - 打卡类型
     * @description 切换类型不再清空文件列表,支持多类型混合上传
     */
    const switchType = (type) => {
        activeType.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 - 回调处理函数
     * @description
     * 编辑模式下:
     * 1. 调用 getUploadTaskInfoAPI 获取详情
     * 2. 回显文本、类型、文件列表
     * 3. 处理计数打卡的数据恢复
     */
    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 || '',
                                file_type: item.file_type || data.file_type || 'image' // 恢复 file_type
                            }

                            // 对于图片类型,添加isImage标记确保正确显示
                            if (fileItem.file_type === '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
    }
}