import methods from "@/common/methodTool";
export function download(url) {
  url = methods.splitImgHost(url);
  // #ifdef H5
  window.location.href = url;
  // #endif
  // #ifdef MP-WEIXIN
  const _s = saveImgToLoca;
  uni.getSetting({
    success: (res) => {
      if (!res.authSetting["scope.writePhotosAlbum"]) {
        uni.authorize({
          scope: "scope.writePhotosAlbum",
          success() {
            _s(url);
          },
          fail() {},
        });
      } else {
        _s(url);
      }
    },
  });
  // #endif
}

export function saveImgToLoca(url) {
  uni.downloadFile({
    url: url, //图片地址
    success: ({ statusCode, tempFilePath }) => {
      if (statusCode === 200) {
        const type = tempFilePath.substr(tempFilePath.lastIndexOf(".") + 1);
        if (type === "pdf") {
          uni.getFileSystemManager().saveFile({
            tempFilePath,
            success: function (res) {
              uni.showToast({
                title: "保存成功",
                icon: "none",
              });
            },
            fail: function () {
              uni.showToast({
                title: "保存失败",
                icon: "none",
              });
            },
          });
          return;
        }
        uni.showModal({
          title: "提示",
          content: "确定保存到相册吗",
          success: (res) => {
            if (res.confirm) {
              uni.saveImageToPhotosAlbum({
                filePath: tempFilePath,
                success: function () {
                  uni.showToast({
                    title: "保存成功",
                    icon: "none",
                  });
                },
                fail: function () {
                  uni.showToast({
                    title: "保存失败",
                    icon: "none",
                  });
                },
              });
            }
          },
        });
      }
    },
  });
}
export function preview(url) {
  url = methods.splitImgHost(url);
  // #ifdef H5
  uni.navigateTo({
    url: `/pages5/webview/sdlink?url=https://preview.xyyxt.net?src=${url}`,
  });
  // #endif
  // #ifdef MP-WEIXIN
  uni.downloadFile({
    url: url,
    success: ({ tempFilePath }) => {
      uni.openDocument({
        filePath: tempFilePath,
        showMenu: true,
        success: (res) => {},
        fail: (err) => {
          uni.showToast({
            icon: "none",
            title: "文档地址错误",
          });
        },
      });
    },
    fail: (err) => {
      this.downLoading = false;
      uni.showModal({
        title: "提示",
        content: "文档错误," + err.errMsg,
        showCancel: false,
      });
    },
  });
  // #endif
}

export function throttle(fn, delay) {
  let timeout = null;
  return function () {
    let args = arguments;
    if (!timeout) {
      timeout = setTimeout(() => {
        timeout = null;
        fn.apply(this, args);
      }, delay);
    }
  };
}
