import { aliyunpolicy } from "@/utils/upload";
export function uploadFile(rules) {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 1,
      sizeType: ["compressed"],
      sourceType: ["album", "camera"], //从相册选择
      success: (chooseImageRes) => {
        const tempFilePaths = chooseImageRes.tempFilePaths[0];
        if (rules && !rules(tempFilePaths)) {
          return;
        }
        aliyunpolicy({ imageStatus: 6 }).then((res) => {
          let ossToken = res.resultContent;
          uni.uploadFile({
            url: ossToken.host,
            name: "file",
            filePath: tempFilePaths,
            fileType: "image",
            header: {
              AuthorizationToken: "WX " + uni.getStorageSync("token"),
            },
            formData: {
              key: ossToken.dir,
              OSSAccessKeyId: ossToken.accessid,
              policy: ossToken.policy,
              Signature: ossToken.signature,
              success_action_status: 200,
            },
            success: (result) => {
              resolve(ossToken.dir);
            },
            fail: (error) => {
              uni.showToast({
                title: "上传报错",
                icon: "none",
              });
              return;
            },
          });
        });
      },
    });
  });
}

// 下载
export function downloadFile(url, fileName) {
  const a = document.createElement("a");
  a.setAttribute("href", url)
  a.setAttribute("download", fileName)
  a.setAttribute("target", "_blank")
  let clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);
  a.dispatchEvent(clickEvent);
}

export function base64ToPath(base64) {
  return new Promise(function(resolve, reject) {
      if (typeof window === 'object' && 'document' in window) {
          base64 = base64.split(',')
          var type = base64[0].match(/:(.*?);/)[1]
          var str = atob(base64[1])
          var n = str.length
          var array = new Uint8Array(n)
          while (n--) {
              array[n] = str.charCodeAt(n)
          }
          return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type: type })))
      }
      var extName = base64.match(/data\:\S+\/(\S+);/)
      if (extName) {
          extName = extName[1]
      } else {
          reject(new Error('base64 error'))
      }
      var fileName = Date.now() + '.' + extName
      if (typeof plus === 'object') {
          var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
          bitmap.loadBase64Data(base64, function() {
              var filePath = '_doc/uniapp_temp/' + fileName
              bitmap.save(filePath, {}, function() {
                  bitmap.clear()
                  resolve(filePath)
              }, function(error) {
                  bitmap.clear()
                  reject(error)
              })
          }, function(error) {
              bitmap.clear()
              reject(error)
          })
          return
      }
      if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
          var filePath = wx.env.USER_DATA_PATH + '/' + fileName
          wx.getFileSystemManager().writeFile({
              filePath: filePath,
              data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
              encoding: 'base64',
              success: function() {
                  resolve(filePath)
              },
              fail: function(error) {
                  reject(error)
              }
          })
          return
      }
      reject(new Error('not support'))
  })
}