<script setup lang="ts">
import { useUserStoreWithOut, UserInterface } from "@/stores/modules/user"
import { getAuthCode } from 'dingtalk-jsapi'; 
import reqest from "@/utils/request";

const userStore = useUserStoreWithOut();
const initUserInfoHandler = async () => {
    const code: string = await getDDAuthCode() as string
    const userIdResult = await getUserIdByDD({code})
    if (userIdResult && userIdResult?.data) {
        const userResult = await getUserInfoById(userIdResult?.data.accessToken)
        if (userResult && userResult?.data) { 
            const userInfo: UserInterface = {
                id: userResult?.data.user.id,
                nickname: userResult?.data.user.nickname,
                accessToken: userIdResult?.data.accessToken,
            }
            userStore.setUser(userInfo)
            localStorage.setItem("ACCESS_TOKEN", userIdResult?.data.accessToken)
          localStorage.setItem("_userInfo", JSON.stringify(userInfo))
            console.log(localStorage.getItem("ACCESS_TOKEN"))
        }
    }
}
initUserInfoHandler()
function getDDAuthCode() {
    return new Promise((resolve, reject) => {
        getAuthCode({
            corpId: 'ding65143abf9aeea2ec',
            success: (res: any) => {
                const { code } = res;
                if (code) {
                    resolve(code);
                }
            },
            fail: (ex: any) => {
                reject(ex);
            },
            complete: () => {},
        });
    });
}
interface UserIdParam {
    code: string
}
const getUserIdByDD = async (data: Required<UserIdParam>) => {
  return reqest.post(`/app-api/system/auth/login-ding?code=${data.code}`, null)
}
//@ts-ignore
const getUserInfoById = async (token: Required<string>) => {
    return reqest.get('/admin-api/system/auth/get-permission-info', {
        headers: { 'Authorization': 'Bearer ' + token }
  })
}
</script>

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

<style scoped>
</style>
