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

<script setup>
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { SET_TOKEN,SET_USER_ROLES,SET_USER_CUR_ROLE } from "@/store/modules/app/type";
import { onMounted } from "vue";

const router = useRouter();
const route = useRoute();
const store = useStore();

let userId = route.query.userId;

onMounted(async () => {
    await getFarmList();
    const token = route.query.token
    const targetUrl = route.query.targetUrl ? route.query.targetUrl : '/home';
    if (!token) {
        const { data } = await VE_API.system.devLogin({ userId: userId });
        store.dispatch(`app/${SET_TOKEN}`, data.token);
        store.dispatch(`app/${SET_USER_ROLES}`, data.roles);
        // 如果 roles 中包含 2，赋值 2，否则赋值 0
        const curRole = Array.isArray(data.roles) && data.roles.includes(2) ? 2 : 0;
        store.dispatch(`app/${SET_USER_CUR_ROLE}`, curRole);
        localStorage.setItem("localUserInfo", JSON.stringify(data));
    }
    // 存userId
    let pointXy = route.query.point.split(",")
    // 刷新后仍保留id和point
    localStorage.setItem("MINI_USER_ID", userId)
    route.query?.userInfo && localStorage.setItem("localUserInfo", route.query.userInfo);
    if(route.query.roles){
        const roles = JSON.parse(route.query.roles);
        store.dispatch(`app/${SET_USER_ROLES}`, roles);
        // 如果 roles 中包含 2，赋值 2，否则赋值 0
        const curRole = Array.isArray(roles) && roles.includes(2) ? 2 : 0;
        store.dispatch(`app/${SET_USER_CUR_ROLE}`, curRole);
    }
    localStorage.setItem("MINI_USER_LOCATION", route.query.point)
    localStorage.setItem("MINI_USER_LOCATION_POINT", `POINT(${pointXy[0]} ${pointXy[1]})`)
    store.commit("home/SET_MINI_USER_LOCATION", route.query.point);
    store.commit("home/SET_MINI_USER_ID", userId);
    store.commit("home/SET_MINI_USER_LOCATION_POINT", `POINT(${pointXy[0]} ${pointXy[1]})`);
    router.push(`${targetUrl}?miniJson=${JSON.stringify(route.query)}`);
})

const getFarmList = async () => {
    const { data } = await VE_API.farm.userFarmSelectOption();
    if(data && data.length > 0) {
        localStorage.setItem('isGarden', true);
    }
}

</script>

<style scoped></style>
