<template>
    <div>
        <Upload
            type="drag"
            accept=".xls,.xlsx"
            :format="['xls','xlsx']"
            :on-format-error="handleFormatError"
            :before-upload="beforeUpload"
            style="height:290px"
            action="">
            <div style="height:280px;padding: 20px 0">
                <Icon type="ios-cloud-upload" size="52" style="margin-top: 80px;color: #3399ff"></Icon>
                <p>点击或拖拽文件到此处上传</p>
            </div>
        </Upload>
        <div class="file-name" v-show="file">
            <Icon class="file-name-del" @click="del" type="md-close" color="red"/>
            <span>{{file.name}}</span>
        </div>
    </div>
</template>
<script>
import XLSX from 'xlsx'
export default {
    name: 'UploadIndex',
    data () {
        return {
            file: ''
        }
    },

    methods: {
        handleFormatError(file) {
            this.$Notice.warning({
                title: '提示',
                desc: '只能上传Excel文件'
            })
        },

        beforeUpload (file) {
            this.file = file
            
            const fileReader = new FileReader()
            fileReader.onload = ev => {
                const data = ev.target.result
                
                const workbook = XLSX.read(data, {
                    type: 'binary'
                })
                const wsname = workbook.SheetNames[0] //取第一张表
                const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) //生成json表格内容
                
                this.$emit('on-before-upload', file, ws)
                this.$emit('on-change-index', 0)
            }
            fileReader.readAsBinaryString(file)
            return false
        },

        del () {
            this.file = ''
            this.$emit('on-change-index', -1)
        }
    }
}
</script>
<style lang="less" scoped>
.file-name {
    display: flex;
    align-items: center;

    &-del {
        margin-right: 10px;
        cursor: pointer;
    }
}
</style>
