<template>
    <el-upload ref="uploadRef" :on-preview="previewFile" :limit="1" :on-change="changeFile" :auto-upload="false" :data="uploadForm.data">
        <template #trigger>
            <el-button type="primary">选取文件</el-button>
        </template>
        <el-button style="margin-left: 10px;" type="success" @click="uploadParts">确认导入库存数据</el-button>
    </el-upload>
</template>
<script setup>
import store from '@/store'
import { ref, reactive } from 'vue';
import { uploadExcelParts } from '@/api/excel.js'
import { ElMessage } from 'element-plus'
import { sizeFormatter } from '@/utils/formatter.js'
const file = ref()
const uploadForm = reactive({
    data: {
        fileId: '',
        name: '',
        type: '',
        size: null
    }
})
const changeFile = (uploadFile) => {
    console.log('max: ' + sizeFormatter(1048576))
    file.value = uploadFile
    uploadForm.data = {
        fileId: file.value.raw.uid,
        name: file.value.raw.name,
        type: file.value.raw.type,
        size: sizeFormatter(file.value.raw.size),
        userName: store.getters.getUserName
    }
    console.log(uploadForm.data)
}
const uploadRef = ref()
const uploadParts = () => {
    
    if (uploadForm == undefined || file.value == undefined) {
        ElMessage.error('请选择文件之后再导入')
    }
    const jsonStr = JSON.stringify(uploadForm.data);
    const blob = new Blob([jsonStr], {
        type: 'application/json'
    });
    let formData = new FormData();
    // 这里很重要 file.value.raw才是真实的file文件，file.value只是一个Proxy代理对象
    formData.append("obj", blob);
    formData.append("file", file.value.raw);
    console.log(formData)
    uploadExcelParts(formData).then(res => {
        if (res.data.code == 0) {
            ElMessage({
                message: '导入成功',
                type: 'success',
            })
            // 清空选择的文件项
            uploadRef.value.clearFiles()
            file.value = undefined
        } else {
            ElMessage.error(res.data.message)
        }
    }).catch(err => {
        console.log(err)
        ElMessage.error('导入错误')
    })
}
const previewFile = () => {

}
</script>
<style scoped></style>