<script setup lang="ts">
import { ContentWrap } from '../../../components/ContentWrap'
import { ref, unref } from 'vue'
import { ElDivider, ElImage, ElButton, ElMessage } from 'element-plus'
import defaultAvatar from '../../../assets/imgs/avatar.png'
import UploadAvatar from './components/UploadAvatar.vue'
import { Dialog } from '../../../components/Dialog'
import { useUserStore } from '../../../store/modules/user'
import EditPassword from './components/EditPassword.vue'

const userInfo = ref()
const fetchDetailUserApi = async () => {
  // 这里可以调用接口获取用户信息
  const data = useUserStore().getUserInfo
  userInfo.value = data
}
fetchDetailUserApi()

const dialogVisible = ref(false)

const uploadAvatarRef = ref<ComponentRef<typeof UploadAvatar>>()
const avatarLoading = ref(false)
const saveAvatar = async () => {
  try {
    avatarLoading.value = true
    const base64 = unref(uploadAvatarRef)?.getBase64()
    console.log(base64)
    // 这里可以调用修改头像接口
    fetchDetailUserApi()
    ElMessage.success('修改成功')
    dialogVisible.value = false
  } catch (error) {
    console.log(error)
  } finally {
    avatarLoading.value = false
  }
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap title="个人信息" class="w-400px">
      <div class="flex justify-center items-center">
        <!-- <div
          class="avatar w-[150px] h-[150px] relative cursor-pointer"
          @click="dialogVisible = true"
        > -->
        <div class="avatar w-[150px] h-[150px]">
          <ElImage
            class="w-[150px] h-[150px] rounded-full"
            :src="userInfo?.avatarUrl || defaultAvatar"
            fit="fill"
          />
        </div>
      </div>
      <ElDivider />
      <div class="flex justify-between items-center">
        <div>账号：</div>
        <div>{{ userInfo?.userNo }}</div>
      </div>
      <ElDivider />
      <div class="flex justify-between items-center">
        <div>姓名：</div>
        <div>{{ userInfo?.userName }}</div>
      </div>
      <ElDivider />
      <div class="flex justify-between items-center">
        <div>所属部门：</div>
        <div>
          {{ userInfo?.deptList[0].deptName }}
        </div>
      </div>
      <ElDivider />
    </ContentWrap>
    <ContentWrap title="修改密码" class="flex-[3] ml-20px">
      <EditPassword />
    </ContentWrap>
  </div>

  <Dialog v-model="dialogVisible" title="修改头像" width="800px">
    <UploadAvatar ref="uploadAvatarRef" :url="userInfo?.avatarUrl || defaultAvatar" />

    <template #footer>
      <ElButton type="primary" :loading="avatarLoading" @click="saveAvatar"> 保存</ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>

<style lang="less" scoped>
.avatar {
  position: relative;

  &:hover {
    &::after {
      opacity: 1;
    }
  }
}
</style>
