<template>
  <div class="main">
    <template v-if="has_login">
      <template v-if="is_enabled && is_registered">
        <template v-if="!store.currentRole">
          <h5>请选择您的登录身份</h5>
          <van-grid square :gutter="10" :column-num="4">
            <van-grid-item
              :text="role.role_name || role.role_key"
              v-for="role in activeRoles"
              @click="chooseRole(role.role_key, scene)"
            ></van-grid-item>
          </van-grid>
        </template>
        <div v-else class="role-home-redirect">
          <van-loading size="24px" vertical>进入工作台…</van-loading>
        </div>
      </template>
      <van-empty v-else description="账号未启用或未通过注册审核" />
    </template>
    <course-package-store v-if="!has_login" />
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, watchEffect } from "vue";
import useUser from "~/store/user";
import useOrg from "~/store/org";
import useTeacher from "~/store/teacher";
import { useRouter } from "vue-router";
import { HtyBaseRoles, HtyStates, HtySuperRoles, WxScenes, UserStates } from "~/types";
import {
  Button,
  CellGroup,
  Empty,
  Field,
  Form,
  Grid,
  GridItem,
  Loading,
  Picker,
  Popup,
  Radio,
  RadioGroup,
  showConfirmDialog,
} from "vant";
import CoursePackageStore from "~/components/course-package-store.vue";
import { CurrentUserRole } from "~/utils";
import { sanitizeMiniProgramWebViewPathForRouter } from "~/utils/wxMiniProgramWebViewShare";

export default defineComponent({
  components: {
    [Button.name!]: Button,
    [Empty.name!]: Empty,
    [Field.name!]: Field,
    [CellGroup.name!]: CellGroup,
    [Grid.name!]: Grid,
    [GridItem.name!]: GridItem,
    [Picker.name!]: Picker,
    [Radio.name!]: Radio,
    [RadioGroup.name!]: RadioGroup,
    [Form.name!]: Form,
    [Popup.name!]: Popup,
    [Loading.name!]: Loading,
    [CoursePackageStore.name!]: CoursePackageStore,
  },
  props: ["params"],
  setup({ params }) {
    const router = useRouter();
    const { store, setRole, chooseRole, update } = useUser(router);
    const { store: orgStore, loadMyOrgs, switchOrg } = useOrg();
    const { store: teacherStore, tryAutoSelect } = useTeacher();
    let { unionid, openid, status, nickName, avatarUrl, scene, tongzhi_id, page_path } = params;
    console.log(params)
    console.log("loaded at...", Date.now())
    let userStatus = Number(status || UserStates.Anonymous);
    if (scene) {
      scene = Number(scene) as WxScenes;
    }
    store.unionid = unionid;
    store.wxPayload = {
      openid, scene, avatarUrl, nickName, status
    }

    const has_teacher = computed(() => store.teachers.mine.length > 0);
    const is_student = computed(() => store.currentRole === HtyBaseRoles.STUDENT);

    onMounted(async () => {
      console.log('on mounted');
      // update openid
      if (store.current.id && !store.current.openid && openid) {
        await update(store.userMeta, { ...store.userAppMeta, openid });
      }

      console.log("page_path...", page_path, decodeURIComponent(page_path))
      if (page_path) {
        const inner = sanitizeMiniProgramWebViewPathForRouter(decodeURIComponent(page_path))
        await router.push(inner)
        return;
      }

      // 如果先打开了小程序，然后从通知里打开小程序，微信此时认定的场景值很可能依然是之前一次打开时的值，而不是消息通知的值
      if (tongzhi_id) {
        await router.push("/tongzhi/detail?id=" + tongzhi_id);
        return;
      }

      if (scene === WxScenes.TemplateMessage) {
        await router.push("/tongzhi");
        return;
      }

      if (store.current.hty_id && store.current.enabled && store.current.is_registered) {
        const organizations = await loadMyOrgs();
        if (organizations.length > 1 && !orgStore.currentOrgId) {
          await router.replace("/org/select");
          return;
        }
        if (organizations.length === 1 && !orgStore.currentOrgId) {
          await switchOrg(organizations[0].id);
        }
      }
    });

    const initial_roles = [
      { value: HtyBaseRoles.STUDENT, label: "学生" },
      { value: HtyBaseRoles.TEACHER, label: "老师" },
    ];
    const has_login = computed(() => !!store.current.hty_id);
    const is_registered = computed(() => store.current.is_registered);
    const is_enabled = computed(() => store.current.enabled);
    const authorized = computed(() => userStatus === UserStates.Authorized);
    const activeRoles = computed(() =>
      store.current.roles?.filter((r) => r.role_status === HtyStates.ACTIVE)
    );

    if (has_login.value && !(is_registered.value && is_enabled.value)) {
      store.currentRole = HtyBaseRoles.GUEST;
    }

    if (is_registered.value && is_enabled.value && activeRoles.value?.length <= 1) {
      let activeRole = activeRoles.value[0]
      console.log('active role...', activeRole)
      if (activeRole) {
        store.currentRole = activeRole.role_key;
        window.localStorage.setItem(CurrentUserRole, activeRole.role_key);
        if (activeRole.role_key === HtyBaseRoles.STUDENT && store.teachers.mine.length > 0) {
          tryAutoSelect(store.teachers.mine);
        }
        if (scene === WxScenes.TemplateMessage) {
          router.push("/tongzhi");
        }
      }
    }

    const landingPathForRole = (role: string | undefined): string | null => {
      if (!role) return null
      if (role === HtyBaseRoles.STUDENT) return '/student/home'
      if (role === HtyBaseRoles.TEACHER) return '/teacher/home'
      if (role === HtySuperRoles.ADMIN) return '/admin/teachers'
      if (role === HtySuperRoles.TESTER) return '/tester'
      if (role === HtySuperRoles.SUPERVISOR) return '/supervisor/subsidiaries'
      return '/guest/profile'
    }

    watchEffect(() => {
      if (router.currentRoute.value.path !== '/') return
      if (!store.current.hty_id) return
      if (!store.current.enabled || !store.current.is_registered) return
      if (!store.currentRole) return

      // Auto-select first teacher for students when none is selected
      if (store.currentRole === HtyBaseRoles.STUDENT && store.teachers.mine.length > 0) {
        tryAutoSelect(store.teachers.mine);
      }

      // If student still has no teacher, redirect to teacher-select page
      if (store.currentRole === HtyBaseRoles.STUDENT && !teacherStore.currentTeacherId) {
        void router.replace('/student/teacher-select')
        return
      }

      const target = landingPathForRole(store.currentRole)
      if (target && target !== '/') {
        void router.replace(target)
      }
    })

    return {
      is_registered, is_enabled, is_student, has_teacher,
      has_login, authorized, activeRoles, chooseRole, setRole, store,
      initial_roles, scene
    }
  },
});
</script>

<style scoped lang="less">
.main {
  width: 100%;
  height: calc(100% - 1rem);
  overflow-y: auto;

  h4,
  h5 {
    text-align: center;
    color: #555555;
  }

  .buttons {
    margin-top: 1rem;
    padding: 0.32rem;
  }

  .text-warning {
    font-size: small;
    color: #ed6a0c;
  }

  .role-home-redirect {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 40vh;
    padding: 1rem;
  }
}
</style>
