import {
  download,
  get,
  getFileUrl,
} from '@/common/utils/http-util.ts'

interface PresignedUrl extends Record<string, string | undefined> {
  url?: string
  bucketName?: string
  objectName?: string
}

export interface DefaultPlace {
  province?: string
  city?: string
  provinceName?: string
  cityName?: string
}

export interface District {
  id?: string
  province?: string
  city?: string
  area?: string
  town?: string
  districtName?: string
}


export default {
  defaultPlace() {
    return get<DefaultPlace>('/district/default_place')
  },
  districtList(data: { pid?: string, name?: string }) {
    return get<District[]>('/district/list', data)
  },
  obtainPresignedUrl(filename: string) {
    return get<PresignedUrl>('/oss/obtain_presigned_url', {filename})
  },
  download(filename: string, params?: any, defaultName: string = '下载的文件') {
    let url = ''
    if (filename.startsWith('http') || filename.startsWith('https')) {
      url = filename
    }
    if (filename.startsWith('/')) {
      url = '/oss/download' + filename
    } else {
      url = '/oss/download/' + filename
    }
    return download(url, params, defaultName)
      .then(res => {
        // 创建新的URL并指向File对象或者Blob对象的地址
        const blobURL = window.URL.createObjectURL(res.data.data)
        // 创建a标签，用于跳转至下载链接
        const tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', decodeURI(res.data.filename))
        // 兼容：某些浏览器不支持HTML5的download属性
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        // 挂载a标签
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        // 释放blob URL地址
        window.URL.revokeObjectURL(blobURL)
      })
  },
  fileUrl(filename?: string) {
    if (filename == null || filename.length <= 0) {
      return ''
    }
    if (filename.startsWith('http') || filename.startsWith('https')) {
      return filename
    }
    if (filename.startsWith('/')) {
      return getFileUrl('/oss/download' + filename)
    } else {
      return getFileUrl('/oss/download/' + filename)
    }
  },
}
