<template>
    <div class="info">
        <div class="avatar" @click="editAvatar">
          <van-image v-if="avatarUrl" round :src="avatarUrl" width="132" height="132" fit="cover" />
          <van-icon v-else size="132" name="https://b.yzcdn.cn/vant/icon-demo-1126.png" />
          <van-icon size="16" name="edit" class="icon-edit" color="#1989fa" />
        </div>
        <h5>
          <template v-if="!state.editing">
            {{user.real_name}}
            <van-icon size="16" @click="state.editing = true" name="edit" class="icon-edit" color="#1989fa" />
          </template>
          <template v-else>
            <input type="text" v-model="state.real_name" />
            <van-button type="primary" size="small" class="input-action" @click.prevent="editName"><van-icon  size="16" name="success" /></van-button>
            <van-button type="danger" size="small" class="input-action" @click.prevent="state.editing = false"><van-icon  size="16" name="cross" /></van-button>
          </template>
        </h5>
        <div class="current-org">
          <span>当前机构：{{ currentOrgName || '未选择机构' }}</span>
          <van-button size="mini" plain type="primary" @click="goOrgSelect">切换机构</van-button>
        </div>
        <div v-if="isStudent" class="current-teacher">
          <span>当前老师：{{ currentTeacherName || '未选择老师' }}</span>
          <van-button size="mini" plain type="primary" @click="goTeacherSelect">切换老师</van-button>
        </div>
        <div class="roles">
            <template v-for="role in roles">
                <van-tag type="primary" v-if="currentRole === role.role_key">{{role.role_name}}</van-tag>
                <van-tag v-else-if="role.role_status === 'DELETED'">{{role.role_name}}</van-tag>
                <van-tag plain type="primary" v-else>{{role.role_name}}</van-tag>
            </template>
            <van-icon v-if="hasMultiRoles" @click="switching = true" name="exchange" />
        </div>
    </div>
    <van-action-sheet :lock-scroll="false" v-model:show="switching" :actions="roles" @select="switchRole" />
</template>
<script lang="ts">
import {defineComponent, ref, computed, reactive, onMounted} from 'vue'
import {computedAsync} from "@vueuse/core";
import {Image, Icon, Tag, ActionSheet, showConfirmDialog, Button, showToast} from 'vant'
import useUser from '~/store/user';
import {HtyRole, HtyStates} from '~/types'
import { useRouter } from "vue-router";
import {UpyunAccess} from "~/utils/upyun";
import {CurrentUserRole, HtyAuthToken, HtySudoToken} from "~/utils";
import useOrg from "~/store/org";
import useTeacher from "~/store/teacher";

export default defineComponent({
    name: 'user-profile',
    components: {
        [Image.name!]: Image,
        [Icon.name!]: Icon,
        [Tag.name!]: Tag,
        [ActionSheet.name!]: ActionSheet,
        [Button.name!]: Button
    },
    setup() {
        const switching = ref(false);
        const router = useRouter();
        const { store, chooseRole, update, logout } = useUser(router);
        const { store: orgStore, loadMyOrgs } = useOrg();
        const { store: teacherStore, switchTeacher } = useTeacher();
        const user = computed(() => store.current)
        const state = reactive({
          editing: false,
          real_name: user.value.real_name
        })

        const tokenOrgRoleKeys = computed(() => {
          try {
            const token = window.localStorage.getItem(HtyAuthToken);
            if (!token) return [] as string[];
            const tokenParts = token.split(".");
            if (tokenParts.length < 2) return [] as string[];
            const payloadRaw = tokenParts[1].replace(/-/g, "+").replace(/_/g, "/");
            const payloadJson = decodeURIComponent(
              atob(payloadRaw)
                .split("")
                .map((char) => `%${("00" + char.charCodeAt(0).toString(16)).slice(-2)}`)
                .join("")
            );
            const payload = JSON.parse(payloadJson);
            return payload.current_org_role_keys || [];
          } catch (_e) {
            return [] as string[];
          }
        });

        const roles = computed(() => {
          const allRoles = store.current.roles || [];
          const roleKeys = tokenOrgRoleKeys.value;
          const scopedRoles = roleKeys.length
            ? allRoles.filter((role) => roleKeys.includes(role.role_key))
            : allRoles;
          return scopedRoles.map((role) => ({
            ...role,
            name: role.role_name,
            disabled: role.role_status === HtyStates.DELETED,
          }));
        })
        const hasMultiRoles = computed(() => roles.value.filter(r => r.role_status === HtyStates.ACTIVE).length > 1)
        const currentRole = computed(() => store.currentRole)
        const switchRole = ({role_key, role_name}: HtyRole) => {
            if (role_key !== store.currentRole) {
              showConfirmDialog({message: `将切换到【${role_name}】身份`})
                .then(() => {
                chooseRole(role_key)
                switching.value = false;
                }).catch(() => {})
            } else {
                switching.value = false;
            }
        }

        const editAvatar = () => {
          router.push("/avatar")
        }
        const goOrgSelect = () => router.push("/org/select");

        const logoutUser = () => {
          logout()
          showToast("logout")
        }

        const editName = async () => {
          let real_name = (state.real_name || "").trim();
          if (real_name !== user.value.real_name) {
            showConfirmDialog({
              message: "确认修改姓名为" + real_name + "? "
            }).then(async () => {
              let user = store.userMeta, userApp = store.userAppMeta;
              await update({...user, real_name}, userApp)
              state.editing = false;
            });
          } else {
            state.editing = false;
          }
        }

        const avatarUrl = computedAsync(async () => {
          let url = store.current.avatar_url || store.current.meta?.avatarUrl;
          if (url && url.includes("upyun")) {
            return (await UpyunAccess.getSign(url));
          }
          return url;
        })

        const currentOrgName = computed(() => {
          const currentOrgId = orgStore.currentOrgId;
          if (!currentOrgId) return "";
          return orgStore.orgs.find(org => org.id === currentOrgId)?.org_name || currentOrgId;
        });

        const isStudent = computed(() => store.currentRole === 'STUDENT');

        const currentTeacherName = computed(() => {
          if (!teacherStore.currentTeacherId) return '';
          const teacher = store.teachers.mine.find(t => t.hty_id === teacherStore.currentTeacherId);
          return teacher?.real_name || '';
        });

        const goTeacherSelect = () => router.push("/student/teacher-select");

        onMounted(async () => {
          if (!orgStore.orgs.length) {
            await loadMyOrgs();
          }
        });

        return { switching, hasMultiRoles, roles,  user, currentRole, switchRole, editAvatar, avatarUrl, editName, state, logoutUser, currentOrgName, goOrgSelect, isStudent, currentTeacherName, goTeacherSelect }
    }
})

</script>
<style lang="less" scoped>
  .info {
    text-align: center;
    padding: 0.32rem 0 2rem;
    background: #FFFFFF;

    h5 {
      margin: 0.2rem 0;
      display: flex;
      justify-content: center;
      align-items: center;

      :deep(.van-icon) {
        margin-left: 0.1rem;
      }

      input {
        display: inline-block;
        padding: 0.125rem 0.25rem;
        font-weight: 400;
        color: #212529;
        background-color: #fff;
        background-clip: padding-box;
        border: 1px solid #ced4da;
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
        transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
        position: relative;
        width: 2.5rem;
      }
      .input-action {
        border-radius: 0;
      }
    }

    .avatar {
      position: relative;
      width: 132px;
      margin: 0 auto;
      :deep(.icon-edit) {
        position: absolute;
        right: 0;
        bottom: 0;
      }
    }


    .roles {
      display: flex;
      align-items: center;
      justify-content: center;

      :deep(.van-tag) {
       margin: 0 0.06rem;
      }

      :deep(.van-icon) {
        margin-left: 0.1rem;
      }
    }

    .current-org, .current-teacher {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 0.12rem;
      color: #666;
      margin-bottom: 0.12rem;
    }
  }

</style>
