<template>
  <ServicesModal ref="serviceModalRef" />
</template>

<script lang="ts">
  import ServicesModal from '@/views/serverSelect/modal.vue';
  import { ref } from 'vue';
  import { ResultEnum } from '@/enums/httpEnum';
  import { useMessage } from 'naive-ui';
  import { useUserStore } from '@/store/modules/user';
  import { useRouter } from 'vue-router';

  export default {
    components: { ServicesModal },

    setup() {
      return {
        serviceModalRef: ref(),
        message: useMessage(),
        userStore: useUserStore(),
        router: useRouter(),
      };
    },
    created() {
      this.handleAuthCallback();
    },
    methods: {
      openModal() {
        const { openDrawer } = this.serviceModalRef;
        openDrawer();
      },

      async handleAuthCallback() {
        const params = new URLSearchParams(window.location.search);
        // 获取 access-token 的值
        const fsCode = params.get('code');

        console.log('fsCode:' + fsCode);
        if (fsCode) {
          try {
            const { code, msg } = await this.userStore.feishuLogin({ code: fsCode });
            if (code == ResultEnum.SUCCESS) {
              this.message.success('登录成功，即将进入系统');
              // this.openModal();
              await this.router.push('/selectSystem');
            } else {
              if (code === 9999) {
                this.message.info(msg);
                await this.router.push('/login');
              }
              this.message.info(msg || '登录失败1');
            }
          } catch (error) {
            console.error('登录失败:', error);
            this.message.info('登录失败2');
          }
        } else {
          this.message.info('取消授权');
        }
      },
    },
  };
</script>
