<template>
    <div class="hc-global-upload-file-box-hide" v-if="isBody">
        <Teleport to="#app">
            <UploadFile ref="uploadFileRef"
                        :global="customGlobal"
                        :params="customParams"
                        :options="customOptions"
                        @fileAdded="uploadFileAdded"
                        @fileProgress="uploadFileProgress"
                        @fileSuccess="uploadFileSuccess"
                        @filesChange="uploadFileChange"
                        @fileError="uploadFileError"
            />
        </Teleport>
    </div>
</template>

<script setup>
import {nextTick, onMounted, ref, watch} from 'vue'
import UploadFile from './file.vue'

const props = defineProps({
    global: {
        type: Boolean,
        default: true
    },
    // 发送给服务器的额外参数
    params: {
        type: Object,
        default: () => ({})
    },
    options: {
        type: Object,
        default: () => ({})
    }
})

//初始变量
const isBody = ref(false)
const uploadFileRef = ref(null)
const customGlobal = ref(props.global)
const customParams = ref(props.params)
const customOptions = ref(props.options)

//事件
const emit = defineEmits(['fileAdded', 'fileSuccess', 'fileError', 'filesChange', 'fileProgress'])

//监听
watch(() => [
    props.params,
    props.options,
    props.global
], ([params, options, global]) => {
    customGlobal.value = global
    if (params) {
        customParams.value = params
    }
    if (options) {
        customOptions.value = options
    }
})

onMounted(() => {
    //页面渲染完成后，再让 vue3 的 Teleport，把弹出框挂载到外部节点上。
    nextTick(() => {
        isBody.value = true
    })
})

//选择了文件
const uploadFileAdded = () => {
    emit('fileAdded')
}

// 文件上传进度
const uploadFileProgress = (res) => {
    emit('fileProgress', res)
}
// 文件上传成功的回调
const uploadFileSuccess = (res) => {
    emit('fileSuccess', res)
}

//文件上传失败
const uploadFileError = () => {
    emit('fileError')
}

// 文件全部上传完成
const uploadFileChange = () => {
    emit('filesChange')
}

//关闭
const close = () => {
    remove()
    isShow(false)
}

//清除
const remove = () => {
    uploadFileRef.value?.remove()
}

const cancel = () => {
    uploadFileRef.value?.cancel()
}

//是否显示
const isShow = (res) => {
    uploadFileRef.value?.isShow(res)
}

//点击上传按钮
const btnUpload = () => {
    uploadFileRef.value?.btnUpload()
}

// 暴露出去
defineExpose({
    close,
    remove,
    cancel,
    isShow,
    btnUpload
})
</script>

<style lang="scss">
.hc-global-upload-file-box-hide {
    display: none;
}
</style>
