import type { ServerList, ServerRes } from '~/service/index'
import { SystemDim } from '~/dim/system'
import httpRequest from "~/service/index";

interface OssSignature {
  accessKeyId: string,
  policy: string,
  signature: string,
  filePath: string,
  host: string,
  expire: string,
  callback: string,
}

export interface OssCallback {
  path: string,
  size: number,
  width: number,
  height: number,
}

export function useOss() {
  const apiRoot = "/system/oss"
  const host = "https://io.house-tk.com"

  async function getSignature(dir: string, filename: string, fileType: string) {
    return await httpRequest.post<ServerRes<OssSignature>>(`${apiRoot}/signature`, { dir, filename, fileType })
  }

  async function uploadImage(file: File, dir: string): Promise<any> {
    return upload(file, dir, SystemDim.FileType.image)
  }

  async function uploadFile(file: File, dir: string): Promise<any> {
    return upload(file, dir, SystemDim.FileType.file)
  }

  async function upload(file: File, dir: string, fileType: string): Promise<any> {
    let signatureRes:any = await getSignature(dir, file.name, fileType)
    if (signatureRes.code != 200)
      return Promise.reject("上传失败. 无法获得oss签名")

    let signature = signatureRes.data
    let formData = new FormData()
    formData.append("key", signature.filePath)   // 存储在oss的文件路径
    formData.append("OSSAccessKeyId", signature.accessKeyId)
    formData.append("policy", signature.policy)
    formData.append("success_action_status", '200') // 让服务端返回200,不然，默认会返回204
    formData.append("signature", signature.signature)
    formData.append("callback", signature.callback)
    formData.append("file", file)
    return await httpRequest.post<any>(signature.host, formData)
  }

  return {
    host,
    upload,
    uploadImage,
    uploadFile,
  }
}
