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

const isFocus = ref(false)

//获得焦点
const handleFocus = () => {
    isFocus.value = true
}

//失去焦点
const handleBlur = () => {
    isFocus.value = false
}
</script>

<style lang="scss" scoped>
.hc-upload-table-form {
    border-radius: 3px;
    transition: box-shadow 0.3s, background-color 0.3s;
    &.is-focus, &:hover {
        background-color: #eddac4;
        box-shadow: 0 0 0 1.5px var(--el-color-primary) inset;
    }
    .hc-upload-input-src {
        position: absolute;
        z-index: -1;
        right: 10px;
        width: 10px;
    }
}
</style>
