const tencentBucket = "daya-online-1303457149"
const ossType = "tencent"
function fileUpload({ host, token }, { fileName, file }) {
  // 上传名称加上时间戳
  fileName = addTimestampBeforeExtension(fileName)
  return new Promise((res, rej) => {
    getUploadSign(fileName, host, token)
      .then(resUploadSign => {
        if (resUploadSign.code === 200) {
          try {
            onOnlyFileUpload(resUploadSign.data.signature, {
              fileName,
              file
            })
              .then(resUpload => {
                if (resUpload.statusCode === 200) {
                  res(resUpload.Location.includes("http") ? resUpload.Location : `https://${resUpload.Location}`)
                } else {
                  rej("")
                }
              })
              .catch(() => {
                rej("")
              })
          } catch {
            rej("")
          }
        } else {
          rej("")
        }
      })
      .catch(() => {
        rej("")
      })
  })
}

const getUploadSign = (fileName, host, token) => {
  const fileUrl = `pptList/${filePath || "errPath/"}` + fileName
  return ajaxRequest(
    `${host}/edu-app/open/getUploadSign?pluginName=${ossType}`,
    "POST",
    {
      "Content-Type": "application/json",
      Authorization: token
    },
    {
      postData: {
        key: fileUrl
      },
      pluginName: ossType,
      bucketName: tencentBucket,
      filename: fileUrl
    }
  )
}

const onOnlyFileUpload = (signature, params) => {
  const cos = new COS({
    Domain: "https://oss.dayaedu.com",
    Protocol: "https",
    getAuthorization: async (options, callback) => {
      callback({ Authorization: signature })
    }
  })
  return cos.uploadFile({
    Bucket: tencentBucket /* 填写自己的 bucket，必须字段 */,
    Region: "ap-nanjing" /* 存储桶所在地域，必须字段 */,
    Key: `pptList/${filePath || "errPath/"}${params.fileName}`,
    /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
    Body: params.file, // 上传文件对象
    SliceSize: 1024 * 1024 * 500 /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */,
    onProgress: function (progressData) {
      // onProgress({ percent: Math.ceil((progressData.percent || 0) * 100) })
    }
  })
}

function ajaxRequest(url, method = "GET", headers = {}, body = null) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open(method, url, true)
    // 设置请求头
    for (const [key, value] of Object.entries(headers)) {
      xhr.setRequestHeader(key, value)
    }
    xhr.onload = function () {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(JSON.parse(xhr.responseText))
      } else {
        reject(new Error(`HTTP error! status: ${xhr.status}`))
      }
    }
    xhr.onerror = function () {
      reject(new Error("Network error occurred"))
    }
    xhr.send(method === "GET" ? null : JSON.stringify(body))
  })
}

function addTimestampBeforeExtension(filename) {
  const dotIndex = filename.lastIndexOf(".")
  const name = filename.substring(0, dotIndex)
  const extension = filename.substring(dotIndex)
  return `${name}_${Date.now()}${extension}`
}
