<template>
  <div class="main">
    <h4>请选择机构</h4>
    <van-empty v-if="!orgs.length" description="暂无可用机构" />
    <van-cell-group v-else>
      <van-cell
        v-for="org in orgs"
        :key="org.id"
        :title="org.org_name"
        :label="org.org_desc || org.id"
        is-link
        @click="onSelect(org.id)"
      />
    </van-cell-group>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, computed } from "vue";
import { Cell, CellGroup, Empty, showFailToast } from "vant";
import { useRouter } from "vue-router";
import useOrg from "~/store/org";
import { CurrentUserRole, CurrentTeacherId } from "~/utils";
import { HtyBaseRoles } from "~/types";

export default defineComponent({
  name: "org-select",
  components: {
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Empty.name]: Empty,
  },
  setup() {
    const router = useRouter();
    const { store, loadMyOrgs, switchOrg } = useOrg();
    const orgs = computed(() => store.orgs);

    onMounted(async () => {
      await loadMyOrgs();
    });

    const onSelect = async (orgId: string) => {
      const switched = await switchOrg(orgId);
      if (!switched) {
        return;
      }
      // For students, clear teacher and let index page handle auto-select
      const currentRole = window.localStorage.getItem(CurrentUserRole);
      if (currentRole === HtyBaseRoles.STUDENT) {
        window.localStorage.removeItem(CurrentTeacherId);
      }
      // Redirect to index page which handles role-based auto-select/redirect
      window.location.assign("/");
    };

    return { orgs, onSelect };
  },
});
</script>

<style scoped lang="less">
.main {
  padding: 0.5rem;
}
</style>
