<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('试题导入')" />
    <th:block th:include="include :: element-css" />
</head>
<body class="white-bg" style="text-align: center;position: relative">
<div class="wrapper wrapper-content animated fadeInRight ibox-content" id="app">
    <el-row>
        <el-button type="primary" plain icon="el-icon-upload" @click="chooseFile()">导入文件</el-button>
        <el-button type="warning" plain icon="el-icon-download" @click="downloadTemplate()">下载导入模板</el-button>
        <input ref="upFile" class="file" name="file" type="file" style="display: none" @change="doImport">
    </el-row>
    <el-row>
        <div style="color: red;height: 30px;line-height: 30px;">
            提示：请下载导入模板（试题导入模板.xlsx），</br> 按照模板要求填写后导入。
        </div>
    </el-row>
    <el-row style="margin-top: 20px">
        <div>
            <span v-for="(file, index) in fileList" :key="index" style="margin-right: 10px">
                {{file.name}}
                <el-button type="text" @click="deleteFile(index)">删除</el-button>
            </span>
        </div>
    </el-row>
    <el-row style="position: absolute;top: 200px;right: 38px;">
        <el-button type="primary" icon="el-icon-check" @click="save()">确认上传</el-button>
        <el-button type="info" icon="el-icon-back" @click="canle()">取消</el-button>
    </el-row>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: element-js" />
<script th:inline="javascript">
    var prefix = ctx + "system/qu";
    // 请求实例
    const instance = axios.create({
        baseURL: ctx,
        timeout: 60000
    })
    var app = new Vue({
        el: '#app',
        data: {
            importVisible:false,
            fileList:[]
        },
        mounted(){

        },
        methods: {
            toImport(){
                this.importVisible = true
            },
            // 只是为了美化一下导入按钮
            chooseFile: function() {
                this.$refs.upFile.dispatchEvent(new MouseEvent('click'))
            },
            downloadTemplate() {
                // 创建一个隐藏的<a>标签
                var link = document.createElement('a');
                link.style.display = 'none';
                document.body.appendChild(link);
                link.setAttribute('href', '/file/试题导入模板.xlsx');
                link.setAttribute('download', '试题导入模板.xlsx');
                link.click();
                document.body.removeChild(link);
            },
            upload(url, file, data) {
                const formData = new FormData()
                formData.append('file', file)

                // 附加数据
                if (data) {
                    Object.keys(data).forEach((key) => {
                        formData.append(key, data[key])
                    })
                }
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                return new Promise((resolve, reject) => {
                    instance.request({
                        url: url,
                        method: 'post',
                        data: formData,
                        timeout: 1200000
                    }).then(response => {
                        loading.close();
                        console.log(response)
                        resolve(response)
                    }).catch(err => {
                        reject(err)
                    })
                })
            },
            importExcel(file) {
                return this.upload('system/qu/import', file)
            },
            deleteFile(index){
                this.fileList= []
            },
            doImport(e) {
                let file = e.target.files[0]
                if (!file.name.match(/\.(xls|xlsx)$/i)) {
                    // Display error message if the file extension is not .xls or .xlsx
                    this.$message.error('请选择Excel文件 (.xls, .xlsx)');
                    return;
                }
                this.fileList = e.target.files
            },
            save(){
                if(this.fileList.length === 0){
                    this.$message({
                        message: '请先选择文件！',
                        type: 'warning'
                    })
                    return false
                }
                let that = this
                this.importExcel(this.fileList[0]).then((res)=>{
                    console.log(res)
                    if (res.data.code !== 0) {
                        that.$alert(res.data.msg, '导入信息', {
                            dangerouslyUseHTMLString: true
                        })
                    } else {
                        that.$message({
                            message: '数据导入成功！',
                            type: 'success'
                        })
                        this.importVisible = false
                        this.successCallback(res)
                    }
                })
            },
            canle(){
                $.modal.close()
            },
            // 成功回调执行事件（父窗体静默更新）
            successCallback: function(result) {
                if (result.data.code == web_status.SUCCESS) {
                    var parent = activeWindow();
                    if ($.common.isEmpty(parent.table)) {
                        $.modal.msgSuccessReload(result.data.msg);
                    } else if (parent.table.options.type == table_type.bootstrapTable) {
                        $.modal.close();
                        parent.$.modal.msgSuccess(result.data.msg);
                        parent.$.table.refresh();
                    } else if (parent.table.options.type == table_type.bootstrapTreeTable) {
                        $.modal.close();
                        parent.$.modal.msgSuccess(result.data.msg);
                        parent.$.treeTable.refresh();
                    }
                } else if (result.data.code == web_status.WARNING) {
                    $.modal.alertWarning(result.data.msg)
                }  else {
                    $.modal.alertError(result.data.msg);
                }
                $.modal.closeLoading();
                $.modal.enable();
            },
        },
    });
    function submitHandler() {
        if ($.validate.form()) {
            $.operate.save(prefix + "/edit", $('#form-train-edit').serialize());
        }
    }
</script>
</body>
</html>
