import store from "@/store/index.js";
import { aliyunpolicy } from "@/utils/login";
import config from "@/common/config";
export default {
  isGoLogin(isBack = true) {
    if (!uni.getStorageSync("user_account")) {
      uni.navigateTo({
        url: "/pages/login/login?isBack=" + 1,
      });
      return true;
    } else {
      return false;
    }
  },
  isLogin() {
    if (uni.getStorageSync("user_account")) {
      return true;
    } else {
      return false;
    }
  },
  isLogout() {
    // uni.removeStorageSync('user_account')
    // uni.removeStorageSync('token')
  },
  //提示
  showToast(title, icon = "none", time = 2000) {
    return setTimeout(() => {
      uni.showToast({
        title: title,
        icon: icon,
        duration: time,
      });
    }, 500);
  },
  //图片路径填补
  splitImgHost(url, scale = false, width = 250) {
    if (!url) {
      return "";
    } else if (
      url.indexOf("http") != -1 ||
      url.indexOf("https") != -1 ||
      url.indexOf("wxfile") != -1
    ) {
    } else {
      url = config.BASE_IMG_URL + url;
    }
    if (scale) {
      url = url + "?x-oss-process=image/resize,w_" + width;
    }
    return url;
  },
  setUuid(id) {
    uni.setStorageSync("uuid", id);
  },

  getUuid() {
    return uni.getStorageSync("uuid");
  },
  exit() {
    uni.removeStorageSync("user_account");
    uni.removeStorageSync("token");
    store.state.userInfo = null;
    uni.reLaunch({
      url: "/pages/index/index",
    });
  },
  //压缩图片
  imageInfos(url) {
    var self = this;
    return new Promise((resolve, reject) => {
      uni.getImageInfo({
        src: url,
        success: async (res) => {
          let canvasWidth = res.width; //图片原始长宽
          let canvasHeight = res.height;
          if (canvasWidth > 2000 || canvasHeight > 2000) {
            uni.compressImage({
              src: url,
              quality: 75,
              width: "35%",
              height: "35%",
              success: async (rest) => {
                const waitUpload = await self.uploadFile(rest.tempFilePath, 0);
                console.log(waitUpload, "waitUpload");
                resolve(waitUpload);
              },
            });
          } else if (canvasWidth > 1000 || canvasHeight > 1000) {
            uni.compressImage({
              src: url,
              quality: 75,
              width: "50%",
              height: "50%",
              success: async (rest) => {
                const waitUpload = await self.uploadFile(rest.tempFilePath, 0);
                console.log(waitUpload, "waitUpload");
                resolve(waitUpload);
              },
            });
          } else {
            const waitUpload = await self.uploadFile(url, 0);
            console.log(waitUpload, "waitUpload");
            resolve(waitUpload);
            // console.log('无需压缩', url);
            // resolve(url);
          }
        },
      });
    });
  },
  //上传图片
  uploadFile(options, int) {
    return new Promise((resolve, reject) => {
      var self = this;
      // if (options.indexOf("//tmp") === -1 && options.indexOf("//temp") === -1) {
      //   resolve(options);
      //   return;
      // }
      var data = {
        imageStatus: int,
      };
      aliyunpolicy(data).then((res) => {
        var ossToken = res.data.data.resultContent;
        uni.uploadFile({
          url: ossToken.host,
          name: "file",
          filePath: options,
          fileType: "image",
          header: {
            AuthorizationToken: "WX " + uni.getStorageSync("token"),
          },
          formData: {
            key: ossToken.dir,
            OSSAccessKeyId: ossToken.accessid,
            policy: ossToken.policy,
            Signature: ossToken.signature,
            // callback: ossToken.callback,
            success_action_status: 200,
          },
          success: (result) => {
            // if (result.statusCode === 200) {
            resolve(ossToken.dir);
            // } else {
            // 	uni.showToast({
            // 		title: '上传失败',
            // 		icon: 'none'
            // 	});
            // 	return;
            // }
          },
          fail: (error) => {
            uni.showToast({
              title: "上传接口报错",
              icon: "none",
            });
            return;
          },
        });
      });
    });
  },
};

// 监测域名
export function checkDomain(str) {
  let domain =
    /^([\w-]+\.)+((com)|(net)|(org)|(gov\.cn)|(info)|(cc)|(com\.cn)|(net\.cn)|(org\.cn)|(name)|(biz)|(tv)|(cn)|(mobi)|(name)|(sh)|(ac)|   (io)|(tw)|(com\.tw)|(hk)|(com\.hk)|(ws)|(travel)|(us)|(tm)|(la)|(me\.uk)|(org\.uk)|(ltd\.uk)|(plc\.uk)|(in)|(eu)|(it)|(jp))$/;
  return domain.test(str);
}

export function getQueryString(name) {
  const url = location.search; //获取url中"?"符后的字串
  let theRequest = new Object();
  if (url.indexOf("?") != -1) {
    let str = url.substr(1);
    let strs = str.split("&");
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
  }
  if (name) {
    return theRequest[name];
  }
  return theRequest;
}

export function isWechat() {
  var ua = window.navigator.userAgent.toLowerCase();
  return ua.match(/micromessenger/i) == "micromessenger"
}
