<template>
    <div class="form-item-dashed hover flex" @click="importModalClick">
        <div v-if="uploadValue" class="flex-1 truncate">{{ fileNameValue }}</div>
        <div v-else class="flex-1">点此上传文件</div>
        <div v-if="uploadValue" class="text-hover" @click.stop="previewClick">预览文件</div>
    </div>

    <!-- 上传 -->
    <hc-new-dialog v-model="importModal" :loading="uploadDisabled" save-text="确认上传" title="上传文件" widths="38rem" @close="importModalClose" @save="importModalYesClick">
        <el-upload
            ref="uploadRef" :accept="accept" :action="api + action" :auto-upload="false"
            :before-upload="beforeUpload" :data="uploadData" :disabled="uploadDisabled"
            :headers="getTokenHeader()" :limit="1"
            :on-change="uploadChange"
            :on-error="uploadError" :on-exceed="uploadExceed" :on-progress="uploadprogress"
            :on-success="uploadSuccess" :show-file-list="false" class="hc-upload-border approach" drag
        >
            <div v-loading="uploadDisabled" class="hc-upload-loading upload-file-info" element-loading-text="上传中...">
                <template v-if="uploadFileInfo?.name">
                    <HcIcon class="upload-file-icon" name="file-text" />
                    <div class="upload-file-name">{{ uploadFileInfo?.name }}</div>
                </template>
                <template v-else>
                    <HcIcon class="upload-icon" name="upload-cloud" />
                    <div class="el-upload__text">拖动文件到这里 或 <em>点击这里选择文件</em> 并上传</div>
                </template>
            </div>
            <template #tip>
                <div class="el-upload__tip">允许格式：{{ formatTip }}， 文件大小 小于 {{ size }}MB</div>
            </template>
        </el-upload>
    </hc-new-dialog>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { getTokenHeader } from '~src/api/request/header'
import { isFileSize } from 'js-fast-way'
import { genFileId } from 'element-plus'

const props = defineProps({
    modelValue: {
        type: String,
        default: '',
    },
    datas: {
        type: Object,
        default: () => ({}),
    },
    action: {
        type: String,
        default: 'upload-file',
    },
    accept: {
        type: String,
        default: 'image/png,image/jpg,image/jpeg,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,application/pdf,.doc,.docx,application/msword',
    },
    size: {
        type: Number,
        default: 20,
    },
    formatTip: {
        type: String,
        default: 'png/jpg/jpeg/excel/pdf/doc/docx',
    },
    fileName:{
        type: String,
        default: '',
    },

})

//事件
const emit = defineEmits(['progress', 'change', 'update:modelValue'])
//变量
const uploadRef = ref(null)
const uploadData = ref(props.datas)
const uploadFileInfo = ref({})
const uploadDisabled = ref(false)
const uploadValue = ref(props.modelValue)
const fileNameVal = ref(props.fileName)
const api = '/api/blade-resource/oss/endpoint/'

//监听
watch(() => [
    props.datas,
    props.modelValue,
    props.fileName,

], ([datas, val, name]) => {
    uploadData.value = datas
    uploadValue.value = val
    // getFileName(val)
    fileNameVal.value = name
})

onMounted(() => {
    // getFileName(props.modelValue)

    fileNameValue.value = fileNameVal.value
})

//上传弹窗
const importModal = ref(false)
const importModalClick = () => {
    importModal.value = true
}

//确认上传
const importModalYesClick = () => {
    uploadRef.value?.submit()
}

//关闭上传
const importModalClose = () => {
    uploadRef.value?.clearFiles()
    importModal.value = false
}

//获取文件名
const fileNameValue = ref('')
const getFileName = (url) => {
    if (url) {
        let num = url.lastIndexOf('/') + 1
        fileNameValue.value = url.substring(num)
    } else {
        fileNameValue.value = ''
    }
}


//上传前
const beforeUpload = async (file) => {
    if (isFileSize(file?.size, props.size)) {
        return true
    } else {
        window?.$message?.warning('文件大小, 不能过' + props.size + 'M!')
        return false
    }
}

//超出限制时
const uploadExceed = (files) => {
    uploadRef.value?.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadRef.value?.handleStart(file)
}

//上传中
const uploadprogress = () => {
    uploadDisabled.value = true
    emit('progress', true)
}

//上传完成
const uploadSuccess = ({ code, data }) => {
    uploadDisabled.value = false
    emit('progress', false)
    // const pdfUrl = data?.pdfUrl ?? ''
    const pdfUrl = data
    if (code === 200 && pdfUrl) {
        uploadValue.value = pdfUrl
        window?.$message?.success('上传成功')
        importModal.value = false
        // getFileName(pdfUrl)
        fileNameValue.value = data?.originalName
        //事件
        emit('update:modelValue', data?.pdfUrl)
        emit('change', data?.pdfUrl)

    } else {
        window?.$message?.error('上传失败')
    }
}

//上传失败
const uploadError = () => {
    uploadDisabled.value = false
    emit('progress', false)
    window?.$message?.error('上传失败')
}

//文件改变时
const uploadChange = (file) => {
    uploadFileInfo.value = file
}

//预览文件
const previewClick = () => {
    const pdfUrl = uploadValue.value ?? ''
    if (pdfUrl) window.open(pdfUrl, '_blank')
}
</script>

<style lang="scss">
.hc-upload-border.approach {
    .el-upload-dragger {
        padding: 24px;
    }
    .hc-upload-loading.upload-file-info {
        .hc-icon-i {
            font-size: 40px;
        }
        .upload-icon {
            color: var(--el-text-color-placeholder);
        }
        .upload-file-icon {
            color: var(--el-color-primary-light-5);
        }
        .el-upload__text {
            margin-top: 10px;
        }
        .upload-file-name {
            margin-top: 10px;
            font-size: 14px;
            text-align: center;
            color: var(--el-color-primary);
        }
    }
    .el-upload__tip {
        font-size: 14px;
        margin-top: 16px;
        color: var(--el-text-color-placeholder);
    }
}
</style>
