import OSS, { type Checkpoint } from 'ali-oss'
import { type AliOssSTS, getAliOssTokenAxios } from '@/service/api/upload'

// 初始化OSS客户端
export function initOSSClient(token: AliOssSTS) {
  return new OSS({
    region: token.Region || 'oss-cn-shenzhen',
    accessKeyId: token.AccessKeyId,
    accessKeySecret: token.AccessKeySecret,
    stsToken: token.SecurityToken,
    bucket: token.BucketName,
    refreshSTSTokenInterval: 600000, // 10分钟刷新一次token
    refreshSTSToken: async () => {
      // 这里可以添加获取新token的逻辑
      const res = await getAliOssTokenAxios()
      return {
        accessKeyId: res.AccessKeyId,
        accessKeySecret: res.AccessKeySecret,
        stsToken: res.SecurityToken,
      }
    },
  })
}

/**
 * 上传文件到OSS (注意进度从 0 开始到 1 结束)
 */
export async function uploadFileToOSS(client: OSS, file: File, path: string, progress?: ((progress: number, checkpoint?: Checkpoint, http?: any) => any) | undefined) {
  try {
    const result = await client.multipartUpload(path, file, {
      parallel: 5, // 并发分片数
      partSize: 1024 * 1024 * 5, // 分片大小5MB
      progress,
    })
    return result
  }
  catch (error) {
    console.error('上传文件失败:', error)
    throw error
  }
}
