<template>
  <van-loading v-show="loading"/>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { callback, getInfo } from '@/api/login';
import { setToken, getToken } from '@/utils/auth';
import useUserStore from "@/store/modules/user";

const route = useRoute();
const router = useRouter();
const useUser = useUserStore();
const loading = ref(true);

const do_callback = () => {
  const code = route.query.code as string;
  const state = route.query.state as string;
  callback({code, state}).then((res)=>{
      loading.value = false;
      var access_token = res.data.access_token;
      var redirect_url = res.data.redirect_url;
      setToken(access_token);
      
      console.log('redirect_url:', redirect_url);
      setTimeout(function() {
        getUserInfo(redirect_url)
      }, 500);
  })
}

const getUserInfo = (redirect_url) => {
  getInfo().then((res)=>{
    const roles = res.data.roles;
    console.log('roles', roles);
    if(roles.includes("superadmin")) {
      useUser.setRoles("leader");
    }
    if(roles.includes("super_ld")) {
      useUser.setRoles("leader");
    }
    if(roles.includes("super_worker")) {
      useUser.setRoles("worker");
    }
    
    router.push(redirect_url);
  })
};

onMounted(() => {
  nextTick(() => {
    do_callback();
  });
});
</script>
