<template>
    <div class="student-list">
        <div class="student-filter-wrap">
            <span style="margin-top:6px">{{$t('stuAccount.filterLabel')}}</span>
            <!-- 學制Select -->
            <Select v-model="searchPeriod" style="width:120px;" :placeholder="$t('stuAccount.periodHolder')" @on-change="filterData" :not-found-text="$t('stuAccount.noSchool')">
                <Option v-for="(item,index) in periods" :value="item.id" :key="index">{{ item.name }}</Option>
            </Select>
            <!-- 學級Select -->
            <Select v-model="searchGrade" style="width:180px;margin-left:5px;" :placeholder="$t('stuAccount.gradeHolder')" :not-found-text="$t('stuAccount.sltPdFirst')" clearable @on-change="filterData">
                <Option v-for="(item, index) in years" :value="item.value" :key="index">{{ item.label }}</Option>
            </Select>
            <!-- 教室Select -->
            <Select v-model="searchClass" ref="classroom" style="width:180px;margin-left:5px;" :placeholder="$t('stuAccount.classroomHolder')" @on-change="filterData" :not-found-text="searchGrade ? $t('stuAccount.noClass'):$t('stuAccount.sltGdFirst')">
                <Option v-for="(item,index) in filterClasses" :value="item.id" :key="index">{{ item.name }}</Option>
                <Option v-show="!searchGrade" value="noclass">{{$t('stuAccount.noRelClass')}}</Option>
            </Select>
            <!-- 字串模糊搜尋 -->
            <Input v-model="searchText" clearable :placeholder="$t('stuAccount.searchHolder')" style="width: 220px;margin-left:20px;" search @on-search="filterData" @on-clear="filterData"></Input>
        </div>
        <div style="position:relative">
            <Scroll :on-reach-bottom="scrollLoad" height="600" :distance-to-edge="[15,15]">
                <Table ref="stuSelection" :columns="tableColumns" :data="tableShowData" @on-selection-change="getSelectInfo">
                    <template slot-scope="{ row,index }" slot="status">
                        <Icon custom="iconfont icon-auth-key" size="25" color="#565656" />
                    </template>
                    <template slot-scope="{ row,index }" slot="header">
                        <PersonalPhoto :name="row.name" :picture="row.picture"></PersonalPhoto>
                    </template>
                    <template slot-scope="{ row }" slot="gradeName">
                        <span>{{ $jsFn.getGradeNameByYear(schoolBase, searchPeriod, row.classYear) }}</span>
                    </template>
                    <template slot-scope="{ row }" slot="classId">
                        <span>{{ getClassName(row.classId)}}</span>
                    </template>
                    <template slot-scope="{ row }" slot="no">
                        <span>{{row.no}}</span>
                    </template>
                    <template slot-scope="{ row }" slot="action">
                        <div class="item-tools" v-if="$access.can('admin.*|student-upd')">
                            <Icon type="md-create" size="18" color="white" @click="editStudent(row)" />
                            <Icon custom="iconfont icon-reset" size="18" color="white" @click="resetPW(row)" />
                            <Icon type="md-trash" size="18" color="white" @click="delStudent(row)" />
                        </div>
                    </template>
                </Table>
            </Scroll>
            <Loading v-show="tableLoading" :top="100"></Loading>
        </div>
    </div>
</template>
<script>
import PersonalPhoto from '@/components/public/personalPhoto/Index.vue'
import { mapGetters } from 'vuex'
export default {
    components: {
        PersonalPhoto
    },
    data() {
        return {
            bgColor: ['#4ECDC4', '#F99406', '#075CD0', '#F7CA17', '#F2774B', '#67809F', '#BF55ED', '#00B169', '#F72459', '#F15A22', '#03C9A8', '#9A1294'],
            searchText: '',
            searchPeriod: '',
            searchGrade: '',
            searchClass: '',
            selections: [],
            currentPage: 1,
            pageSize: 20,
            tableShowData: [],
            tableColumns: [],
            totalNum: 0,
            tableLoading: false,
            tableFilterData: [],
            basicCount: 99,
            schoolBase: {
                period: []
            }
        }
    },
    methods: {
        //清空选择状态
        clearTable() {
            this.$refs.stuSelection.selectAll(false)
        },
        initData() {
            this.tableColumns = [
                {
                    type: 'selection',
                    width: 80,
                    align: 'center'
                },
                {
                    slot: 'header',
                    title: ' ',
                    align: 'center',
                    width: 150
                },
                {
                    key: 'id',
                    title: this.$t('stuAccount.account'),
                    align: 'center',
                    sortable: true,
                    sortMethod: (a, b, type) => {
                        if (type == 'asc') {
                            return a.localeCompare(b)
                        } else {
                            return b.localeCompare(a)
                        }
                    }
                },
                {
                    key: 'no',
                    title: this.$t('stuAccount.seatNo'),
                    align: 'center',
                    width: 120,
                    sortable: true,
                    sortMethod: (a, b, type) => {
                        if (type == 'desc') {
                            return parseInt(a) > parseInt(b) ? -1 : 1
                        } else {
                            return parseInt(a) < parseInt(b) ? -1 : 1
                        }
                    }
                },
                {
                    key: 'name',
                    title: this.$t('stuAccount.stuName'),
                    align: 'center'
                },
                {
                    slot: 'gradeName',
                    title: this.$t('stuAccount.grade'),
                    align: 'center',
                    width: 140
                },
                {
                    slot: 'classId',
                    title: this.$t('stuAccount.classroomName'),
                    align: 'center'
                }
            ]
        },
        /**基础查询数据 */
        baseFindStudent(params) {
            if (!this.$store.state.user.schoolCode) return
            this.$api.stuAccount.findStudent(this.$store.state.user.schoolCode).then(
                (res) => {
                    this.tableLoading = false
                    res.students = res.students || []
                    // 給一個 PW 讓AddStudent.vue 的Watch 可以動作
                    let newStudents = res.students.map(function (item) {
                        let temp = item
                        temp.pw = '******'
                        return temp
                    })
                    this.$store.dispatch('schoolBaseInfo/setStudentsToState', newStudents)
                    this.filterData()
                },
                (err) => {
                    this.tableLoading = false
                }
            )
        },
        /**根据学段、年级、班级搜索 */
        filterData() {
            let data = this.students
            // 學制篩選
            if (this.searchPeriod) {
                data = data.filter(item => {
                    return item.periodId == this.searchPeriod
                })
            }

            // 年級篩選
            if (this.searchGrade) {
                data = data.filter(item => {
                    return item.classYear == this.searchGrade
                })
            }

            // 班级筛选条件
            if (this.searchClass == 'noclass') {
                data = data.filter(item => {
                    return !item.classId
                })
            } else if (this.searchClass) {
                data = data.filter(item => {
                    return item.classId == this.searchClass
                })
            }

            // 帳號資訊搜尋
            if (this.searchText) {
                data = data.filter(item => {
                    return item.name.indexOf(this.searchText) >= 0 || item.id.indexOf(this.searchText) >= 0
                })
            }

            this.tableFilterData = data
            this.pointNum = this.basicCount
            this.tableShowData = data.slice(0, this.basicCount)
        },

        getSelectInfo(selction, row) {
            this.selections = selction
            this.selectRow = row
            this.$emit('getSelectInfo', selction)
        },

        scrollLoad: function () {
            setTimeout(() => {
                let temp = this.tableFilterData.slice(this.pointNum + 1, this.pointNum + this.basicCount)
                this.pointNum += this.basicCount
                if (temp.length == 0) {
                    this.$Message.info(this.$t('stuAccount.isBottom'))
                } else {
                    this.tableShowData.push(...temp)
                }
            }, 1500);
        },
        /** 取得年級Name */
        getGradeName: function (gradeId) {
            if (gradeId != null) {
                let gradeData = this.grades.filter(function (item) {
                    return item.id == gradeId
                })
                return gradeData[0].name
            } else {
                return ''
            }
        },
        /** 取得教室Name */
        getClassName: function (classId) {
            if (classId && this.classes) {
                let classesData = this.classes.filter(function (item) {
                    return item.id == classId
                })
                return classesData[0] ? classesData[0].name : ''
            } else {
                return '-'
            }
        },
        getFirstChart(name) {
            if (name) {
                return name.substr(0, 1)
            } else {
                return '-'
            }
        },
    },
    created() {
        this.initData()
        this.baseFindStudent()
        this.$store.dispatch('user/getSchoolProfile').then(
            res => {
                this.schoolBase = res.school_base
            }
        )
    },
    computed: {
        ...mapGetters({
            periods: 'user/getPeriods', // 學制s
            grades: 'user/getGrades', // 年級
            classes: 'user/getClasses', // 教室ID
            students: 'schoolBaseInfo/getStudent', // 學生List
        }),
        filterClasses: function () {
            var data = this.classes
            if (this.searchGrade) {
                data = data.filter((item) => {
                    return item.year == this.searchGrade && item.periodId == this.searchPeriod
                })
                return data
            } else {
                return []
            }
        },
        years() {
            if (this.schoolBase && this.schoolBase.period.length && this.searchPeriod) {
                let pData = this.schoolBase.period.find(item => {
                    return item.id == this.searchPeriod
                })
                if (pData) {
                    let date = new Date()
                    let year = date.getFullYear()
                    let month = date.getMonth() + 1
                    let start = pData.semesters.find(item => {
                        return item.start == 1
                    })
                    // 根据入学月份确定当前年级和学级的关系
                    if (start && month < start.month) {
                        year--
                    }
                    let res = pData.grades.map(item => {
                        return {
                            label: `${item}(${year}${this.$t('unit.gradeYear')})`,
                            value: year--
                        }
                    })
                    return res
                } else {
                    return []
                }
            }
            return []
        }
    },
    watch: {
        periods: {
            handler(n, o) {
                if (n && n.length) {
                    this.searchPeriod = n[0].id
                }
            },
            deep: true,
            immediate: true
        }
    }

}
</script>
<style lang="less" scoped>
@import "./StudentList.less";
</style>
<style>
</style>