<template>
  <div class="main">
    <h4>请选择老师</h4>
    <van-empty v-if="!teachers.length" description="暂无可用老师" />
    <van-cell-group v-else>
      <van-cell
        v-for="teacher in teachers"
        :key="teacher.hty_id"
        :title="teacher.real_name + (teacher.meta?.nickName ? ' (' + teacher.meta.nickName + ')' : '')"
        :label="teacher.hty_id"
        is-link
        @click="onSelect(teacher.hty_id)"
      >
        <template #icon>
          <hty-image :type="'avatar'" :url="teacher.avatar_url || teacher.meta?.avatarUrl" />
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, onMounted } from "vue";
import { Cell, CellGroup, Empty } from "vant";
import { useRouter } from "vue-router";
import useUser from "~/store/user";
import useTeacher from "~/store/teacher";
import HtyImage from "~/components/hty-image.vue";

export default defineComponent({
  name: "student-teacher-select",
  components: {
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Empty.name]: Empty,
    [HtyImage.name]: HtyImage,
  },
  setup() {
    const router = useRouter();
    const { store: userStore, loadMyTeachers, getValidTeachers, claimTeacher } = useUser();
    const { switchTeacher } = useTeacher();
    const teachers = computed(() => userStore.teachers.mine.length > 0 ? userStore.teachers.mine : userStore.teachers.valid);

    onMounted(async () => {
      await loadMyTeachers();
      if (userStore.teachers.mine.length === 0) {
        await getValidTeachers();
      }
    });

    const onSelect = async (teacherId: string) => {
      // If using fallback list (unclaimed teachers), claim teacher first
      if (userStore.teachers.mine.length === 0) {
        try {
          await claimTeacher(userStore.current.hty_id!, teacherId);
          await loadMyTeachers();
        } catch {
          return;
        }
      }
      switchTeacher(teacherId);
      if (router.length > 1) {
        router.back();
      } else {
        router.push('/student/home');
      }
    };

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

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