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

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

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

// 退出
export function logoutToApp() {
  jsBridge.callhandler("logout");
}
