import {
  getConfigService,
  getUploadTokenService,
  uploadService
} from '@/api/upload'
import { v4 as uuidv4 } from 'uuid'
import * as qiniu from 'qiniu-js'
import { ref } from 'vue'

/**
 * 上传文件的公共方法
 * @param file
 * @param type
 * @param onProgress
 * @returns {Promise<void>}
 */
export const uploadFile = async (file, type, onProgress) => {
  const userAgent = ref(import.meta.env.VITE_USER_AGENT)

  return new Promise(async (resolve, reject) => {
    try {
      const res = await getUploadTokenService(userAgent.value)
      const uploadToken = res.data
      if (uploadToken !== 'noAuth') {
        const configRes = await getConfigService(userAgent.value, type)
        let prefixUrl = null
        let folder = null
        if (configRes.code === 100000) {
          prefixUrl = configRes.data.prefixUrl
          folder = configRes.data.folder
        }
        //使用七牛云JS-SDK直传
        const uuid = uuidv4().replace(/-/g, '')
        const now = new Date()
        const timestamp =
          now.getFullYear().toString() +
          String(now.getMonth() + 1).padStart(2, '0') +
          String(now.getDate()).padStart(2, '0') +
          String(now.getHours()).padStart(2, '0') +
          String(now.getMinutes()).padStart(2, '0') +
          String(now.getSeconds()).padStart(2, '0')
        const fileType = file.name.substring(file.name.lastIndexOf('.'))
        const key = `${folder}${uuid}_${timestamp}${fileType}`
        const putExtra = {
          fname: file.name, //文件名
          params: {}, //额外参数
          mimeType: ['image/*'] //限制文件上传类型
        }
        const config = {
          useCdnDomain: true,
          region: qiniu.region.z2
        }
        const observable = qiniu.upload(
          file,
          key,
          uploadToken,
          putExtra,
          config
        )
        const observer = {
          next(res) {
            // 计算上传进度
            const progress = res.total.percent.toFixed(2)
            // 调用上传进度回传函数
            console.log('上传进度', progress)
            if (onProgress) {
              onProgress(progress) // 将进度传递给调用者
            }
          },
          error(err) {
            // 上传出错
            console.log('错误', err)
            reject('上传失败')
          },
          complete(res) {
            // 上传完成,生成预览链接
            const previewUrl = `${prefixUrl}/${res.key}`
            console.log('预览链接URL', previewUrl, res.key)
            resolve({
              data: {
                url: previewUrl,
                fileKey: res.key.replace(new RegExp(`^${folder}`), '')
              }
            })
          }
        }
        observable.subscribe(observer)
      } else {
        const res = await uploadService(userAgent.value, file)
        console.log('直传结果', res)
        resolve({
          data: {
            url: res.data.fileUrl,
            fileKey: res.data.fileKey
          }
        })
      }
    } catch (error) {
      console.log('上传过程中发生错误:', error)
      reject('上传失败!')
    }
  })
}
