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

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

<script setup>
import {ref, watch, onMounted} 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: 200
    },
    formatTip: {
        type: String,
        default: "png/jpg/jpeg/excel/pdf/doc/docx"
    },
})

//变量
const uploadRef = ref(null)
const uploadData = ref(props.datas)
const uploadFileInfo = ref({})
const uploadDisabled = ref(false)
const uploadValue = ref(props.modelValue)

const api = '/api/blade-resource/oss/endpoint/';

//监听
watch(() => [
    props.datas,
    props.modelValue
], ([datas,val]) => {
    uploadData.value = datas
    uploadValue.value = val
    getFileName(val)
})

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

//事件
const emit = defineEmits(['progress', 'change', 'update:modelValue'])

//上传弹窗
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 ?? ''
    if (code === 200 && pdfUrl) {
        uploadValue.value = pdfUrl
        window?.$message?.success('上传成功');
        importModal.value = false
        getFileName(pdfUrl)
        //事件
        emit('update:modelValue', pdfUrl)
        emit('change', 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>
