import SparkMd5 from 'spark-md5'
import {sendChromeAPIMessage} from '@/api/chromeApi'

export function getImageMd5(imageUrl) {
  return new Promise((resolve) => {
    fetch(imageUrl).then((response) => response.blob()) // 将响应转换为Blob对象
      .then((blobData) => {
        const fileName = imageUrl.match(/\/([^/]+)$/).at(-1)
        const reader = new FileReader();
        // 读取Blob对象的内容
        reader.onloadend = function () {
          const spark = new SparkMd5.ArrayBuffer()
          spark.append(reader.result);
          const md5 = spark.end()
          resolve({md5, fileName});
        };
        reader.readAsArrayBuffer(blobData); // 将Blob对象作为参数传递给FileReader的readAsArrayBuffer()方法
      })
  });
}

export async function uploadImage(folderId, imageUrl, mallId) {
  let res1 = await getImageMd5(imageUrl)
  let detailList = []
  detailList.push({
    materialMd5: res1.md5,
    materialName: res1.fileName,
    materialType: 1
  })
  let res2 = await sendChromeAPIMessage({
    url: 'marvel-mms/cn/api/kiana/gmp/bg/phoenix/api/material/create',
    needMallId: true,
    mallId: mallId,
    data: {
      createDetailList: detailList,
      folderId: folderId
  }})

  if (res2.success) {
    if (res2.result.responseDetailList[0].alreadyExists) {
      return res2.result.responseDetailList[0].imgUrl
    } else {
      let res3 = await sendChromeAPIMessage({
        url: 'galerie/business/get_signature?sdk_version=js-0.0.16-alpha.0&tag_name=product-material-tag',
        needMallId: true,
        mallId: mallId,
        data: {
          bucket_tag: "product-material-tag"
        }
      })

      let res4 = await sendChromeAPIMessage({
        url: 'https://file.kuajingmaihuo.com/api/galerie/v3/store_image?sdk_version=js-0.0.16-alpha.0&tag_name=product-material-tag',
        isFormData: true,
        data: {
          url_width_height: true,
          image: imageUrl,
          upload_sign: res3.result.signature
        }
      })

      let res5 = await sendChromeAPIMessage({
        url: 'marvel-mms/cn/api/kiana/gmp/bg/phoenix/api/material/edit',
        needMallId: true,
        mallId: mallId,
        data: {
          id: res2.result.responseDetailList[0].id,
          materialName: res2.result.responseDetailList[0].materialName,
          materialType: 1,
          uploadStatus: 3,
          url: res4.url
        }
      })
      return res5.result.imgUrl
    }
  }

}
