<template>
    <el-main></el-main>
</template>
<script setup lang="ts">
//useRouter
import { useRoute, useRouter } from "vue-router";
import { getOrgsApi, getWarehousesListApi } from "@/api/modules/global";
// import { useMsg } from "@/hooks/useMsg";
//重定向
import { usePathUrl } from "@/hooks/usePathUrl";
//登录请求接口
import { loginApi } from "@/api/modules/login";

//用户信息存储
import { useUserStore } from "@/stores/modules/user";

const userStore = useUserStore();
//路由;
const $route = useRoute();
const $router = useRouter();

//获取组织
const getOrgs = async () => {
    const result = await getOrgsApi();
    if (result?.code === 0) {
        const { data } = result;
        if (data?.length) {
            let options: any = [];
            data.forEach((item: any) => {
                options.push({
                    id: item.id,
                    value: item.org_number,
                    label: item.org_name
                });
            });
            userStore.setOrgIdArr(options);
        }
    }
};

const getWarehousesList = async () => {
    const result = await getWarehousesListApi();
    if (result?.code === 0) {
        const { data } = result;
        if (data?.length) {
            let options: any = [];
            data.forEach((item: any) => {
                options.push({
                    id: item.id,
                    value: item.warehouse_name,
                    label: item.warehouse_name
                });
            });
            userStore.setWarehouse(options);
        }
    }
};

// 登录
const loginHttp = async (code: any) => {
    const result: Record<string, any> = await loginApi(code);
    if (result.code === 0) {
        userStore.setToken(result?.data?.access_token);
        // 设置用户信息
        userStore.setUserInfo(result?.data?.user_data);

        let redirect_path: any = $route.query.redirect_path;

        if (result?.data?.access_token) {
            getWarehousesList();
            getOrgs();
        }
        if (redirect_path) {
            setTimeout(() => {
                $router.replace({ path: redirect_path });
            }, 500);
        } else {
            setTimeout(() => {
                $router.replace({ path: "/" });
            }, 500);
        }
    } else {
        location.href = usePathUrl();
    }
};

// 登录前的判断
const login = () => {
    const { code, redirect_path } = $route.query;
    // 没有code直接跳转到登录页
    if (!code && redirect_path) {
        location.href = usePathUrl(redirect_path);
        return;
    }
    if (!code) {
        location.href = usePathUrl();
        return;
    }
    // 有code就登录请求
    if (code) {
        loginHttp(code);
    }
};
login();
</script>
<style lang="scss">
.el-main {
    height: 100vh;
}
</style>
