<template>
    <el-upload class="hc-upload-table-form" :disabled="isLoading" :placeholder="placeholder" :keyname="isKeyName" :headers="getTokenHeader()" :action="action" :accept="accept" :show-file-list="false"
               :on-progress="uploadprogress" @exceed="formUploadExceed" :on-error="formUploadError" @success="formUploadSuccess" v-loading="isLoading" element-loading-text="上传中...">
        <img v-if="isSrc" :src="isSrc" class="hc-table-form-img" alt="">
        <div class="hc-table-form-icon" v-else>点此选择文件并上传</div>
        <div v-if="isSrc" class="hc-table-form-del">
            <el-button type="danger" plain @click.stop="delTableFormFile">删除当前文件</el-button>
        </div>
    </el-upload>
</template>

<script setup>
import { ref, watch } from 'vue'
import {getTokenHeader} from '~src/api/request/header';
const props = defineProps({
    src: {
        type: [Number,String],
        default: ''
    },
    keyname: {
        type: [Number,String],
        default: ''
    },
    placeholder: {
        type: [Number,String],
        default: '相片'
    },
})

//变量
const isLoading = ref(false)
const isSrc = ref(props.src)
const isKeyName = ref(props.keyname)

const action = '/api/blade-manager/exceltab/add-buss-imginfo';
const accept = 'image/png,image/jpg,image/jpeg';

//监听
watch(() => [
    props.src,
    props.keyname,
], ([src, keyname]) => {
    isSrc.value = src
    isKeyName.value = keyname
})

//事件
const emit = defineEmits(['success', 'del'])

//上传进度
const uploadprogress = () => {
    isLoading.value = true
}

//上传完成
const formUploadSuccess = (res) => {
    isLoading.value = false
    if (res.code === 200) {
        const link = res.data?.link || ''
        emit('success', {
            res,
            src: link,
            key: isKeyName.value,
        })
    }
}

//上传失败
const formUploadError = () => {
    isLoading.value = false
}

//格式错误
const formUploadExceed = () => {
    isLoading.value = false
}

//删除上传的文件
const delTableFormFile = () => {
    emit('del', isKeyName.value)
}
</script>

<style lang="scss" scoped>

</style>
