'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var vue = require('vue');
var elementPlus = require('element-plus');
var Cookies = require('js-cookie');
require('../../../../hooks/index.js');
var index = require('../../../../hooks/base/useGlobalConfig/index.js');
require('../../../../utils/index.js');
var url = require('../../../../utils/src/http/url.js');
var tenant = require('../../../../utils/src/tenant.js');
var createModes = require('../../../../utils/src/http/createModes.js');
var loginDialog = require('./loginDialog.js');
var key = require('../../../../constants/key.js');
var index$1 = require('../../../../hooks/store/useLogin/index.js');
var is = require('../../../../utils/src/is.js');

const _hoisted_1 = { key: 0 };
const _hoisted_2 = ["src"];
const _hoisted_3 = ["src"];
const loginEnvKey = "VITE_GIIME_LOGIN_URL";
var _sfc_main = /* @__PURE__ */ vue.defineComponent({
  __name: "LoginDialog",
  props: loginDialog.loginDialogProps,
  setup(__props) {
    const props = __props;
    const router = index.useGlobalConfig("router");
    const route = vue.computed(() => router.value ? vue.unref(router.value.currentRoute) : void 0);
    const loginStore = index$1.useLoginStore();
    const loginUrl = vue.ref("");
    const importMetaEnv = index.useGlobalConfig("env");
    const isSSRShowDialog = vue.ref(importMetaEnv.value.SSR === false);
    let originLoginUrl = "";
    if (is.isString(importMetaEnv.value[loginEnvKey])) {
      originLoginUrl = importMetaEnv.value[loginEnvKey];
    } else {
      const loginPath = tenant.isGiikin() ? "/guard/sso/public/auth" : "/fe/basic/login";
      const resetMode = importMetaEnv.value[key.resetEnvMode];
      const hostname = window.location.hostname;
      const findEnvConfig = Object.values(createModes.envConfigs).find((config) => config.domain === hostname);
      if (resetMode && createModes.envConfigs[resetMode]) {
        originLoginUrl = url.urlJoin(createModes.envConfigs[resetMode].url, loginPath);
      } else if (findEnvConfig) {
        originLoginUrl = url.urlJoin(findEnvConfig.url, loginPath);
      } else if (importMetaEnv.value.DEV) {
        originLoginUrl = url.urlJoin(createModes.envConfigs.develop.url, loginPath);
      } else {
        originLoginUrl = loginPath;
      }
    }
    const handleLogin = () => {
      const protocol = window.location.protocol;
      const host = window.location.host;
      const myPath = window.location.pathname;
      loginUrl.value = `${originLoginUrl}?_system=${props.system}`;
      if (route.value && props.needScanningRouteNames.includes(route.value?.name?.toString() ?? "")) {
        loginUrl.value += "&is_dashboard=1";
      }
      const guard_company = Cookies.get("guard_company");
      if (guard_company) {
        loginUrl.value += `&companyId=${guard_company}`;
      }
      loginUrl.value += `&${props.redirectUrlField}=${protocol}//${host}${myPath}`;
      console.log(loginUrl.value);
      if (is.isMobile() || is.isDingTalk()) {
        window.location.href = loginUrl.value;
      }
    };
    const handleRetryLogin = () => {
      loginStore.resetLoginBlock();
      handleLogin();
    };
    const handleClearCache = () => {
      const cookies = document.cookie.split(";");
      const curDomain = url.getDomain();
      cookies.forEach((cookie) => {
        const name = cookie.split("=")[0].trim();
        if (name) {
          Cookies.remove(name);
          Cookies.remove(name, { domain: curDomain });
          Cookies.remove(name, { domain: `.${curDomain}` });
        }
      });
      elementPlus.ElMessage.success("\u6E05\u9664cookie\u7F13\u5B58\u6210\u529F");
    };
    vue.watch(
      () => loginStore.showLogin,
      (value) => {
        if (value) {
          handleLogin();
        }
      }
    );
    const reloadTimer = vue.ref();
    if (route.value) {
      vue.watch(route, (newValue, oldValue) => {
        if (!oldValue || !newValue) {
          return;
        }
        if (oldValue.name && props.needScanningRouteNames.includes(oldValue.name.toString())) {
          window.clearInterval(reloadTimer.value);
        }
        if (newValue.name && props.needScanningRouteNames.includes(newValue.name.toString())) {
          reloadTimer.value = window.setInterval(
            () => {
              if (!loginStore.showLogin) {
                return;
              }
              window.location.reload();
            },
            3 * 60 * 1e3
          );
        }
      });
    }
    vue.onMounted(() => {
      isSSRShowDialog.value = true;
      if (loginStore.showLogin) {
        handleLogin();
      }
      window.addEventListener("message", async (e) => {
        if (e.data.type == "giikin-Logged") {
          const data = e.data;
          console.log(e.data);
          const token = Cookies.get("token");
          const isProduction = importMetaEnv.value.MODE.includes("production");
          if (
            // 测试环境  但是需要登陆的情况
            !isProduction && data?.data?.token || // 正式环境 登录成功  但是服务器token设置失败
            isProduction && !token && data?.data?.token
          ) {
            loginStore.userId = data.data.userId;
            const now = /* @__PURE__ */ new Date();
            let time = now.getTime();
            time += 8 * 60 * 60 * 1e3;
            now.setTime(time);
            const curDomain = url.getDomain();
            if (!data.data.disabledWrite) {
              if (data.cookies && Array.isArray(data.cookies)) {
                data.cookies.forEach((cookie) => {
                  document.cookie = cookie;
                });
              }
              Cookies.set("token", data.data.token, { expires: now, domain: isProduction ? curDomain : void 0 });
              if (importMetaEnv.value.DEV && data.data.tokens) {
                data.data.tokens.forEach((token2) => {
                  Cookies.set(token2.key, token2.value, { expires: now, domain: curDomain });
                });
              }
              if (!Cookies.get("sso_user_id") && data.data.userId) {
                Cookies.set("sso_user_id", data.data.userId, {
                  expires: now,
                  domain: isProduction ? curDomain : void 0
                });
              }
            }
          }
          if (!data.data.disabledClose) {
            if (data?.data?.token || data?.data?.loginSuccess) {
              await loginStore.triggerLoginResult(true);
            }
            loginStore.showLogin = false;
            if (route.value && props.needRealodRouteNames.includes(route.value.name?.toString() ?? "")) {
              window.location.reload();
            }
          }
        }
      });
    });
    vue.onUnmounted(() => {
      window.clearInterval(reloadTimer.value);
    });
    return (_ctx, _cache) => {
      return isSSRShowDialog.value ? (vue.openBlock(), vue.createElementBlock("div", _hoisted_1, [
        vue.createVNode(vue.unref(elementPlus.ElDialog), {
          modelValue: vue.unref(loginStore).showLogin,
          "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => vue.unref(loginStore).showLogin = $event),
          width: "80%",
          "append-to-body": ""
        }, {
          default: vue.withCtx(() => [
            vue.createCommentVNode(" \u6B63\u5E38\u767B\u5F55\u72B6\u6001\uFF1A\u663E\u793Aiframe "),
            vue.unref(loginStore).showLogin && !vue.unref(loginStore).isLoginBlocked ? (vue.openBlock(), vue.createElementBlock("iframe", {
              key: 0,
              class: "gm-h-[600px] gm-w-full",
              src: loginUrl.value
            }, null, 8, _hoisted_2)) : vue.unref(loginStore).isLoginBlocked ? (vue.openBlock(), vue.createElementBlock(
              vue.Fragment,
              { key: 1 },
              [
                vue.createCommentVNode(" \u5F02\u5E38\u72B6\u6001\uFF1A\u663E\u793A\u9519\u8BEF\u63D0\u793A "),
                vue.createElementVNode("div", {
                  class: "gm-py-10",
                  src: loginUrl.value
                }, [
                  vue.createVNode(vue.unref(elementPlus.ElResult), {
                    icon: "warning",
                    title: "\u767B\u5F55\u5F02\u5E38",
                    "sub-title": "\u77ED\u65F6\u95F4\u5185\u591A\u6B21\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"
                  }, {
                    extra: vue.withCtx(() => [
                      vue.createVNode(vue.unref(elementPlus.ElButton), {
                        type: "primary",
                        onClick: handleRetryLogin
                      }, {
                        default: vue.withCtx(() => [
                          vue.createTextVNode("\u91CD\u65B0\u767B\u5F55")
                        ]),
                        _: 1
                        /* STABLE */
                      }),
                      vue.createVNode(vue.unref(elementPlus.ElButton), {
                        type: "warning",
                        onClick: handleClearCache
                      }, {
                        default: vue.withCtx(() => [
                          vue.createTextVNode("\u6E05\u7A7A\u7F13\u5B58")
                        ]),
                        _: 1
                        /* STABLE */
                      }),
                      vue.createVNode(vue.unref(elementPlus.ElButton), {
                        onClick: _cache[0] || (_cache[0] = ($event) => vue.unref(loginStore).showLogin = false)
                      }, {
                        default: vue.withCtx(() => [
                          vue.createTextVNode("\u5173\u95ED")
                        ]),
                        _: 1
                        /* STABLE */
                      })
                    ]),
                    _: 1
                    /* STABLE */
                  })
                ], 8, _hoisted_3)
              ],
              2112
              /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */
            )) : vue.createCommentVNode("v-if", true)
          ]),
          _: 1
          /* STABLE */
        }, 8, ["modelValue"])
      ])) : vue.createCommentVNode("v-if", true);
    };
  }
});

exports.default = _sfc_main;
//# sourceMappingURL=LoginDialog.vue2.js.map
