<template>
  <a-card :bordered="false">
    <div class="panel-inner">
      <a-upload :custom-request="customRequest" :file-list="fileList" :show-upload-button="true" :show-file-list="false"
        :on-before-upload="beforeUpload" @change="uploadChange" accept="image/png, image/jpeg, image/jpg">
        <template #upload-button>
          <a-avatar :size="100" class="info-avatar" v-if="fileList.length" :imageUrl="fileList[0].url">
            <template #trigger-icon>
              <icon-camera />
            </template>
          </a-avatar>
        </template>
      </a-upload>
      <a-descriptions :data="renderData" :column="2" align="right" layout="inline-horizontal" :label-style="{
        width: '140px',
        fontWeight: 'normal',
        color: 'rgb(var(--gray-8))',
      }" :value-style="{
        width: '250px',
        paddingLeft: '8px',
        textAlign: 'left',
      }">
        <template #label="{ label }">{{ label }} :</template>
        <template #value="{ value, data }">
          <span>{{ value }}</span>
        </template>
      </a-descriptions>
    </div>
  </a-card>
</template>

<script setup>
import { uploadAvatar } from '@/api/upload'
import { Notification } from '@arco-design/web-vue'
import { ref, computed, onBeforeMount } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { Message } from '@arco-design/web-vue'

const user = ref(null)
const fileList = ref([])

const userStore = useUserStore()

const getUser = async () => {
  const userInfo = await userStore.getInfoFromServer()
  if (userInfo?.avatar) {
    user.value = userInfo
    fileList.value = [{ uid: '-1', name: 'avatar', url: userInfo.avatar }]
  }
}

onBeforeMount(getUser)

const renderData = computed(() => {
  if (!user.value) return []
  return [
    { label: '用户名', value: user.value.username },
    { label: '邮箱', value: user.value.email },
    { label: '注册时间', value: stramptoTime(user.value.registTime) }
  ]
})

const stramptoTime = (time) => {
  if (time < 10)
    return '未知时间'
  return new Date(+time).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })
}

const uploadChange = (fileItemList) => {
  if (fileItemList.length > 0) {
    fileList.value = [{ uid: '-1', name: 'avatar', url: fileItemList[0].url }]
  }
}

const beforeUpload = (file) => {
  return new Promise((resolve, reject) => {
    const isJpgOrPng =
      file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
    if (!isJpgOrPng) {
      Notification.error({
        title: '图片上传失败！',
        content: '请上传jpg/png格式的图片文件!'
      })
      return reject('图片格式错误')
    }

    const isLt3M = file.size / 1024 / 1024 < 3
    if (!isLt3M) {
      Notification.error({
        title: '图片上传失败！',
        content: '图片大小不得超过3MB!',
      })
      return reject('图片大小超过限制')
    }

    resolve(file)
  })
}

const customRequest = async ({ onSuccess, onError, fileItem }) => {
  try {
    const formData = new FormData()
    formData.append('upload', fileItem.file)
    formData.append('uuid', user.value?.uuid)
    formData.append('session', user.value?.session)

    const res = await uploadAvatar(formData)
    if (!res || res.code !== 0) {
      onError(new Error('上传失败'), res)
      return Notification.error({
        title: '头像上传失败',
        content: res?.msg ?? '请求出现错误，请稍后再试'
      })
    }

    fileList.value = [{ uid: '-1', name: 'avatar', url: res.data.picturePath }]

    await userStore.getInfoFromServer()
    Message.success('上传头像成功！')
    onSuccess(res.data)
    // setTimeout(() => { router.go(0) }, 2000)
  } catch (error) {
    Notification.error({
      title: '头像上传失败',
      content: '请求出现错误，请稍后再试',
    })
    onError()
  }
}
</script>

<style scoped lang="less">
.arco-card {
  padding: 14px 0 4px 4px;
  border-radius: 4px;
}

.panel-inner {
  display: flex;
  align-items: center;
  gap: 54px;
}

:deep(.arco-descriptions-layout-inline-horizontal .arco-descriptions-item-label),
:deep(.arco-descriptions-layout-inline-horizontal .arco-descriptions-item-value) {
  white-space: nowrap;
}

:deep(.arco-avatar-trigger-icon-button) {
  width: 32px;
  height: 32px;
  line-height: 32px;
  background-color: #e8f3ff;

  .arco-icon-camera {
    margin-top: 8px;
    color: rgb(var(--arcoblue-6));
    font-size: 14px;
  }
}

@media (max-width: 768px) {
  .arco-card {
    padding: 10px 0 2px;
  }

  .panel-inner {
    flex-direction: column;
    align-items: center;
    gap: 16px;
  }

  :deep(.arco-descriptions) {
    width: 100%;
  }

  :deep(.arco-descriptions-view) {
    width: 100%;
  }

  :deep(.arco-descriptions-layout-inline-horizontal .arco-descriptions-item) {
    width: 100%;
  }

  :deep(.arco-descriptions-layout-inline-horizontal .arco-descriptions-item-label) {
    min-width: 72px;
    padding-right: 8px;
  }

  :deep(.arco-descriptions-layout-inline-horizontal .arco-descriptions-item-value) {
    flex: 1;
    min-width: 0;
  }

  :deep(.arco-descriptions-item-value > span) {
    word-break: break-word;
    overflow-wrap: anywhere;
  }
}
</style>
