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

import { saveFile } from '@/common/app'
import { serverBaseUrl } from '@/common'

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})
  },
  ossDownload(filename: string, params?: any) {
    let url = ''
    if (filename.startsWith('http') || filename.startsWith('https')) {
      url = filename
    }
    if (filename.startsWith('/')) {
      url = '/oss/download' + filename
    } else {
      url = '/oss/download/' + filename
    }
    saveFile(get<{ content: Blob, filename: string }>(url, params, {responseType: 'arraybuffer'}))
  },
  fileUrl(filename?: string) {
    if (filename == null || filename.length <= 0) {
      return ''
    }
    if (filename.startsWith('http') || filename.startsWith('https') || filename.startsWith('blob')) {
      return filename
    }
    if (filename.startsWith(serverBaseUrl + '/oss/download')) {
      return filename
    } else if (filename.startsWith('/')) {
      return getFileUrl('/oss/download' + filename)
    } else {
      return getFileUrl('/oss/download/' + filename)
    }
  },
  changeIdentity(id: string) {
    return get<LoginTypes.UserDetail>('/customer/change_identity', {targetCustomerId: id})
  },
}
