<template>
  <div :class="prefixCls" v-if="!ssoConfig.enabled" class="login-box relative w-full h-full">
    <div class="login-left-box">
      <div class="logo-box" v-if="show">
        <a href="https://www.learun.cn/" target="_blank">
          <img :src="logoConfig.loginLogoUrl || logopng" />
        </a>
      </div>
      <img :src="logoConfig.backgroundLogoUrl || logobg" class="h-full" />
    </div>
    <div class="fixed-tool">
      <AppDarkModeToggle v-if="!sessionTimeout" />
      <AppLocalePicker
        class="text-white px-4"
        :showText="false"
        v-if="!sessionTimeout && showLocale"
      />
    </div>
    <div class="right-box">
      <div class="login-left-title">
        <div class="title">{{ t('欢迎登录') }}</div>
        <div class="sub-title">{{ t('力软低代码开发平台') }}</div>
      </div>
      <div :class="`${prefixCls}-form`">
        <LoginForm />
      </div>
    </div>
    <div class="right-top-box">
      <img src="../../../assets/images/login-right.gif" />
    </div>
    <div class="copyright">Copyright © 和利时科技集团有限公司<br /></div>
  </div>
</template>
<script lang="ts" setup>
  // import { computed } from 'vue';
  import { AppLocalePicker, AppDarkModeToggle } from '/@/components/Application';
  import LoginForm from './LoginForm.vue';
  // import { useGlobSetting } from '/@/hooks/setting';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useLocaleStore } from '/@/store/modules/locale';
  import { useAppStore } from '/@/store/modules/app';
  import logopng from '/@/assets/images/hls_logo.png';
  import logobg from '/@/assets/images/login-left.png';
  import { getLogoInfo } from '/@/api/system/login';
  import { onMounted, ref } from 'vue';
  import { LogoConfig } from '/#/config';
  import { useRouter } from 'vue-router';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { ssoConfig } from '/@/settings/ssoSetting';
  import { getFileUrl } from '/@/utils/event/design';

  const appStore = useAppStore();
  defineProps({
    sessionTimeout: {
      type: Boolean,
    },
  });

  // const globSetting = useGlobSetting();
  const { prefixCls } = useDesign('login');
  const { t } = useI18n();
  const localeStore = useLocaleStore();
  const showLocale = localeStore.getShowPicker;
  const { notification } = useMessage();
  const userStore = useUserStore();
  // const title = computed(() => globSetting?.title ?? '');

  let logoConfig = ref<LogoConfig>({});
  let show = ref(false);
  getLogoInfo().then((res) => {
    show.value = true;
    logoConfig.value = {
      companyName: res.companyName,
      shortName: res.shortName,
      refreshLogoUrl: getFileUrl(res, 'refreshLogoUrl'),
      backgroundLogoUrl: getFileUrl(res, 'backgroundLogoUrl'),
      designerLogoUrl: getFileUrl(res, 'designerLogoUrl'),
      loginLogoUrl: getFileUrl(res, 'loginLogoUrl'),
      menuLogoUrl: getFileUrl(res, 'menuLogoUrl'),
      systemName: res.systemName,
      smallMenuLogoUrl: getFileUrl(res, 'smallMenuLogoUrl'),
    };
    appStore.setLogoConfig(logoConfig.value);
  });

  onMounted(async () => {
    if (ssoConfig.enabled) {
      if (!location.href.includes('sso-callback')) {
        const initOptions = ssoConfig;
        const { currentRoute } = useRouter();

        if (currentRoute.value.query.code || location.href.includes('code')) {
          const code = location.href.split('code=')[1].split('#/')[0];

          const accessTokenUrl = `${initOptions.server}/oauth2/token?grant_type=authorization_code&client_id=${initOptions.clientId}&client_secret=${initOptions.clientSecret}&code=${code}`;

          const responseStream = await fetch(accessTokenUrl, {
            method: 'POST', // 指定请求方法
            headers: {
              'Content-Type': 'application/json', // 声明发送 JSON 格式
            },
          });
          const accessData = await responseStream.json();

          if (accessData.code !== 200) {
            throw new Error('获取access_token失败');
          }
          const userInfo = await userStore.ssoLogin({
            token: accessData.access_token as string,
            mode: 'none', //不要默认的错误提示
          });
          if (userInfo) {
            notification.success({
              message: t('登录成功'),
              description: `${t('欢迎回来')}: ${userInfo.name}`,
              duration: 3,
            });
          }
        } else {
          const authCodeUrl = `${initOptions.serverAuth}/oauth2/authorize?response_type=code&client_id=${initOptions.clientId}&redirect_uri=http://192.168.0.139:3100&scope=${initOptions.scope}`;
          console.log('authCodeUrl:', authCodeUrl);
          location.href = authCodeUrl;
        }
      }
    }
  });
</script>
<style lang="less">
  @prefix-cls: ~'@{namespace}-login';
  @logo-prefix-cls: ~'@{namespace}-app-logo';
  @countdown-prefix-cls: ~'@{namespace}-countdown-input';
  @dark-bg: linear-gradient(to bottom, #364876, #112049);

  .vben-login-form {
    padding: 180px 100px 40px;
  }

  .login-box {
    display: flex;
  }

  .logo-box {
    position: fixed;
    top: 50px;
    left: 40px;
  }

  .logo-box img {
    width: 130px;
  }

  .login-left-title {
    position: relative;
    top: 120px;
    left: 100px;
  }

  .login-left-title .title {
    color: #333;
    font-size: 20px;
    border: none;
    margin-bottom: 10px;
  }

  .login-left-title .sub-title {
    font-size: 36px;
    font-weight: bold;
    color: @primary-color;
  }

  .login-box .right-box {
    position: absolute;
    right: 0;
    bottom: 2%;
  }

  .fixed-tool {
    position: fixed;
    right: 20px;
    top: 40px;
    display: flex;
    z-index: 2;
  }

  .right-top-box {
    width: 400px;
    position: fixed;
    right: 0;
    top: 0;
  }

  html[data-theme='dark'] {
    .login-box {
      background: @dark-bg;
    }

    .login-left-title {
      border: none;
    }

    .login-left-title .title {
      color: #fff;
    }

    .@{prefix-cls} {
      background-color: @dark-bg;

      // &::before {
      //   background-image: url(/@/assets/svg/login-bg-dark.svg);
      // }

      .ant-input,
      .ant-input-password {
        background-color: #232a3b;
      }

      .ant-input-affix-wrapper {
        border-color: #525e7c;
        background-color: #232a3b;
      }

      .ant-checkbox-inner {
        border-color: #525e7c;
      }

      .ant-btn:not(.ant-btn-link, .ant-btn-primary) {
        border: 1px solid #4a5569;
      }

      &-form {
        background: transparent !important;
      }

      .app-iconify {
        color: #fff;
      }
    }

    input.fix-auto-fill,
    .fix-auto-fill input {
      -webkit-text-fill-color: #c9d1d9 !important;
      box-shadow: inherit !important;
    }
  }

  .@{prefix-cls} {
    min-height: 100%;
    overflow: hidden;
    @media (max-width: @screen-xl) {
      background-color: @dark-bg;

      .@{prefix-cls}-form {
        background-color: #fff;
      }
    }

    &::before {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      margin-left: -48%;
      // background-image: url(/@/assets/svg/login-bg.svg);
      background-position: 100%;
      background-repeat: no-repeat;
      background-size: auto 100%;
      content: '';
      @media (max-width: @screen-xl) {
        display: none;
      }
    }

    .@{logo-prefix-cls} {
      position: absolute;
      top: 12px;
      height: 30px;

      &__title {
        font-size: 16px;
        color: #fff;
      }

      img {
        width: 32px;
      }
    }

    .container {
      .@{logo-prefix-cls} {
        display: flex;
        width: 60%;
        height: 80px;

        &__title {
          font-size: 24px;
          color: #fff;
        }

        img {
          width: 48px;
        }
      }
    }

    &-sign-in-way {
      .anticon {
        font-size: 22px;
        color: #888;
        cursor: pointer;

        &:hover {
          color: @primary-color;
        }
      }
    }

    input:not([type='checkbox']) {
      min-width: 360px;

      @media (max-width: @screen-xl) {
        min-width: 320px;
      }

      @media (max-width: @screen-lg) {
        min-width: 260px;
      }

      @media (max-width: @screen-md) {
        min-width: 240px;
      }

      @media (max-width: @screen-sm) {
        min-width: 160px;
      }
    }

    .@{countdown-prefix-cls} input {
      min-width: unset;
    }

    .ant-divider-inner-text {
      font-size: 12px;
      color: @text-color-secondary;
    }
  }

  .copyright {
    position: fixed;
    bottom: 10px;
    left: 0;
    right: 0;
    text-align: center;
    align-items: center;
    color: #fff;
  }
</style>
