import { jsx as C } from "react/jsx-runtime";
import { useState as x, useEffect as S } from "react";
import { AuthContext as M } from "./AuthContext.mjs";
import { authApi as $, dataApi as H } from "./api/apis.mjs";
import { tokenTool as d, JWT as _, isExpired as J } from "./tool.mjs";
import { AuthErrorMessages as N } from "./Errors.mjs";
const s = {
  isAuthenticated: !1,
  loginInfo: null,
  user: null,
  userInfo: null,
  setUserInfo: function(c) {
    this.userInfo = c;
  },
  setLoginUser: function(c) {
    this.user = c;
  },
  setLoginAdrress: function(c) {
    this.loginInfo = c;
  },
  signin() {
    if (this.loginInfo) {
      d.delToken(), s.isAuthenticated = !1;
      const c = `${window.location.protocol}//${window.location.host}${window.location.pathname}`, g = this.loginInfo.loginUrl, r = (() => {
        try {
          return new URL(g).origin;
        } catch (k) {
          return "";
        }
      })();
      let w = "";
      try {
        w = new URL(g).searchParams.get("service_key") || "";
      } catch (k) {
      }
      const f = this.loginInfo.checkTicketPath;
      if (r && w && f) {
        const k = `__jsonp_${Date.now()}_${Math.floor(Math.random() * 1e3)}`, b = `${r}/user_ticket?service_key=${encodeURIComponent(w)}&callback=${encodeURIComponent(k)}`;
        let I = !1;
        const m = (l) => {
          try {
            delete window[k];
          } catch (U) {
          }
          l && l.parentNode && l.parentNode.removeChild(l);
        };
        try {
          const l = document.createElement("script");
          window[k] = (p) => {
            m(l), I = !0;
            const R = (typeof p == "string" ? p : String(p || "")).trim();
            if (!R) {
              window.location.href = g.replace("{callback_url}", c);
              return;
            }
            const v = new URL(window.location.href);
            v.searchParams.set("ticket", R), window.location.href = v.toString();
          }, l.src = b, l.onerror = () => {
            m(l), window.location.href = g.replace("{callback_url}", c);
          }, document.body.appendChild(l), setTimeout(() => {
            I ? m(l) : (m(l), window.location.href = g.replace("{callback_url}", c));
          }, 8e3);
          return;
        } catch (l) {
          window.location.href = g.replace("{callback_url}", c);
          return;
        }
      }
      window.location.href = this.loginInfo.loginUrl.replace("{callback_url}", c);
    }
  },
  signout() {
    return new Promise((c, g) => {
      $.logout().finally(() => {
        for (const r in window.localStorage)
          (r.substring(r.length - 2) === ".u" || r === "u") && d.delToken(r), (r.substring(r.length - 2) === ".idu" || r === "idu") && d.delIdTokenHint(r);
        s.isAuthenticated = !1, this.loginInfo && this.loginInfo.logoutUrl.indexOf("{callback_url}") > -1 && (window.location.href = this.loginInfo.logoutUrl.replace("{callback_url}", `${window.location.protocol}//${window.location.host}${window.location.pathname}`)), c();
      });
    });
  }
}, q = (c, g, r) => {
  var w;
  return (w = s.user) != null && w.token ? $.postRefreshToken(s.user.token, c, g || "", void 0, r).then((f) => {
    const i = _(f.token), k = i == null ? void 0 : i.exp, b = i == null ? void 0 : i.ro, I = i == null ? void 0 : i.ten, m = i == null ? void 0 : i.uid, l = i == null ? void 0 : i.oid, U = {
      token: f.token,
      exp: k,
      ten: I,
      ro: b,
      uid: m,
      oid: l
    };
    return d.setToken(f.token), s.user = U, f.token;
  }) : Promise.reject({
    status: 401,
    massage: "当前用户token不存在"
  });
};
function F({
  children: c
}) {
  const [g, r] = x(!0), [w, f] = x(null), [i, k] = x(null), [b, I] = x(), m = (e) => {
    const t = _(e), h = t == null ? void 0 : t.ten, o = window.location.pathname.split("/")[2] || h, a = t == null ? void 0 : t.oid;
    return $.postRefreshToken(e, o, a).then(({
      token: n
    }) => n);
  };
  S(() => {
    $.getLoginUrl().then((e) => {
      s.loginInfo = e[0];
    }).then(() => {
      var T, P;
      const e = new URLSearchParams(window.location.search), t = window.location.pathname.split("/").filter((u) => !!u), o = window.location.hostname !== "localhost" && `${t[1]}.${t[2]}.u` || "u", a = e.get("token") || d.getToken(o);
      if (a && !J(a))
        return m(a);
      const n = {};
      if ([...e.entries()].forEach((u) => n[u[0]] = u[1]), Object.keys(n).length > 0 && (T = s.loginInfo) != null && T.checkTicketPath) {
        let u = (P = s.loginInfo) == null ? void 0 : P.checkTicketPath;
        return u.search("/v1/") !== -1 && (u = u.substring(3)), $.getToken(u, n);
      }
      throw {
        status: 401,
        message: "请重新登录"
      };
    }).then((e) => {
      if (!e)
        r(!1);
      else {
        let t, h;
        typeof e == "string" ? t = e : (t = e.accessToken, h = e.otherToken), t && d.setToken(t), h && d.setIdTokenHint(h);
        const o = t ? _(t) : {}, a = o == null ? void 0 : o.exp, n = o == null ? void 0 : o.ro, T = o == null ? void 0 : o.ten, P = o == null ? void 0 : o.uid, u = o == null ? void 0 : o.oid, L = {
          token: t,
          exp: a,
          ten: T,
          ro: n,
          uid: P,
          oid: u
        };
        return s.user = L, f(L), s.setLoginUser(L), l(t).then(() => {
          r(!1);
        });
      }
    }).catch((e) => {
      if (e.message === N.UserLeft) {
        r(!1);
        const t = {
          token: ""
        };
        f(t), s.setLoginUser(t);
      } else if (e.status === 401)
        console.log(e), U();
      else {
        r(!1);
        const t = {
          token: ""
        };
        f(t), I(e), s.setLoginUser(t), console.error(e);
      }
    }).finally(() => {
      const e = new URL(window.location.href);
      [...e.searchParams.keys()].forEach((t) => e.searchParams.delete(t)), history.replaceState({}, "", e);
    });
  }, []);
  const l = (e) => {
    const t = e ? _(e).uid : "";
    return H.getUserInfo(t).then((h) => (k(h), s.setUserInfo(h), h));
  }, U = () => s.signin(), p = () => s.signout(), A = (e) => {
    s.setLoginAdrress(e);
  }, R = (e, t, h) => {
    var o;
    return (o = s.user) != null && o.token ? q(e, t, h).then((a) => {
      const n = _(a), T = n == null ? void 0 : n.exp, P = n == null ? void 0 : n.ro, u = n == null ? void 0 : n.ten, L = n == null ? void 0 : n.uid, j = n == null ? void 0 : n.oid, E = {
        token: a,
        exp: T,
        ten: u,
        ro: P,
        uid: L,
        oid: j
      };
      return f(E), d.setToken(a), s.user = E, a;
    }) : Promise.reject({
      status: 401,
      massage: "当前用户token不存在"
    });
  }, v = {
    loading: g,
    signin: U,
    signout: p,
    setLoginAdrress: A,
    loginInfo: s.loginInfo,
    userInfo: i,
    user: w,
    error: b,
    setUser: f,
    refresh: R
    // DO: 15. permissions 可以另外封装组件
  };
  return /* @__PURE__ */ C(M.Provider, {
    value: v,
    children: c
  });
}
export {
  F as AuthProvider,
  s as authProvider,
  q as refreshToken
};
