<template>
    <div class="importCourseWrap">
        <div class="importArea" v-if="tableList.length == 0">
            <el-form ref="form" :model="excelForm" :rules="excleRules" label-width="150px">
                <el-form-item label="请选择班级" prop="className">
                    <el-select v-model="excelForm.className" filterable placeholder="请选择">
                        <el-option v-for="item in classList" :key="item.trainClassId" :label="item.trainClassName"
                            :value="item.trainClassId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="请上传excel" prop="excelFile">
                    <el-upload class="upload-demo" drag action="#" :file-list="fileList" :before-upload="beforeUpload"
                        :show-file-list="false" :on-remove="handleRemove">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">只能上传excel、xlsx文件，且不超过500kb</div>
                    </el-upload>
                    <div>{{ excelForm.excelFile }}</div>

                </el-form-item>
            </el-form>
            <div style="text-align: center;">
                <el-button @click="parseExcel(file)" type="primary"
                    :disabled="(excelForm.className == '' || excelForm.excelFile == '')">确认上传{{ excelForm.className &&
                        excelForm.excelFile }}</el-button>
            </div>
        </div>
        <div v-else>
            <el-table height="800px" :data="tableList" style="width: 100%">
                <el-table-column prop="courseName" label="课堂名称" width="width"></el-table-column>
                <el-table-column prop="courseTime" label="上课时间" width="width"></el-table-column>
                <el-table-column prop="dateTime" label="下课时间" width="width"></el-table-column>
                <el-table-column prop="instructor" label="老师" width="width"></el-table-column>
                <el-table-column prop="isPay" label="是否付款" width="width"></el-table-column>
                <el-table-column prop="remark" label="备注" width="width"></el-table-column>
                <el-table-column prop="title" label="职称" width="width"></el-table-column>
                <el-table-column prop="url" label="链接" width="width"></el-table-column>
                <el-table-column>
                    <template slot-scope="scope">
                        <el-button type="text" @click="dialogVisible = true" size="mini">编辑</el-button>
                        <el-button type="text" size="mini" @click="delRow(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: center;margin: 10px 0;">
                <el-button type="primary" @click="tableList = []">重新上传</el-button>
                <el-button type="primary" @click="submit">确定提交</el-button>
            </div>
        </div>
        <el-dialog title="编辑" :visible.sync="dialogVisible" width="width">
            <div>
                <el-form ref="form" :model="form" label-width="80px">
                    <el-form-item label="1">
                        <el-input placeholder=""></el-input>
                    </el-form-item>
                    <el-form-item label="2">
                        <el-input placeholder=""></el-input>
                    </el-form-item>
                    <el-form-item label="3">
                        <el-input placeholder=""></el-input>
                    </el-form-item>
                    <el-form-item label="4">
                        <el-input placeholder=""></el-input>
                    </el-form-item>
                    <el-form-item label="5">
                        <el-input placeholder=""></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    getClassList,
} from '@/api/trainService/index'
const keyMap = {
    '上课时间': 'courseTime',
    '下课时间': 'dateTime',
    '备注': 'remark',
    '授课内容': 'contend',
    '授课老师': 'instructor',
    '是否付费': 'isPay',
    '职称': 'title',
    '课堂名称': 'courseName',
    '课程链接': 'url',
}
export default {
    created() {
        this.init()
    },
    data() {
        return {
            excelForm: {
                className: '',
                excelFile: ''
            },
            classList: [],
            excleRules: {
                className: [{ required: true, message: '请选择班级', trigger: 'blur' }],
                excelFile: [{ required: true, message: '请上传excel文件', trigger: 'change' }],
            },
            fileList: [],
            tableList: [],
            file: '',
            newFile: new FormData(),
            dialogVisible: false
        }
    },
    methods: {
        async init() {
            const res = await getClassList()
            this.classList = res.data
        },
        beforeUpload(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.newFile.append('file', file); //  2. 上传之前，拿到file对象，并将它添加到刚刚定义的FormData对象中。 
            this.file = file
            this.excelForm.excelFile = file.name
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        product(outdata, loading) {
            const result = outdata.reduce((pre, cur, index) => {
                const obj = {}
                Object.keys(cur).forEach(key => {
                    console.log(key);
                    if (keyMap[key]) {
                        obj[keyMap[key]] = cur[key]
                    } else {
                        
                    }
                })
                pre.push(obj)
                return pre
            }, [])
            this.tableList = result
            console.log(result);

            console.log(outdata);
            loading.close()
        },
        parseExcel(file) {
            const loading = this.$loading({
                lock: true,
                text: '解析中',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            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]])
                _this.product(outdata, loading)
            }
        },
        delRow(row) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$message({
                    type: 'success',
                    message: '删除成功'
                });
            })
        },
        submit() {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$message.success('修改成功')
                this.$router.push('/courseManage')
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }
    }
}
</script>

<style lang="scss" scoped>
.importCourseWrap {
    .importArea {
        width: 500px;
        margin: 200px auto;
    }
}
</style>