<style lang="less" scoped>
    @import './ImportStudent.less';
</style>
<style lang="less">
    @import './IImportStudent.less';
</style>
<template>
    <div class="content">
        <div v-if="!file">
            <Upload action="" :before-upload="handleBeforeUpload" accept=".xls, .xlsx" :show-upload-list="false">
                <Icon type="ios-folder" color="#606060" size="200" style="margin-top:60px;cursor:pointer;" @click="openUploadFile" />
            </Upload>
            <p class="import-tips" style="margin-top:40px;">{{$t('stuAccount.importTips1')}}</p>
            <p class="import-tips">{{$t('stuAccount.importTips2') + $t('stuAccount.importTips3')}}</p>
            <a style="margin-top:10px;color:turquoise;display:inline-block;" href="https://teammodelstorage.blob.core.chinacloudapi.cn/teammodelcontest/20191107/%E5%AD%A6%E7%94%9F%E8%B4%A6%E5%8F%B7%E5%90%8D%E5%8D%95%20%E2%80%94%E6%AD%A3%E7%A1%AE%E6%95%B0%E6%8D%AE.xlsx">(下载名单模板)</a>
        </div>
        <div class="form-body" style="background:none;" v-else>
            <div class="ivu-upload-list-file">
                <Icon type="ios-stats"></Icon>
                {{ file.name }}
                <Icon v-show="showRemoveFile" type="ios-close" class="ivu-upload-list-remove" @click.native="handleRemove()"></Icon>
            </div>
            <div class="table-info">
                <div class="table-info-item">
                    <span class="table-info-label">{{$t('stuAccount.importInfo1')}}</span>
                    <span class="table-info-num">{{totalNum}}</span>
                </div>
                <div class="table-info-item" v-if="excelFiledNum != 0">
                    <span class="table-info-label">{{$t('Excel欄位有缺：')}}</span>
                    <span class="table-info-num">{{ excelFiledNum }}</span>
                </div>
                <div class="table-info-item" v-if="repeatNum != 0">
                    <span class="table-info-label">{{$t('stuAccount.importInfo2')}}</span>
                    <span class="table-info-num">{{repeatNum}}</span>
                </div>
                <div class="table-info-item" v-if="seatRepeatNum != 0">
                    <span class="table-info-label">{{$t('stuAccount.importInfo3')}}</span>
                    <span class="table-info-num">{{seatRepeatNum}}</span>
                </div>
                <div class="table-info-item" v-if="noClassroomNum != 0">
                    <span class="table-info-label">{{$t('stuAccount.importInfo4')}}</span>
                    <span class="table-info-num">{{noClassroomNum}}</span>
                </div>
                <div class="table-info-item" v-if="noSeatNoNum != 0">
                    <span class="table-info-label">{{$t('沒有座號：')}}</span>
                    <span class="table-info-num">{{noSeatNoNum}}</span>
                </div>
            
                <div class="table-info-item" v-if="existNum != 0">
                    <span class="table-info-label">{{$t('stuAccount.importInfo5')}}</span>
                    <span class="table-info-num">{{existNum}}</span>
                </div>
                <div class="table-info-item" style="display:none;">
                    <span class="table-info-label">{{$t('stuAccount.importInfo6')}}</span>
                    <span class="table-info-num">{{totalNum - repeatNum - existNum}}</span>
                </div>
                <!--<div class="table-info-item">
                  <Icon type="md-trash" size="18" color="white" @click="initUpload" />
                </div>-->
            </div>
            <Table :row-class-name="rowClassName" :columns="tableTitle" :data="tableData" :loading="tableLoading" height="560" style="margin-top:15px; " @on-select="getSelectInfo" @on-select-cancel="getSelectInfo" @on-select-all="getSelectInfo" @on-select-all-cancel="cancelAll">
                <template slot-scope="{ row,index }" slot="pw">
                    <p>{{(row.pw == '' || row.pw == null)? '— —' : row.pw+''}}</p>
                </template>
                <template slot-scope="{ row,index }" slot="status">
                    <!-- Excel 錯誤 -->
                    <p :class="(excelValid.fieldIds.length == 0 || excelValid.fieldIds.indexOf(row.id) == -1) ? 'account-success-tips':'account-warning-tips'">{{(excelValid.fieldIds.length == 0 || excelValid.fieldIds.indexOf(row.id) == -1)?"":"警告：Excel 內欄未完整！" }}</p>
                    <p :class="(excelValid.noReaptIds.length == 0 || excelValid.noReaptIds.indexOf(row.id) == -1) ? 'account-success-tips':'account-warning-tips'">{{(excelValid.noReaptIds.length == 0 || excelValid.noReaptIds.indexOf(row.id) == -1)?"":"警告：Excel 內的座位号重覆！" }}</p>
                    <p :class="(excelValid.reaptIds.length == 0 || excelValid.reaptIds.indexOf(row.id) == -1) ? 'account-success-tips':'account-warning-tips'">{{(excelValid.reaptIds.length == 0 || excelValid.reaptIds.indexOf(row.id) == -1)?"":"警告：Excel 內账号重复！" }}</p>
                    <p :class="row.seatRepeat? 'account-error-tips':''">{{row.seatRepeat ? "错误：座位号已在校內重复":"" }}</p>
                    <!-- 
                    <p :class="(repeatAccounts.length == 0 || repeatAccounts.indexOf(row.id) == -1) ? 'account-success-tips':'account-error-tips'">{{(repeatAccounts.length == 0 || repeatAccounts.indexOf(row.id) == -1)?"":"错误：账号重复或已存在学校里！" }}</p>
                    <p :class="(row.classId == '' || row.classId == null) ? 'account-warning-tips':''">{{(row.classId == '' || row.classId == null)?"警告 ：未找到指定班级":"" }}</p>
                    
                    <p :class="(row.no == '' || row.no == null) ? 'account-warning-tips':''">{{(row.no == '' || row.no == null)?"警告 ：沒有座號":"" }}</p> -->

                </template>
            </Table>
            <p style="margin-top:15px;">{{$t('stuAccount.passwordTips')}}</p>
            <Button class="confirm-btn" :class=" isError == 0 ?'confirm-btn-active':''  " :loading="uploadLoading" @click="saveFileData">
                {{$t('stuAccount.submitList')}}
            </Button>
        </div>
    </div>
</template>
<script>
    import excel from '../../utils/excel'
    import {  mapGetters } from 'vuex'
    export default {
        props: {
            isShow: {
                type: Boolean,
                default: false
            },
            schoolCode: {
                type: String,
                default: ''
            },
            academicYear: {
                type: Number,
            }
        },
        data() {
            return {
                // Excel 檢核
                excelValid:{
                    fieldIds: [],
                    noReaptIds: [],
                    reaptIds: []
                },
                totalNum: 0,
                seatRepeatNum: 0,
                repeatNum: 0,
                excelFiledNum: 0,

                existNum: 0,
                repeatAccounts: [],
                noClassroomNum: 0,
                noSeatNoNum: 0,
                uploadLoading: false,
                progressPercent: 0,
                showProgress: false,
                showRemoveFile: false,
                selectionData: [],
                file: null,
                tableData: [],
                tableTitle: [],
                tableLoading: false,
                systemColumn: [
                    'id',
                    'pw',
                    'name',
                    'className',
                    'classId',
                    'no'
                ]
            }
        },
        components: {
        },
        computed: {
            ...mapGetters({
                students: 'schoolBaseInfo/getStudent', // 學生List
            }),
            isError() {
                // return this.seatRepeatNum + this.repeatNum + this.existNum + this.noClassroomNum + this.noSeatNoNum
                return this.repeatNum + this.seatRepeatNum + this.excelFiledNum
            },
            show: {
                get() {
                    return this.isShow
                },
                set(value) {
                }
            }
        },
        watch: {
        },
        methods: {
            getSelectInfo() {

            },
            cancelAll() {

            },
            rowClassName(row, index) {
                let className = ''

                if( this.excelValid.fieldIds.indexOf(row.id) >= 0 || this.excelValid.noReaptIds.indexOf(row.id) >= 0 || this.excelValid.reaptIds.indexOf(row.id) >= 0){
                    className = className + 'account-warning-row-bg'
                } else {
                    if (!(this.repeatAccounts.length == 0 || this.repeatAccounts.indexOf(row.id) == -1) || row.seatRepeat) {
                        className = className + 'account-error-row-bg '
                    }
                    if (row.classId == '' || row.classId == null || row.no == '' || row.no == null) {
                        className = className + 'account-warning-row-bg'
                    }
                }
                return className
            },
            cancelUploadFile() {
                this.file = null
            },
            initUpload() {
                this.file = null
                this.showProgress = false
                this.tableData = []
            },
            openUploadFile() {
                this.initUpload()
            },
            handleRemove() {
                this.initUpload()
                this.$Message.info(this.$t('stuAccount.importTips4'))
            },
            handleBeforeUpload(file) {
                const fileExt = file.name.split('.').pop().toLocaleLowerCase()
                if (fileExt === 'xlsx' || fileExt === 'xls') {
                    this.readFile(file)
                    this.file = file
                } else {
                    this.$Notice.warning({
                        title: this.$t('stuAccount.importTips5'),
                        desc: this.$t('stuAccount.importTips6') + file.name + this.$t('stuAccount.importTips7')
                    })
                }
                return false
            },
            // 读取文件
            readFile(file) {
                this.tableLoading = true
                const reader = new FileReader()
                reader.readAsArrayBuffer(file)
                reader.onloadstart = e => {
                    this.showProgress = true
                }
                reader.onprogress = e => {
                    this.progressPercent = Math.round(e.loaded / e.total * 100)
                }
                reader.onerror = e => {
                    this.$Message.error(this.$t('stuAccount.importTips8'))
                }
                reader.onload = e => {
                    const data = e.target.result
                    const { header, results } = excel.read(data, 'array')
                    const tableColumn = header.map(item => { return { title: item, key: item } })
                    const columns = tableColumn.map(item => {
                        return item.key
                    })
                    const columnStr = columns.join('')
                    let flag = true
                    let column = ''
                    for (let item of this.systemColumn) {
                        let f = 0
                        for (let i of columns) {
                            if (i == item) {
                                f = 1
                                break
                            }
                        }
                        if (f == 0) {
                            column = item
                            flag = false
                            break
                        }
                    }
                    if (flag) {
                        // 处理表格导入数据类型
                        this.tableData = results.filter(item => {
                            let arr = item.id.split('#')
                            if (arr.length == 2) {
                                for (let i of this.systemColumn) {
                                    if (i != 'no') {
                                        if (typeof item[i] === 'number') {
                                            item[i] = item[i] + ''
                                        }
                                        if (item.pw == undefined) {
                                            item.pw = arr[1]
                                        }
                                    }
                                }
                            } else {
                                item._disabled = true
                            }
                            return item
                        })

                        // 給予Excel 總數
                        this.totalNum = this.tableData.length

                        // 檢核現在的Excel 邏輯
                        let excelFlag = this.validExcel(this.tableData)

                        // Excel 檢核通過再網下檢核
                        if(excelFlag){
                            // 先歸零
                            this.errNumReset()

                            // 修改與新增的學生檢核
                            this.tableData.forEach( (item, index, array) => {
                                
                                // 檢查座號是否與校內的衝突
                                let studdd = this.students.some( (studInfo, index) => {
                                    return (item.classId == studInfo.classId && item.no == studInfo.no)
                                })
                                if(studdd) {
                                    item.seatRepeat = true
                                    this.seatRepeatNum++
                                }

                            })
                            
                            //整理TtableData
                            this.tableData.map((item, index) => {
                                if(item.pw == undefined || item.pw == null || item.pw == '') item.pw = item.id
                                item['classroom'] = {}
                                item.classroom.classId = item.classId
                                item.classroom.className = item.className
                                item.year = this.academicYear ? this.academicYear.toString() : ''
                                item.no = item.no ? item.no.toString() : ''
                                return item
                            })
                        }


                        // // 计算重复账号数量和重复账号,过滤重复账号
                        // this.totalNum = this.tableData.length
                        // // 取得Excel 全部的ID
                        // let accounts = this.tableData.map(item => { return item.id })
                        // // 合併
                        // let cocatIds = studIDs.concat(accounts);
                        // this.repeatAccounts = cocatIds.filter((item, index, self) => self.indexOf(item) != index)
                        // this.repeatAccounts = this.repeatAccounts.filter((item, index, self) => self.indexOf(item) === index)

                        // // 直接过滤重复账号
                        // // this.tableData = this.tableData.filter((item, index, self) => {
                        // //  if (accounts.indexOf(item.account) === index) {
                        // //    return 1;
                        // //  } else {
                        // //    return 0;
                        // //  }
                        // // });
                        // accounts = accounts.filter((item, index, self) => self.indexOf(item) === index)
                        // this.repeatNum = this.totalNum - accounts.length + this.repeatAccounts.length

                        // // 根据班级Code GroupBy,判断班级座位号是否重复
                        // let classStu = this.groupBy(this.tableData, 'classId')

                        // for (let item of classStu) {
                        //     let seatNoArr = item.map(item => { return item.no })
                        //     for (let index in item) {
                        //         let flag = seatNoArr.indexOf(item[index]['no'])
                        //         if (flag != index) {
                        //             let tableIndex = this.getIndex(this.tableData, item[flag])
                        //             if (this.tableData[tableIndex].seatRepeat != true) {
                        //                 this.seatRepeatNum++
                        //                 this.tableData[tableIndex].seatRepeat = true
                        //             }
                        //             tableIndex = this.getIndex(this.tableData, item[index])
                        //             this.tableData[tableIndex].seatRepeat = true
                        //             this.seatRepeatNum++
                        //         }
                        //     }
                        // }
                        // // 筛选没有班级账号
                        // let noRoom = this.tableData.filter(item => { return (item.classId == '' || item.classId == null) })
                        // this.noClassroomNum = noRoom.length

                        // // 筛选沒有座號
                        // let noSeatNo = this.tableData.filter(item => { return (item.no == '' || item.no == null) })
                        // this.noSeatNoNum = noSeatNo.length

                        // //整理TtableData
                        // this.tableData.map((item, index) => {
                        //     if(item.pw == undefined || item.pw == null || item.pw == '') item.pw = item.id
                        //     item['classroom'] = {}
                        //     item.classroom.classId = item.classId
                        //     item.classroom.className = item.className
                        //     item.year = this.academicYear ? this.academicYear.toString() : ''
                        //     item.no = item.no ? item.no.toString() : ''
                        //     return item
                        // })

                        // // 檢查與現在的學生名單同教室裡是否有重複座號
                        // this.tableData.forEach( (item) => {
                        //     let studdd = this.students.filter( (studInfo) => {
                        //         return (item.classId == studInfo.classId && item.no == studInfo.no)
                        //     })
                        //     if(studdd.length > 0) {
                        //         item.seatRepeat = true
                        //         this.seatRepeatNum++
                        //     }
                        // })
                        
                        this.$Message.info(this.$t('stuAccount.importTips11'))
                        this.tableLoading = false
                    } else {
                        this.$Message.error({
                            content: this.$t('stuAccount.importTips9') + column + this.$t('stuAccount.importTips10'),
                            duration: 4
                        })
                        this.tableLoading = false
                    }
                    this.showRemoveFile = true
                }
            },
            groupBy(array, key) {
                const groups = {}
                array.forEach(function (item) {
                    const group = JSON.stringify(item[key])
                    groups[group] = groups[group] || []
                    groups[group].push(item)
                })
                return Object.keys(groups).map(function (group) {
                    return groups[group]
                })
            },
            /*
            *获取对象在对象数组的中index
            */
            getIndex(_arr, _obj) {
                var len = _arr.length
                for (let i = 0; i < len; i++) {
                    if (this.isObjEqual(_arr[i], _obj)) {
                        return parseInt(i)
                    }
                }
                return -1
            },

            /*
            * 判断两个json对象是否相同
            */
            isObjEqual(o1, o2) {
                var props1 = Object.keys(o1)
                var props2 = Object.keys(o2)
                if (props1.length != props2.length) {
                    return false
                }
                for (var i = 0, max = props1.length; i < max; i++) {
                    var propName = props1[i]
                    if (o1[propName] !== o2[propName]) {
                        return false
                    }
                }
                return true
            },
            saveFileData() {
                if (this.isError == 0) {
                    this.uploadLoading = true
                    //整理TtableData
                    let temp = this.tableData.map((item) => {
                        item.classNo = item.classId
                        return item
                    })
                    this.$api.stuAccount.ImportStudent(this.schoolCode, temp).then(
                        (res) => {
                            if (res.error == null) {
                                this.$emit('importStudentInfo', res.students)
                                this.$Message.info(this.$t('匯入成功'))
                                this.initData()
                                this.uploadLoading = false
                            } else {
                                this.$Message.error('API error!')
                            }
                        },
                        (err) => {

                        }
                    )
                } else {
                    this.$Message.error(this.$t('stuAccount.importTips12'))
                }
            },
            cancel() {
                this.initData()
                this.$emit('importStudentInfo', {
                    data: []
                })
            },
            initData() {
                this.totalNum = 0
                this.repeatNum = 0
                this.existNum = 0
                this.seatRepeatNum = 0
                this.repeatAccounts = []
                this.noClassroomNum = 0
                this.noSeatNoNum = 0
                this.uploadLoading = false
                this.progressPercent = 0
                this.showProgress = false
                this.showRemoveFile = false
                this.file = null
                this.tableData = []
                this.tableTitle = [
                    {
                        type: 'selection',
                        width: 80,
                        align: 'center'
                    },
                    {
                        title: this.$t('stuAccount.seatNo'),
                        key: 'no',
                        width: 80
                    },
                    {
                        title: this.$t('stuAccount.account'),
                        key: 'id'
                    },
                    {
                        title: this.$t('stuAccount.password'),
                        slot: 'pw'
                    },
                    {
                        title: this.$t('stuAccount.stuName'),
                        key: 'name'
                    },
                    {
                        title: this.$t('stuAccount.classroomName'),
                        key: 'className'
                    },
                    {
                        title: this.$t('stuAccount.classroomCode'),
                        key: 'classId'
                    },
                    {
                        title: this.$t('stuAccount.abnormalStatus'),
                        slot: 'status'
                    }
                ]
            },
            validExcel(data){
                let _this = this
                var excelData = data
                let validFalg = false

                // 先歸零
                this.errNumReset()

                excelData.forEach( (item, index, array) => {
                    // 座號、ID、教室ID、教室名稱必填
                    if(item.no == '' || item.no == null || item.id == '' || item.id == null || item.classId == '' || item.classId == null || item.className == '' || item.className == null) {
                        _this.excelValid.fieldIds.push(item.id)
                        _this.excelFiledNum++
                    }

                    // 座號重複檢核
                    let repNo = array.filter( (i) => {
                        return i.id != item.id && i.classId != undefined && i.classId != null && i.classId != '' && i.classId == item.classId && i.no == item.no 
                    })
                    if(repNo.length > 0){
                        for( let no of repNo) {
                            _this.excelValid.noReaptIds.push(no.id)
                            _this.seatRepeatNum ++
                            validFalg = true
                        }
                    }

                    // ID 重複
                    let repID = array.filter( (i, key) => {
                        return i.id == item.id && index != key
                    })
                    if(repID.length > 0){
                        for( let id of repID) {
                            _this.excelValid.reaptIds.push(id.id)
                            _this.repeatNum ++
                            validFalg = true
                        }
                    }
                })

                if( (_this.excelValid.noReaptIds.length + _this.excelValid.fieldIds.length + _this.excelValid.reaptIds.length) == 0){
                    validFalg = true
                }
                return validFalg
            },
            errNumReset(){
                this.repeatNum = 0 // 帳號重複
                this.seatRepeatNum = 0 // 座號重複
                this.excelFiledNum = 0 // Excel 欄位空白檢核
            }
        },
        created() {
            this.initData()
        },
        mounted() {
        },
        watch: {
            
        }
    }
</script>
