<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/download/%E5%AD%A6%E7%94%9F%E5%90%8D%E5%8D%95%E6%A8%A1%E5%9D%97.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('stuAccount.lackAttr')}}</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('stuAccount.noSetNo')}}</span>
                    <span class="table-info-num">{{noSeatNoNum}}</span>
                </div>
                <div class="table-info-item" v-if="gradeNum != 0">
                    <span class="table-info-label">{{$t('stuAccount.gradeErr')}}</span>
                    <span class="table-info-num">{{gradeNum}}</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 }" slot="classYear">
                    <p>{{ `${$jsFn.getGradeNameByYear(schoolBase, period, row.classYear)}(${row.classYear}级)` }}</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)?"" : $t('stuAccount.attrWarning') }}</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)?"":$t('stuAccount.setNoWarning') }}</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)?"": $t('stuAccount.idWarning') }}</p>
                    <p :class="row.seatRepeat? 'account-error-tips':''">{{row.seatRepeat ? $t('stuAccount.setNoErr'):"" }}</p>
                    <p :class="(excelValid.gradeIds.length == 0 || excelValid.gradeIds.indexOf(row.id) == -1) ? 'account-success-tips':'account-warning-tips'">{{(excelValid.gradeIds.length == 0 || excelValid.gradeIds.indexOf(row.id) == -1)?"": $t('stuAccount.gradeWarning') }}</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,
        },
        period: {
            type: String,
        }
    },
    data() {
        return {
            // Excel 檢核
            excelValid: {
                fieldIds: [],
                noReaptIds: [],
                reaptIds: [],
                gradeIds: []
            },
            totalNum: 0,
            seatRepeatNum: 0,
            repeatNum: 0,
            excelFiledNum: 0,
            gradeNum: 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', //班级编号 1,2,3（只能是数字）
                'no',
                'stuYear',//学生学级
                'classYear'//班级年级
            ]
        }
    },
    components: {
    },
    computed: {
        ...mapGetters({
            students: 'schoolBaseInfo/getStudent', // 學生List
            grades: 'user/getGrades', // 年級
            classes: 'user/getClasses', // 教室ID
        }),
        isError() {
            return this.repeatNum + this.seatRepeatNum + this.excelFiledNum + this.gradeNum
        },
        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 || this.excelValid.gradeIds.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('#') //账号id不用#
                        // if (arr.length == 2) {
                        for (let i of this.systemColumn) {
                            if (i != 'no') {
                                if (typeof item[i] === 'number') {
                                    item[i] = item[i] + ''
                                }
                                //表格保留pw栏位，如果没有设置则密码默认同账号id
                                // if (item.pw == undefined) {
                                //     item.pw = arr[1]
                                // }
                                item.pw = item.pw || item.id
                                // item.pw = item.id
                            }
                        }
                        // } else {
                        //     item._disabled = true
                        // }
                        return item
                    })

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

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

                    // Excel 檢核通過再和DATA比對
                    if (excelFlag) {
                        // 先歸零
                        this.errNumReset()

                        // 比較 students 取出已存在的教室內容
                        // 取出Excel重複的班級
                        let classIds = []
                        this.tableData.forEach((item) => {
                            if (classIds.indexOf(item.classId) < 0) { classIds.push(item.classId) }
                        })
                        // 先篩選出會被修改的學生
                        let updStuds = []
                        classIds.forEach((id) => {
                            let stud = this.students.filter((studInfo) => {
                                return (id == studInfo.classNo)
                            })

                            updStuds.push(...stud)
                        })

                        // 修改與新增的學生檢核
                        this.tableData.forEach((item, index, array) => {
                            // 檢查座號是否與校內的衝突
                            // 先抓教室座號是否與原教室座號重複
                            let repStud = updStuds.filter((studInfo) => {
                                return (item.classId == studInfo.classNo && item.no == studInfo.no)
                            })

                            if (repStud.length > 0) {
                                let isExistTable = array.some((a) => {
                                    return a.classId == repStud[0].classNo && a.id == repStud[0].id
                                })

                                if (!isExistTable) {
                                    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() : ''//通过表格汇入，不用从UI上面设置
                            item.year = item.stuYear
                            item.no = item.no ? item.no.toString() : ''
                            item.periodId = this.period
                            return item
                        })
                    }

                    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
            }
        },
        saveFileData() {
            if (this.isError == 0) {
                this.uploadLoading = true
                //整理TtableData
                let temp = this.tableData.map((item) => {
                    item.classNo = item.classId
                    item.year = parseInt(item.year)
                    item.classYear = parseInt(item.classYear)
                    delete item.classId
                    delete item.stuYear
                    delete item._disabled
                    delete item.schoolCode
                    delete item.classroom
                    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: '学级',
                    key: 'stuYear'
                },
                {
                    title: this.$t('stuAccount.classroomName'),
                    key: 'className'
                },
                {
                    title: '年级',
                    slot: 'classYear'
                },
                {
                    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 || item.gradeIndex == '' || item.gradeIndex == null) {
                if (!item.no || !item.id || !item.classId || !item.className) {
                    _this.excelValid.fieldIds.push(item.id)
                    _this.excelFiledNum++
                } else {
                    // 座號重複檢核
                    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++
                        }
                    }

                    // 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++
                        }
                    }

                    // 年級與教室的組合必須一致
                    let classInfo = _this.classes.filter((i) => {
                        return item.classId == i.no
                    })
                    if (classInfo.length > 0) {
                        let gradeID = ''
                        let data = _this.grades.filter((i) => {
                            return i.periodId == _this.period
                        })
                        if (data.length > 0 && data[item.gradeIndex - 1]) {
                            gradeID = data[item.gradeIndex - 1].id
                        }
                        // //不用设置年级，通过学级自动计算年级
                        // if(gradeID != classInfo[0].gradeId){
                        //     _this.excelValid.gradeIds.push(item.id)
                        //     _this.gradeNum++
                        // }
                    } else {
                        let data = array.filter((i) => {
                            return i.classId == item.classId && i.gradeIndex != item.gradeIndex
                        })

                        if (data.length > 0) {
                            _this.excelValid.gradeIds.push(item.id)
                            _this.gradeNum++
                        }
                    }
                }
            })

            if ((_this.excelValid.noReaptIds.length + _this.excelValid.fieldIds.length + _this.excelValid.reaptIds.length + _this.excelValid.gradeIds.length) == 0) {
                validFalg = true
            }
            return validFalg
        },
        errNumReset() {
            this.repeatNum = 0 // 帳號重複
            this.seatRepeatNum = 0 // 座號重複
            this.excelFiledNum = 0 // Excel 欄位空白檢核
            this.gradeNum = 0 // 年級錯誤
        }
    },
    created() {
        this.initData()
        //直接读取登录成功拿到得学校基础信息
        this.$store.dispatch('user/getSchoolProfile').then(
            res => {
                this.schoolBase = res.school_base
            },
            err => {
                this.$Message.warning(this.$t('cusMgt.noSchool'))
            }
        )
    },
    mounted() {
    },
    watch: {
        period:{
            handler(n,o){
                this.tableData.forEach(item=>{
                    item.periodId = this.period
                })
            }
        }
    }
}
</script>
