<template>
    <div>
        <!-- 导入excel模板 -->
        <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :title="title" :visible.sync="open"
            width="400px" @close="close" append-to-body>

            <el-button style="margin-bottom:10px" v-if="downloadArr && downloadArr.length>0" type="primary" @click="downloadExcelTemplate">{{$t('template.common.downloadTemplate') }}</el-button>

            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :disabled="upload.isUploading" action=""
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件</span>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">{{ $t('form.cancel') }}</el-button>
                <el-button type="primary" @click="save">{{ $t('form.confirm') }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import * as XLSX from 'xlsx'
export default {
    name: "ImportEccelDialog",
    components: {},
    props:{
        downloadArr:{
            type:Array,
            default(){
                return []
            }
        }
    },
    data() {
        return {
            title: this.$t('form.modify'),
            open: false,
            upload: {
                // 是否禁用上传
                isUploading: false,
            },
            excelData: null,
        }
    },
    computed: {
    },
    created() {
    },
    methods: {
        show() {
            this.open = true
        },
        cancel() {
            this.open = false
        },
        close() {
            if (!this.isChecked) {
                this.$emit('cancel')
            }
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.open = false
            this.upload.isUploading = false
            this.$refs.upload.clearFiles()
        },
        // 提交上传文件
        save() {
            const file = this.$refs.upload.uploadFiles
            if (!file || file.length === 0 || !file[0].name.toLowerCase().endsWith('.xls') && !file[0].name.toLowerCase().endsWith('.xlsx')) {
                this.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
                return
            }

            const reader = new FileReader()
            reader.onload = (event) => {
                try {
                    const data = event.target.result
                    // 解析 Excel
                    const workbook = XLSX.read(data, { type: 'binary' })
                    // 获取第一个工作表
                    const firstSheetName = workbook.SheetNames[0]
                    const worksheet = workbook.Sheets[firstSheetName]
                    // 转为二维数组（header:1 表示保留原始行列）
                    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
                    this.excelData = jsonData
                    this.$emit('onLoadData', this.excelData)
                    this.$refs.upload.handleRemove(file)
                } catch (error) {
                    console.error('解析失败：', error)
                    this.$modal.msgError('文件解析失败，请检查格式', error)
                }
            }

            reader.readAsArrayBuffer(file[0].raw);
        },
        downloadExcelTemplate() {
            this.$emit('downloadExcelTemplate',this.downloadArr)
		},

    }
}
</script>
