<template>
    <el-upload
        class="avatar-uploader"
        :action="uploadImgUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :headers="headers"
        :before-upload="beforeAvatarUpload"
    >
        <div class="image-box">
            <img v-if="imageUrl" :src="imageUrl" class="img-box" />
            <div v-else class="kong d-flex flex-cln a-c j-c">
                <div class="d-flex a-c">
                    <img class="mr5" src="@/assets/svg/normal_u190.svg" alt="" />
                    <div>点击上传文件</div>
                </div>
            </div>
        </div>
    </el-upload>
</template>

<script lang="ts" setup name="PhotoUpload">
import { ComponentInternalInstance, getCurrentInstance, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { globalHeaders } from "@/utils/request";
import { propTypes } from '@/utils/propTypes';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps({
  modelValue: String,
  // 图片数量限制
  limit: propTypes.number.def(1),
  // 大小限制(MB)
  fileSize: propTypes.number.def(500),
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: propTypes.array.def(["png", "jpg", "jpeg"])
});
const emit = defineEmits(['update:modelValue']);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload"); // 上传的图片服务器地址
const headers = ref(globalHeaders());
const imageUrl = ref('')

watch(() => props.modelValue, async val => {
  if (val) {
    imageUrl.value = val as string
  }
}, { deep: true, immediate: true });

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    // imageUrl.value = response.data.url
    proxy?.$modal.closeLoading();
    emit('update:modelValue', response.data.url)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    let isImg = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (rawFile.name.lastIndexOf(".") > -1) {
      fileExtension = rawFile.name.slice(rawFile.name.lastIndexOf(".") + 1);
    }
    isImg = props.fileType.some((type: any) => {
      if (rawFile.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } else {
    isImg = rawFile.type.indexOf("image") > -1;
  }
  if (!isImg) {
    proxy?.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = rawFile.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy?.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy?.$modal.loading("正在上传图片，请稍候...");
}
</script>

<style lang="scss">
.avatar-uploader {
    width: 100%;

    .el-upload {
        width: 100%;
    }
}

.avatar-uploader .image-box {
    width: 100%;
    height: 115px;
    border-radius: 6px;
    border: 1px dashed #0f8240;
    background-color: rgba(0, 0, 0, 0.02);
    box-sizing: border-box;
}
</style>
<style lang="scss" scoped>
.kong {
    width: 100%;
    height: 100%;
}
.img-box {
    width: 100%;
    height: 100%;
}

.def-xiao {
    width: 103px;
    height: 60px;
}
</style>
