<template>
    <el-upload class="upload-demo myupload" :action="action" :headers="headers" :on-preview="handlePreview"
        :on-remove="handleRemove" :before-remove="beforeRemove" :on-success="successUpload" :limit="3"
        :on-exceed="handleExceed" :before-upload="beforeAvatarUpload">
        <slot></slot>
    </el-upload>
</template>

<script>
import { mapGetters } from "vuex";
export default {
    data() {
        return {
            action: '/',
            name: ''
        };
    },
    computed: {
        ...mapGetters(['token']),
        headers() {
            return { Authorization: "Bearer " + this.token };
        },
    },
    methods: {
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        handleExceed(files, fileList) {

        },
        beforeRemove(file, fileList) {
            // return this.$confirm(`确定移除 ${file.name}？`);
        },
        successUpload(response) {
            console.log(response);
            this.$emit('upload', response, this.name)
        },
        beforeAvatarUpload(file, fileList) {
            this.name = file.name
            const filetype = file.name.slice(file.name.lastIndexOf('.', file.name.length))
            console.log(filetype);

            const isType = ['.excel', '.xlsx'].some(item => { return item == filetype })
            if (!isType) {
                this.$message.error('只能上传excel文件!');
                return false
            }
            this.parseExcel(file)
        },
        parseExcel(file) {
            let reader = new FileReader()
            let _this = this
            reader.readAsArrayBuffer(file)
            reader.onload = function () {
                let buffer = reader.result
                let bytes = new Uint8Array(buffer)
                let length = bytes.byteLength
                let binary = ''
                for (let i = 0; i < length; i++) {
                    binary += String.fromCharCode(bytes[i])
                }
                let XLSX = require('xlsx')
                let wb = XLSX.read(binary, {
                    type: 'binary'
                })
                let outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
                console.log(outdata)
            }
        }
    }
}
</script>

<style lang="scss">
.myupload .el-upload-list {
    display: none;
}
</style>