// H5 去调用App的方法
import jsBridge from "./bridge";

class bridgeToAppFun {
  constructor() {
    this.userAgent = null;
    console.log(navigator.userAgent);
    if (
      navigator.userAgent.indexOf("Android") > -1 ||
      navigator.userAgent.indexOf("Adr") > -1
    ) {
      this.userAgent = "android";
    } else if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
      this.userAgent = "ios";
    } else {
      this.userAgent = "web";
    }
  }
  // 获取Token
  getAuthToken() {
    if (this.userAgent === "android") {
      // android
      let token = null;
      try {
        token = window.android.getAuthToken();
        localStorage.setItem("token", token);
      } catch {
        console.log("token获取失败");
      }
      return new Promise((resolve, reject) => {
        if (token) {
          resolve(token);
        } else {
          reject("失败");
        }
      });
    } else if (this.userAgent === "ios") {
      // ios
      return new Promise((resolve, reject) => {
        jsBridge.callhandler("getAuthToken", null, data => {
          localStorage.setItem("token", data);
          if (data) {
            resolve(data);
          } else {
            console.log("调用失败");
            reject("getAuthToken", data);
          }
        });
      });
    }
  }
  // 退出
  logoutToApp() {
    console.log("退出登录");
    if (this.userAgent === "android") {
      console.log("an");
      window.android.logout();
    } else {
      console.log("ios");
      jsBridge.callhandler("logout");
    }
  }
  navigateBack() {
    console.log("返回");
    if (this.userAgent === "android") {
      console.log("an");
      try {
        const referrer = document.referrer;
        if (referrer !== "") {
          console.log("reffer不为空", referrer);
          const home_url =
            "https://shop92680967.youzan.com/v2/showcase/homepage?alias=6aFsQ4vCp7";
          location.href = home_url;
        } else {
          console.log("调用navigateBack");
          window.android.navigateBack();
        }
      } catch {
        console.log("返回调用失败，都不行");
      }
    } else {
      jsBridge.callhandler("navigateBack");
    }
  }
  showBottomBar(params) {
    console.log("隐藏底部");
    if (this.userAgent === "android") {
      console.log("an");
      window.android.showBottomBar(params);
    } else {
      jsBridge.callhandler("showBottomBar", params);
    }
  }
  redirectToLogin() {
    console.log("去登陆");
    if (this.userAgent === "android") {
      console.log("an");
      window.android.redirectToLogin();
    } else {
      jsBridge.callhandler("redirectToLogin");
    }
  }
}

export default bridgeToAppFun;
