<template>
  <el-dialog
    v-model="visible"
    title="用户信息"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="500px"
    top="10vh"
    append-to-body
    @open="modalBeforeOpen"
  >
    <div v-loading="loading">
      <el-descriptions :column="1" border label-width="140px">
        <el-descriptions-item label="归属学校">
          {{ userInfo.schoolName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="学校ID">
          {{ userInfo.schoolId || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="姓名">
          {{ userInfo.name || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="用户角色">
          {{ userInfo.roleName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="最后登录IP">
          {{ userInfo.lastLoginIp || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="最后登录时间">
          {{ timestampFilter(userInfo.lastLoginTime) }}
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <template #footer> </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import useLoading from '@/hooks/loading';
  import useModal from '@/hooks/modal';
  import { getUser } from '@/api/user';
  import type { UserItem } from '@/api/types/user';
  import { timestampFilter } from '@/utils/filter';

  defineOptions({
    name: 'UserInfoDialog',
  });

  interface Props {
    userId?: number; // 编辑时传入，新增时为空
  }

  const props = defineProps<Props>();

  /* modal */
  const { visible, open, close } = useModal();
  defineExpose({ open, close });

  const { loading, setLoading } = useLoading();

  // 用户信息
  const userInfo = reactive<Partial<UserItem>>({
    schoolName: '',
    schoolId: undefined,
    name: '',
    roleName: '',
    lastLoginIp: '',
    lastLoginTime: '',
  });

  // 加载用户信息
  const loadUserInfo = async () => {
    if (!props.userId) {
      ElMessage.error('用户ID不能为空');
      return;
    }

    setLoading(true);
    try {
      const data = await getUser(props.userId);
      Object.assign(userInfo, {
        schoolName: data.schoolName,
        schoolId: data.schoolId,
        name: data.name,
        roleName: data.roleName,
        lastLoginIp: data.lastLoginIp,
        lastLoginTime: data.lastLoginTime,
      });
    } catch (error) {
      ElMessage.error('获取用户信息失败');
      console.error('获取用户信息失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 弹窗打开前的处理
  const modalBeforeOpen = async () => {
    await loadUserInfo();
  };
</script>
