import { defineComponent, computed, unref, ref, watch, onMounted, onUnmounted, createElementBlock, createCommentVNode, openBlock, createVNode, withCtx, Fragment, createElementVNode, createTextVNode } from 'vue';
import { ElMessage, ElDialog, ElResult, ElButton } from 'element-plus';
import Cookies from 'js-cookie';
import '../../../../hooks/index.mjs';
import { useGlobalConfig } from '../../../../hooks/base/useGlobalConfig/index.mjs';
import '../../../../utils/index.mjs';
import { urlJoin, getDomain } from '../../../../utils/src/http/url.mjs';
import { isGiikin } from '../../../../utils/src/tenant.mjs';
import { envConfigs } from '../../../../utils/src/http/createModes.mjs';
import { loginDialogProps } from './loginDialog.mjs';
import { resetEnvMode } from '../../../../constants/key.mjs';
import { useLoginStore } from '../../../../hooks/store/useLogin/index.mjs';
import { isString, isMobile, isDingTalk } from '../../../../utils/src/is.mjs';

const _hoisted_1 = { key: 0 };
const _hoisted_2 = ["src"];
const _hoisted_3 = ["src"];
const loginEnvKey = "VITE_GIIME_LOGIN_URL";
var _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "LoginDialog",
  props: loginDialogProps,
  setup(__props) {
    const props = __props;
    const router = useGlobalConfig("router");
    const route = computed(() => router.value ? unref(router.value.currentRoute) : void 0);
    const loginStore = useLoginStore();
    const loginUrl = ref("");
    const importMetaEnv = useGlobalConfig("env");
    const isSSRShowDialog = ref(importMetaEnv.value.SSR === false);
    let originLoginUrl = "";
    if (isString(importMetaEnv.value[loginEnvKey])) {
      originLoginUrl = importMetaEnv.value[loginEnvKey];
    } else {
      const loginPath = isGiikin() ? "/guard/sso/public/auth" : "/fe/basic/login";
      const resetMode = importMetaEnv.value[resetEnvMode];
      const hostname = window.location.hostname;
      const findEnvConfig = Object.values(envConfigs).find((config) => config.domain === hostname);
      if (resetMode && envConfigs[resetMode]) {
        originLoginUrl = urlJoin(envConfigs[resetMode].url, loginPath);
      } else if (findEnvConfig) {
        originLoginUrl = urlJoin(findEnvConfig.url, loginPath);
      } else if (importMetaEnv.value.DEV) {
        originLoginUrl = urlJoin(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 (isMobile() || isDingTalk()) {
        window.location.href = loginUrl.value;
      }
    };
    const handleRetryLogin = () => {
      loginStore.resetLoginBlock();
      handleLogin();
    };
    const handleClearCache = () => {
      const cookies = document.cookie.split(";");
      const curDomain = 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}` });
        }
      });
      ElMessage.success("\u6E05\u9664cookie\u7F13\u5B58\u6210\u529F");
    };
    watch(
      () => loginStore.showLogin,
      (value) => {
        if (value) {
          handleLogin();
        }
      }
    );
    const reloadTimer = ref();
    if (route.value) {
      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
          );
        }
      });
    }
    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 = 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();
            }
          }
        }
      });
    });
    onUnmounted(() => {
      window.clearInterval(reloadTimer.value);
    });
    return (_ctx, _cache) => {
      return isSSRShowDialog.value ? (openBlock(), createElementBlock("div", _hoisted_1, [
        createVNode(unref(ElDialog), {
          modelValue: unref(loginStore).showLogin,
          "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => unref(loginStore).showLogin = $event),
          width: "80%",
          "append-to-body": ""
        }, {
          default: withCtx(() => [
            createCommentVNode(" \u6B63\u5E38\u767B\u5F55\u72B6\u6001\uFF1A\u663E\u793Aiframe "),
            unref(loginStore).showLogin && !unref(loginStore).isLoginBlocked ? (openBlock(), createElementBlock("iframe", {
              key: 0,
              class: "gm-h-[600px] gm-w-full",
              src: loginUrl.value
            }, null, 8, _hoisted_2)) : unref(loginStore).isLoginBlocked ? (openBlock(), createElementBlock(
              Fragment,
              { key: 1 },
              [
                createCommentVNode(" \u5F02\u5E38\u72B6\u6001\uFF1A\u663E\u793A\u9519\u8BEF\u63D0\u793A "),
                createElementVNode("div", {
                  class: "gm-py-10",
                  src: loginUrl.value
                }, [
                  createVNode(unref(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: withCtx(() => [
                      createVNode(unref(ElButton), {
                        type: "primary",
                        onClick: handleRetryLogin
                      }, {
                        default: withCtx(() => [
                          createTextVNode("\u91CD\u65B0\u767B\u5F55")
                        ]),
                        _: 1
                        /* STABLE */
                      }),
                      createVNode(unref(ElButton), {
                        type: "warning",
                        onClick: handleClearCache
                      }, {
                        default: withCtx(() => [
                          createTextVNode("\u6E05\u7A7A\u7F13\u5B58")
                        ]),
                        _: 1
                        /* STABLE */
                      }),
                      createVNode(unref(ElButton), {
                        onClick: _cache[0] || (_cache[0] = ($event) => unref(loginStore).showLogin = false)
                      }, {
                        default: withCtx(() => [
                          createTextVNode("\u5173\u95ED")
                        ]),
                        _: 1
                        /* STABLE */
                      })
                    ]),
                    _: 1
                    /* STABLE */
                  })
                ], 8, _hoisted_3)
              ],
              2112
              /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */
            )) : createCommentVNode("v-if", true)
          ]),
          _: 1
          /* STABLE */
        }, 8, ["modelValue"])
      ])) : createCommentVNode("v-if", true);
    };
  }
});

export { _sfc_main as default };
//# sourceMappingURL=LoginDialog.vue2.mjs.map
