<template>
  <div> </div>
</template>

<script lang="ts" setup>
  import { isOAuth2AppEnv, sysOAuth2Callback, sysOAuth2Login } from '@/views/account/login/useLogin';
  import { useRouter } from 'vue-router';
  import { PageEnum } from '@/enums/pageEnum';
  import { router } from '@/router';
  import { useUserStore } from '@/store/modules/user';
  import { useMessage } from '@/hooks/web/useMessage';
  <%_ if (enableTranslation) { _%>
  import { useI18n } from '@/hooks/web/useI18n';
  <%_ } _%>
  import { getAuthCache, getTenantId, getToken } from '@/utils/auth';
  import { requestAuthCode } from 'dingtalk-jsapi';
  import { defHttp } from '/@/utils/http/axios';
  import { OAUTH2_THIRD_LOGIN_TENANT_ID } from "/@/enums/cacheEnum";
  <%_ if (authenticationTypeOauth2) { _%>
  import accountService from '@/api-service/account/account.service';
  import { RoleEnum } from '@/enums/roleEnum';
  <%_ } _%>

  const isOAuth = ref<boolean>(isOAuth2AppEnv());
  const env = ref<any>({ thirdApp: false, wxWork: false, dingtalk: false });
  const { currentRoute } = useRouter();
  const route = currentRoute.value;
  if (!isOAuth2AppEnv()) {
    router.replace({ path: PageEnum.BASE_LOGIN, query: route.query });
  }

  if (isOAuth.value) {
    checkEnv();
  }

  /**
   * 检测当前的环境
   */
  function checkEnv() {
    env.value.thirdApp = true;
    // 判断当时是否是企业微信环境
    if (/wxwork/i.test(navigator.userAgent)) {
      env.value.wxWork = true;
    }
    // 判断当时是否是钉钉环境
    if (/dingtalk/i.test(navigator.userAgent)) {
      env.value.dingtalk = true;
    }
    doOAuth2Login();
  }

  /**
   * 进行OAuth2登录操作
   */
  function doOAuth2Login() {
    if (env.value.thirdApp) {
      // 判断是否携带了Token，是就说明登录成功
      if (route.query.oauth2LoginToken) {
        let token = route.query.oauth2LoginToken;
        // 执行登录操作
        thirdLogin({ token, thirdType: route.query.thirdType, tenantId: getTenantId });
      } else if (env.value.wxWork) {
        sysOAuth2Login('wechat_enterprise');
      } else if (env.value.dingtalk) {
        // 新版钉钉登录
        dingdingLogin();
      <%_ if (authenticationTypeOauth2) { _%>
      } else {
      // 获取用户信息，如果成功，刚跳转到产页，否则跳转到登录页
      const userStore = useUserStore();
      accountService.getAccount().then(user => {
        if (user) {
          const roles = user.authorities || [];
          if (_isArray(roles)) {
            const roleList = roles.map(item => item.code) as RoleEnum[];
            userStore.setRoleList(roleList);
          } else {
            user.authorities = [];
            userStore.setRoleList([]);
          }
          userStore.setToken(user.login)
          userStore.setUserInfo(user);
          window.location.href = "/"
        }
      }).catch(err =>
      {
        console.log('err', err)
      })
      window.location.href = '/oauth2/authorization/oidc'
      <%_ } _%>
      }
    }
  }

  /**
   * 第三方登录
   * @param params
   */
  function thirdLogin(params) {
    const userStore = useUserStore();
    const { notification } = useMessage();
    <%_ if (enableTranslation) { _%>
    const { t } = useI18n();
    <%_ } _%>
    userStore.ThirdLogin(params).then(res => {
      if (res && res.userInfo) {
        notification.success({
          message: <% if (enableTranslation) { %>t('sys.login.loginSuccessTitle')<% } else { %>'t$t('sys.login.loginSuccessTitle')$t$'<% } %>,
          description: `<% if (enableTranslation) { %>${t('sys.login.loginSuccessDesc')}<% } else { %>t$t('sys.login.loginSuccessDesc')$t$<% } %>: ${res.userInfo.realname}`,
          duration: 3,
        });
      } else {
        notification.error({
          message: <% if (enableTranslation) { %>t('sys.login.errorTip')<% } else { %>'t$t('sys.login.errorTip')$t$'<% } %>,
          description: ((res.response || {}).data || {}).message || res.message || <% if (enableTranslation) { %>t('sys.login.networkExceptionMsg')<% } else { %>'t$t('sys.login.networkExceptionMsg')$t$'<% } %>,
          duration: 4,
        });
      }
    });
  }

  /**
   * 钉钉登录
   */
  function dingdingLogin() {
    // 先获取钉钉的企业id，如果没有配置 还是走原来的逻辑，走原来的逻辑 需要判断存不存在token，存在token直接去首页
    let tenantId = getAuthCache(OAUTH2_THIRD_LOGIN_TENANT_ID) || 0;
    let url = `/sys/thirdLogin/get/corpId/clientId?tenantId=${tenantId}`;
    defHttp.get({ url:url },{ isTransformResponse: false }).then((res) => {
        if (res.success) {
          if(res.result && res.result.corpId && res.result.clientId){
            requestAuthCode({ corpId: res.result.corpId, clientId: res.result.clientId }).then((res) => {
              let { code } = res;
              sysOAuth2Callback(code);
            });
          }else{
            toOldAuthLogin();
          }
        } else {
          toOldAuthLogin();
        }
      }).catch((err) => {
        toOldAuthLogin();
      });
  }

  /**
   * 旧版钉钉登录
   */
  function toOldAuthLogin() {
    let token = getToken();
    if (token) {
      router.replace({ path: PageEnum.BASE_HOME });
    } else {
      sysOAuth2Login('dingtalk');
    }
  }
</script>
