<template>
    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false" accept="image/*"
        :on-success="handleSuccess" :before-upload="beforeUpload" :http-request="handleHttpRequest">
        <img v-if="props.imageUrl" :src="props.imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
            <Plus />
        </el-icon>
    </el-upload>
    <!-- imageUrl: {{ imageUrl }} -->
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, UploadProps, UploadRequestOptions } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import * as cos from '../utils/qcloud-cos-upload';

const props = defineProps({
    // 获取列表 接口函数
    'imageUrl': {
        type: String,
        required: true,
        default: '',
    }
})

const emit = defineEmits(['change'])

const handleHttpRequest = async (data: UploadRequestOptions) => {
    console.log('httpRequest', data)
    let result = await cos.upload(data.file)
    console.log("result", result)
    return result
}

const handleSuccess: UploadProps['onSuccess'] = (
    response, // 这里的 response 就是 handleHttpRequest 返回的结果
    uploadFile
) => {
    console.log("response", response)
    // let url = URL.createObjectURL(uploadFile.raw!)
    let url = "//" + response.Location
    emit('change', url)
}

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
    console.log("rawFile", rawFile)
    if (!['image/jpeg', 'image/png'].includes(rawFile.type)) {
        ElMessage.error('仅支持 JPG、PNG 格式图片，请重新选择')
        return false
    } else if (rawFile.size > 2 * 1024 * 1024) {
        ElMessage.error('图片太大，请选择 2MB 以内的图片')
        return false
    }
    return true
}
</script>

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

.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: 120px;
    height: 120px;
    text-align: center;
}
</style>
