<script setup lang="ts">
import { useRoute } from 'vue-router';
import { getBindUserInfo } from '@/api/user';
import AuthBind from '@/components/LoginModal/auth.vue';
import { computed, reactive, ref, onMounted } from 'vue';
import { useAccount } from '@/utils/hooks/useAccount';
import isPhone from '@/utils/isPhone';
import router from '@/router';
import { Message } from 'vue-devui/message';
import { emitEvent } from '@/utils/eventBus';
import { useReport } from '@/utils/hooks/useReport';
const route = useRoute();

const { RecordInfo } = useAccount();

const isAttached = ref(true);

const isMobile = computed(() => isPhone());

const formData = reactive({
  mask: '',
  user_id: '',
  mobile: '',
  identity_id: '',
  platform: ''
});

const automgitPath = '/setting/pipeline';

onMounted(async() => {
  const { type = 'atomgit', code, state, error, installation_id } = route.query;
  formData.platform = type as string;
  if (error && !code) { // github | gitee 用户取消授权
    emitEvents('fail', '你已取消授权');
    return;
  }
  const excRes = /(.*)_(.*)/.exec(state as string);
  if (excRes) {
    if (window.parent) {
      // window.opener?.postMessage({ fn: 'otho', type, code, state: excRes[1] }, (import.meta as any).env.VITE_HOST);
      window.opener?.postMessage({ fn: 'otho', type, code, state: excRes[1] }, window.location.origin + '/openRepoPortal');
      window?.close();
    }
    return;
  }

  const fromAtomGit = installation_id && /atomgit.com/.test(document.referrer); // 来自AtomGit应用的跳转
  const bindType = fromAtomGit ? 'atomgit' : type;
  const bindState = fromAtomGit ? 'atomgit' : state;
  if ((code && state) || fromAtomGit) {
    const signup_type = localStorage.getItem('cache_timeStamp') && localStorage.getItem('utm_source') ? '博客加速' : (sessionStorage.getItem('loginType') || '');
    const res = await getBindUserInfo(bindType as unknown as any, code as string, bindState as string, signup_type as string) as any;
    if (!res.error) {
      if (localStorage.getItem('op_access_token') && fromAtomGit) {
        emitEvents('success', '', automgitPath);
        return;
      }
      const { bind_status_enum, mask, mobile, user_id, user_login_resp, identity_id } = res.data.data;
      formData.mask = mask || '';
      formData.user_id = user_id || '';
      formData.mobile = mobile || '';
      formData.identity_id = identity_id || '';
      if (!mobile) {
        isAttached.value = false;
        // 如果查不出来手机号必须绑定完成才算完成流程 不管bind_status_enum是否为SUCCESS gitee ｜ github | atomgit
        // 如果未绑定手机号user_login_resp必为null
      }
      if (bind_status_enum === 'SUCCESS') {
        handleSubmit(user_login_resp);
      }
    } else {
      !fromAtomGit && emitEvents('fail', res.error.error_message);
    }
  }
});
/** 绑定手机号 */
const handleConfirm = (config: Record<string, any>) => {
  const { mobile } = config;
  formData.mobile = mobile;
  isAttached.value = true;
  handleSubmit(config);
};
/** 取消绑定 */
const handleCancel = () => {
  if (isMobile.value) {
    router.replace('/');
  } else {
    window?.close();
  }
};
/** 发送事件 */
const emitEvents = (type: 'success' | 'fail' = 'success', error_info?: string, path?: string) => {
  const url = localStorage.getItem('loginReturnUrl');
  if (isMobile.value || route.query?.installation_id) {
    if (type === 'success') {
      // 登录后回到登录前页面 hack一下automgit跳转
      if (route.query?.installation_id) {
        // window.location.href = `${(import.meta as any).env.VITE_HOST}${path || '/'}`;
        window.location.href = `${window.location.origin}/SAP${path || '/'}`;
      } else {
        url && localStorage.removeItem('loginReturnUrl');
        url ? window.location.href = url : router.replace('/');
      }
      // Message.success({
      //   message: '欢迎来到GitCode!',
      //   onClose: () => {
      //     emitEvent('notice');
      //   }
      // });
    } else {
      router.replace('/login');
      Message.warning(error_info || '授权失败');
    }
  } else {
    if (url) {
      localStorage.removeItem('loginReturnUrl');
      window.location.href = url;
    } else if (window.parent) {
      window.opener?.postMessage({
        type,
        message: error_info || type === 'success' ? '' : '你已取消授权',
        path
      // }, (import.meta as any).env.VITE_HOST);
      }, window.location.origin + '/SAP');
      window?.close();
    }
  }
};

const handleSubmit = (conf: any) => {
  if (conf) {
    const { username, email } = conf;
    RecordInfo(conf, isMobile.value);
    if (`${username}@gitcode.com` === email) { // 需要修改默认的弹窗
      localStorage.setItem('validator_email', 'invalid');
    } else {
      localStorage.setItem('validator_email', 'valid');
    }
    emitEvents('success', '', route.query?.installation_id ? automgitPath : '');
  }
};

</script>

<template>
  <div :class="[isMobile ? 'oauth-container-mobile' : 'oauth-container']">
    <div :class="[isMobile ? 'mt-[100px]' : '', 'text-CG600 text-[16px] text-center']" v-if="isAttached">正在查询授权结果, 稍等片刻 ...</div>
    <div :class="[isMobile ? 'oauth-mobile-form' : 'g-content-card', 'oauth-container-form']" v-else>
      <AuthBind v-bind="formData" @cancel="handleCancel" @confirm="handleConfirm" />
    </div>
  </div>
</template>

<style lang="scss">
.oauth-container {
  @apply flex flex-col items-center justify-center m-auto overflow-hidden w-[410px] mt-[64px];
}
.oauth-container-mobile {
  @apply h-[100%] bg-white box-border p-[8px] m-auto
        sm:w-[414px] w-[100%];
}
.oauth-container-form {
  @apply pt-[22px] p-[24px] w-[100%] m-auto;
}
</style>
