// H5 去调用App的方法
import jsBridge from "./bridge";
import { getUserInfo } from "@/api/user";

function saveUser(data) {
  localStorage.setItem("token", data);
  if (data) {
    getUserInfo().then(res => {
      console.log("存用户信息");
      console.log(res);
      console.log("----");
      if (res.code == 0) {
        localStorage.setItem("user", JSON.stringify(res.data));
      }
    });
  } else {
    console.log("调用失败");
  }
}

// 获取Token
export function getAuthToken() {
  const userAgent = navigator.userAgent;
  console.log("ua", userAgent);
  if (userAgent.indexOf("Android") > -1 || userAgent.indexOf("Adr") > -1) {
    // android
    console.log("android, 和安卓交互");
    const token = window.android.getAuthToken();
    console.log("an-token", token);
    return new Promise((resolve, reject) => {
      if (token) {
        saveUser(token);
        resolve(token);
      } else {
        reject("失败");
      }
    });
  } else if (userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
    // ios
    console.log("ios");
    return new Promise((resolve, reject) => {
      console.log("调用1");
      jsBridge.callhandler("getAuthToken", null, data => {
        console.log("调用2");
        localStorage.setItem("token", data);
        console.log("--------------");
        if (data) {
          resolve(data);
          getUserInfo().then(res => {
            if (res.code === 0) {
              localStorage.setItem("user", JSON.stringify(res.data));
            }
          });
        } else {
          console.log("调用失败");
          reject("getAuthToken", data);
        }
      });
    });
  }
}

// 退出
export function logoutToApp() {
  console.log("退出登录");
  const userAgent = navigator.userAgent;
  if (userAgent.indexOf("Android") > -1 || userAgent.indexOf("Adr") > -1) {
    console.log("an");
    window.android.logout();
  } else {
    jsBridge.callhandler("logout");
  }
}

export function navigateBack() {
  console.log("返回");
  const userAgent = navigator.userAgent;
  if (userAgent.indexOf("Android") > -1 || userAgent.indexOf("Adr") > -1) {
    console.log("an");
    window.android.navigateBack();
  } else {
    jsBridge.callhandler("navigateBack");
  }
}

export function showBottomBar(params) {
  console.log("隐藏底部");
  const userAgent = navigator.userAgent;
  if (userAgent.indexOf("Android") > -1 || userAgent.indexOf("Adr") > -1) {
    console.log("an");
    window.android.showBottomBar(params);
  } else {
    jsBridge.callhandler("showBottomBar", params);
  }
}
