<template>
  <el-upload
      class="avatar-uploader"
      :action="state.action"
      :headers="state.headers"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :on-error="handleAvatarError"
      :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
    <el-icon v-else class="avatar-uploader-icon">
      <Plus/>
    </el-icon>
  </el-upload>
</template>

<script lang="ts" setup>
import {ref, reactive, onMounted, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'

import type {UploadProps} from 'element-plus'
import {Session} from "/@/utils/storage";
import u from "/@/utils/u"
import {Msg} from "/@/utils/message";

const emit = defineEmits(['update:modelValue', 'on-change']);

const props = defineProps({
  modelValue: {
    type: String
  }
})

const state = reactive({
  action: '',
  headers: {}
})

watch(() => props.modelValue, (o, v) => {
  imageUrl.value = u.fmt.fmtUrl(props.modelValue);
})

const imageUrl = ref('')

onMounted(() => {
  let url = import.meta.env.VITE_API_URL;
  if (!url) {
    url = `${location.origin}/admin/`;
  }
  state.action = `${url}file/upload`
  state.headers = {"satoken": Session.get("token")}
})

const handleAvatarError = ()=>{
  Msg.hideLoading();
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  Msg.hideLoading();
  console.log(uploadFile, response)
  let {url, uuid} = response.data;
  imageUrl.value = url;
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)

  emit("update:modelValue", uuid)
  emit("on-change", uuid)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  Msg.showLoading("上传中...")
  return true
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 60px;
  height: 60px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
}
</style>
