<template>
    <div class="mgt-class-container dark-iview-select dark-iview-checkbox custom-scroll-bar common-save-btn" @click="nameEdStatus = true">
        <!-- 头部 -->
        <div class="mgt-class-header">
            <span class="text-label">{{$t('cusMgt.classLabel')}}</span>
            <Select v-model="curClassCode" style="width:200px">
                <Option v-for="(item,index) in classList" :value="item.id" :key="index" @click.native="selectClass(index)">{{ item.name }}</Option>
            </Select>
            <span v-if="classList[curClassIndex] && classList[curClassIndex].students" style="margin-left: 10px;color: #aaaaaa;">
                {{$t('cusMgt.stuCount')}}{{classList[curClassIndex].students.length}}
            </span>
            <Button :disabled="!updated" size="small" style="float:right;margin-right:30px;margin-top:10px;" @click="saveGroup" icon="ios-albums-outline">
                {{$t('cusMgt.saveGroup')}}
            </Button>
            <span :class="classList.length > 0 ? 'action-btn-wrap': 'disable-text-icon action-btn-wrap'" @click="customGroupStatus = true">
                <Icon type="md-shuffle" size="14" />
                {{$t('cusMgt.autoGroup')}}
            </span>
            <span :class="classList.length > 0 ? 'action-btn-wrap': 'disable-text-icon action-btn-wrap'" @click="exportStudents">
                <Icon type="md-arrow-round-down" size="16" />
                {{$t('cusMgt.exportStu')}}
            </span>
            <span :class="classList.length > 0 ? 'action-btn-wrap': 'disable-text-icon action-btn-wrap'" @click="toggleView()">
                <Icon :type="viewType ? 'md-card':'md-list'" size="16" />
                {{viewType ? $t('cusMgt.viewport1'):$t('cusMgt.viewport2') }}
            </span>
        </div>
        <!-- 表格模式 -->
        <div class="mgt-class-body dark-iview-table animated fadeIn" id="table-wrap" v-if="viewType == 1">
            <vuescroll>
                <Table :columns="columns" v-if="classList[curClassIndex]" :data="classList[curClassIndex].students" :loading="tableLoading" ref="students" :height="tableHeight" :no-data-text="$t('cusMgt.noStu')">
                    <Loading slot="loading" bgColor="rgba(103, 103, 103, 0.27)"></Loading>
                    <template slot-scope="{ row,index }" slot="header">
                        <PersonalPhoto :name="row.name" :picture="row.picture" />
                    </template>
                    <template slot-scope="{ row,index }" slot="action">
                        <div class="item-tools">
                            <Icon type="md-refresh" size="18" style="cursor:pointer;" :title="$t('cusMgt.resetPw')" @click="resetPW(row)" />
                        </div>
                    </template>
                    <template slot-scope="{ row, index }" slot="groupId">
                        <span>{{row.groupId ? row.groupId : '- -'}}</span>
                    </template>
                    <template slot-scope="{ row, index }" slot="groupName">
                        <span>{{row.groupName ? row.groupName : $t('cusMgt.noGroup')}}</span>
                    </template>
                </Table>
                <EmptyData v-else :textContent="$store.state.userInfo.hasSchool ? $t('cusMgt.noMgtClass2') : $t('cusMgt.noMgtClass1')" :top="150"></EmptyData>
                <p style="text-align:center" v-show="!$store.state.userInfo.hasSchool">
                    <router-link to="/home/settings">{{$t('cusMgt.toJoin')}}</router-link>
                </p>
            </vuescroll>
        </div>
        <!-- 分组模式 -->
        <div class="mgt-class-body dark-iview-table animated fadeIn dark-iview-input disabled-iview-input" id="table-wrap" v-else>
            <vuescroll>
                <div class="group-wrap-item" v-for="(item,index) in groupData" :key="index">
                    <div class="group-title-wrap">
                        <span class="group-num-tag">{{item.groupId ? parseInt(item.groupId) : 1}}</span>
                        <Input v-model="item.groupName" class="group-name-tag" :placeholder="$t('cusMgt.groupNameHolder')" :disabled="nameEdStatus" @click.native.stop="nameEdStatus = false" :title="$t('cusMgt.edtiGroupName')" @on-change="$jsFn.debounce(setGroupName,1000)(index)" />
                        <Icon type="md-close" class="close-group-icon" @click="delGroup(index)" />
                    </div>
                    <Draggable ghost-class="ghost" group="student" class="list-group" :list="item.students" :animation='200' @end="groupToList">
                        <div class="student-info-item" v-for="(stuItem,index) in item.students" :key="index">
                            <span>{{stuItem.no+ '-' +stuItem.name}}</span>
                            <span>{{'('+stuItem.id+')'}}</span>
                        </div>
                        <EmptyData :textContent="$t('cusMgt.noStu')" v-if="item.students.length == 0"></EmptyData>
                    </Draggable>
                </div>
                <div id="add-group-box">
                    <Input v-model="groupName" :placeholder="$t('cusMgt.groupNameHolder')" style="width: 200px;margin:40px 50px 10px 50px;" />
                    <Icon type="md-add-circle" class="add-group-icon" @click="addGroup" />
                    <p class="add-group-label" @click="addGroup">{{$t('cusMgt.addGroup')}}</p>
                </div>
            </vuescroll>
        </div>
        <!-- 分组设置 -->
        <Modal v-model="customGroupStatus" :title="$t('cusMgt.autoGroup')" @on-ok="comfirmCustomRules" class="custom-group" class-name="dark-iview-modal dark-iview-form">
            <Form :label-width="80" :label-colon="true" style="color:white;">
                <FormItem :label="$t('cusMgt.studentCountLabel')">
                    <span v-if="customGroupStatus">{{classList[curClassIndex].students.length}}{{$t('unit.text7')}}</span>
                </FormItem>
                <FormItem :label="$t('cusMgt.groupCountLabel')">
                    <InputNumber :max="10" :min="1" v-model="groupNum"></InputNumber>
                </FormItem>
                <FormItem :label="$t('cusMgt.groupTypeLabel')">
                    <RadioGroup v-model="groupType">
                        <Radio label="1">
                            <span>{{$t('cusMgt.groupType1')}}</span>
                        </Radio>
                        <Radio label="2">
                            <span>{{$t('cusMgt.groupType2')}}</span>
                        </Radio>
                        <Radio label="3">
                            <span>{{$t('cusMgt.groupType3')}}</span>
                        </Radio>
                    </RadioGroup>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
import Draggable from 'vuedraggable'
import excel from '@/utils/excel.js'
import PersonalPhoto from "@/components/public/personalPhoto/Index.vue"
export default {
    components: {
        Draggable, PersonalPhoto
    },
    data() {
        return {
            curClassIndex: 0,
            groupName: '',
            groupData: [],
            tableHeight: 0,
            nameEdStatus: true,
            viewType: 1,
            tableLoading: false,
            customGroupStatus: false,
            updated: false,
            tableLoading: false,
            classList: [],
            groupNum: 2,
            groupType: '1',
            bgColor: ['#4ECDC4', '#F99406', '#075CD0', '#F7CA17', '#F2774B', '#67809F', '#BF55ED', '#00B169', '#F72459', '#F15A22', '#03C9A8', '#9A1294'],
            curClassCode: '',
            columns: [
                {
                    type: 'selection',
                    width: 80,
                    align: 'center'
                },
                {
                    slot: 'header',
                    title: ' ',
                    align: 'center',
                    //width:120
                },
                {
                    key: 'name',
                    title: this.$t('stuAccount.stuName'),
                    align: 'center',
                    //width:200
                },
                {
                    key: 'id',
                    title: this.$t('stuAccount.account'),
                    align: 'center',
                    //width:200
                },
                {
                    key: 'no',
                    title: this.$t('stuAccount.seatNo'),
                    align: 'center',
                    sortable: true,
                    sortMethod: function (a, b, type) {
                        if (type == 'asc') {
                            return parseInt(a) > parseInt(b) ? 1 : -1
                        } else if (type == 'desc') {
                            return parseInt(a) > parseInt(b) ? -1 : 1
                        }
                    }
                },
                {
                    slot: 'groupId',
                    title: this.$t('cusMgt.stuClassCol4'),
                    key: 'groupId',
                    align: 'center',
                    sortable: true,
                    sortMethod: function (a, b, type) {
                        if (type == 'asc') {
                            return parseInt(a) > parseInt(b) ? 1 : -1
                        } else if (type == 'desc') {
                            return parseInt(a) > parseInt(b) ? -1 : 1
                        }
                    }
                },
                {
                    slot: 'groupName',
                    title: this.$t('cusMgt.action'),
                    key: 'groupName',
                    align: 'center',
                    sortable: true,
                    //width: 80
                },
                {
                    slot: 'action',
                    title: ' ',
                    align: 'center'
                }
            ]
        }
    },
    methods: {
        /**
         * 重置密碼
         * @param row
         */
        resetPW(row) {
            //重置单个学生
            if (row != -1) {
                this.$Modal.confirm({
                    title: this.$t('cusMgt.resetPw'),
                    content: '<p>' + this.$t('cusMgt.resetPwContent1') + " <strong style='color:red;'>" + row.name + '</strong>' + this.$t('cusMgt.resetPwContent1') + '?</p>',
                    onOk: () => {
                        let ids = []
                        row.pw = row.id
                        row.year = row.year ? row.year.toString() : ''
                        delete row.no
                        ids.push(row)
                        this.tableLoading = true
                        this.$api.stuAccount.saveAllStudent(this.$store.state.user.schoolCode, ids).then(
                            res => {
                                this.$Message.success(this.$t('cusMgt.resetPwOk'))
                                this.tableLoading = false
                            },
                            err => {
                                this.$Message.error('API error!')
                                this.tableLoading = false
                            }
                        )
                    }
                })
            } else {
                //批量重置
                if (this.selections.length > 0) {
                    this.$Modal.confirm({
                        title: this.$t('cusMgt.resetPw'),
                        content: '<p>' + this.$t('cusMgt.resetPwContent3') + " <strong style='color:red;'>" + this.selections.length + '</strong>' + this.$t('cusMgt.resetPwContent4') + '</p>',
                        onOk: () => {
                            this.tableLoading = true
                            let apiData = this.selections.map((item) => {
                                let d = item
                                d.pw = d.id
                                delete d.no
                                return d
                            })

                            this.$api.stuAccount.saveAllStudent(this.$store.state.user.schoolCode, apiData).then(
                                res => {
                                    this.selections.length = 0
                                    this.$Message.success(this.$t('cusMgt.resetPwOk'))
                                },
                                err => {
                                    this.$Message.error('API ERROR!')
                                }
                            ).finally(() => {
                                this.tableLoading = false
                            })
                        }
                    })
                }
            }
        },
        //切换班级
        selectClass(index) {
            this.curClassIndex = index
            if (!this.classList[this.curClassIndex].students) {
                this.findClassStu()
            }
            if (this.viewType == 0) {
                this.handelGroup()
            }
        },
        //设置组名
        setGroupName(index) {
            for (let i in this.classList[this.curClassIndex].students) {
                if (this.classList[this.curClassIndex].students[i].groupId == this.groupData[index].groupId) {
                    this.classList[this.curClassIndex].students[i].groupName = this.groupData[index].groupName
                }
            }
            this.updated = true
        },
        //分组视图修改后对应调整表格视图
        groupToList() {
            this.classList[this.curClassIndex].students = []
            for (let i in this.groupData) {
                for (let j in this.groupData[i].students) {
                    this.groupData[i].students[j].groupId = this.groupData[i].groupId
                    this.groupData[i].students[j].groupName = this.groupData[i].groupName
                    this.classList[this.curClassIndex].students.push(this.groupData[i].students[j])
                }
            }
            this.updated = true
        },
        //删除组别
        delGroup(index) {
            if (this.groupData.length > 1) {
                let students = JSON.parse(JSON.stringify(this.groupData[index].students))
                for (let i in students) {
                    students[i].groupId = this.groupData[0].groupId
                    students[i].groupName = this.groupData[0].groupName
                }
                this.groupData.splice(index, 1)
                this.groupData[0].students.push(...students)
                this.groupToList()
            } else {
                this.$Message.warning(this.$t('cusMgt.atLeast'))
            }
            this.updated = true
        },
        //新增分组
        addGroup() {
            if (this.groupName == '') {
                this.$Message.warning(this.$t('cusMgt.checkName'))
            } else if (this.classList[this.curClassIndex].students.length == 0) {
                this.$Message.warning(this.$t('cusMgt.noStuTips'))
            } else {
                this.groupData.push({
                    groupId: (this.groupData.length + 1) + '',
                    groupName: this.groupName,
                    students: []
                })
                this.groupName = ''
            }
            this.updated = true
        },
        toggleView() {
            this.viewType = 1 - this.viewType
            if (!this.viewType) {
                this.handelGroup()
            }

        },
        //列表视图转分组视图
        handelGroup() {
            let groupRes = this.$jsFn.groupBy(this.classList[this.curClassIndex].students, 'groupId')
            this.groupData.length = 0
            for (let index in groupRes) {
                this.groupData.push({
                    groupName: groupRes[index][0].groupName,
                    groupId: groupRes[index][0].groupId,
                    students: groupRes[index]
                })
            }
            this.groupData.sort((a, b) => {
                return parseInt(a.groupId) - parseInt(b.groupId)
            })
            //this.updated = true
        },
        saveGroup() {
            this.tableLoading = true
            // this.$api.schoolSetting.upsertGroup({
            //     classroom: this.classList[this.curClassIndex]
            // }).then(
            //     (res) => {
            //         if (!res.error) {
            //             this.$Message.success(this.$t('cusMgt.saveOk'))
            //         } else {
            //             this.$Message.error('API error!')
            //         }
            //     },
            //     (err) => {
            //         this.$Message.error('API error!')
            //     }
            // ).finally(() => {
            //     setTimeout(() => {
            //         this.tableLoading = false
            //     }, 500)
            // })
            this.$api.schoolSetting.upsertGroup({
                students: this.classList[this.curClassIndex].students
            }).then(
                (res) => {
                    if (!res.error) {
                        this.$Message.success(this.$t('cusMgt.saveOk'))
                    } else {
                        this.$Message.error('API error!')
                    }
                },
                (err) => {
                    this.$Message.error('API error!')
                }
            ).finally(() => {
                setTimeout(() => {
                    this.tableLoading = false
                }, 500)
            })
        },
        comfirmCustomRules() {
            if (this.groupNum === 0) {
                this.$Message.warning(this.$t('cusMgt.groupCount'))
            } else if (!this.groupType) {
                this.$Message.warning(this.$t('cusMgt.groupTypeTips'))
            } else {
                switch (this.groupType) {
                    case '1':
                        this.randomGroup()
                        break
                    case '2':
                        this.orderGroup()
                        break
                    case '3':
                        this.orderGroupS()
                        break
                    default:
                        break
                }
                this.tableLoading = true
                this.updated = true
                this.handelGroup()
            }
        },
        // 依座顺序S形分组
        orderGroupS() {
            let stuLen = this.classList[this.curClassIndex].students.length
            let surplus = stuLen % this.groupNum// 余数
            let maxCount = surplus == 0 ? stuLen / this.groupNum : Math.ceil(stuLen / this.groupNum)// 每组最大人数
            this.classList[this.curClassIndex].students = this.classList[this.curClassIndex].students.sort((a, b) => {
                a.seatNo > b.seatNo
            })
            for (let i = 0; i < this.groupNum; i++) {
                let num = surplus == 0 ? maxCount : i < surplus ? maxCount : maxCount - 1 //每组实际人数
                for (let j = 0; j < num; j++) {
                    let startIndex = i + (j * this.groupNum)
                    this.$set(this.classList[this.curClassIndex].students[startIndex], 'groupId', (i + 1) + '')
                    this.$set(this.classList[this.curClassIndex].students[startIndex], 'groupName', (i + 1) + this.$t('cusMgt.groupUnit'))
                }
            }
            setTimeout(() => {
                this.tableLoading = false
            }, 500)
        },
        // 依座号分组
        orderGroup() {
            let stuLen = this.classList[this.curClassIndex].students.length
            let surplus = stuLen % this.groupNum// 余数
            let maxCount = surplus == 0 ? stuLen / this.groupNum : Math.ceil(stuLen / this.groupNum)// 每组最大人数
            this.classList[this.curClassIndex].students = this.classList[this.curClassIndex].students.sort((a, b) => {
                a.no > b.no
            })
            let flag = 0
            let startIndex = 0
            for (let i = 0; i < this.groupNum; i++) {
                for (let j = 0; j < maxCount; j++) {
                    if (startIndex + j < stuLen) {
                        this.$set(this.classList[this.curClassIndex].students[startIndex + j], 'groupId', i + 1)
                        this.$set(this.classList[this.curClassIndex].students[startIndex + j], 'groupName', (i + 1) + this.$t('cusMgt.groupUnit'))
                    } else {
                        break
                    }
                }
                startIndex += maxCount
                flag++
                if (flag == surplus) {
                    maxCount--
                }
            }
            setTimeout(() => {
                this.tableLoading = false
            }, 500)
        },
        // 随机分组
        randomGroup() {
            let stuLen = this.classList[this.curClassIndex].students.length
            let surplus = stuLen % this.groupNum// 余数
            let surplusCount = surplus// 余数
            let maxCount = surplus == 0 ? stuLen / this.groupNum : Math.ceil(stuLen / this.groupNum)// 每组最大人数
            let record = {}// 记录每个组已经分配的人数
            for (let i = 1; i <= this.groupNum; i++) {
                record[i] = 0
            }
            let flag = true
            for (let index in this.classList[this.curClassIndex].students) {
                let groupIndex = this.$jsFn.getBtwRandom(1, this.groupNum)
                if (record[groupIndex] < maxCount) {
                    record[groupIndex] = record[groupIndex] + 1
                } else {
                    for (let key in record) {
                        if (record[key] < maxCount) {
                            record[key] = record[key] + 1
                            groupIndex = key
                            break
                        }
                    }
                }
                this.$set(this.classList[this.curClassIndex].students[index], 'groupId', groupIndex + '')
                this.$set(this.classList[this.curClassIndex].students[index], 'groupName', groupIndex + this.$t('cusMgt.groupUnit'))
                if (record[groupIndex] == maxCount) {
                    surplusCount--
                }
                if (surplusCount <= 0 && surplus > 0 && flag) {
                    maxCount--
                    flag = false
                }
            }
            setTimeout(() => {
                this.tableLoading = false
            }, 500)
        },
        getFirstChart(name) {
            if (name) {
                return name.substr(0, 1)
            } else {
                return '--'
            }
        },
        //导出名单
        exportStudents() {
            /*const params = {
                title: this.columns.map(i => i.title),
                key: this.columns.map(i => i.key),
                data: this.classList[this.curClassIndex].students,
                autoWidth: true,
                filename: '学生名单'
            }*/
            const params = {
                title: [
                    this.$t('cusMgt.stuClassCol1'),
                    this.$t('cusMgt.stuClassCol2'),
                    this.$t('cusMgt.stuClassCol3'),
                    this.$t('cusMgt.stuClassCol4'),
                    this.$t('cusMgt.stuClassCol5')
                ],
                key: ['name', 'id', 'no', 'groupId', 'groupName'],
                data: this.classList[this.curClassIndex].students,
                autoWidth: true,
                filename: this.$t('cusMgt.stuNameList')
            }
            excel.export_array_to_excel(params)
        },
        //查询自己管理的班级
        findClass() {
            this.$store.dispatch('user/getSchoolProfile').then(
                res => {
                    if (this.$store.state.userInfo.isHeadmaster) {
                        let classes = res.school_classes
                        console.log('class', classes)
                        this.classList = classes.filter(item => {
                            return this.$store.state.userInfo.mgtClasses.indexOf(item.id) > -1
                        })
                        if (this.classList.length > 0) {
                            this.curClassCode = this.classList[0].id
                            this.findClassStu()
                        }
                        console.log('list', this.classList)
                    }
                }
            )
        },
        //查询班级学生
        findClassStu() {
            this.tableLoading = true
            let params = {
                'school_code': this.$store.state.userInfo.schoolCode,
                'ids': [this.curClassCode],
                'scope': 'school'
            }
            this.$api.schoolSetting.getClassroomStudent(params).then(
                (res) => {
                    if (!res.error) {
                        this.classList[this.curClassIndex].students = res.stus.length ? res.stus[0] : []
                    } else {
                        this.$Message.error('API error!')
                    }
                },
                (err) => {
                    this.$Message.error('API error!')
                }
            ).finally(() => {
                setTimeout(() => {
                    this.tableLoading = false
                }, 500)
            })
        }
    },
    created() {
        this.findClass()
        this.$nextTick(() => {
            let dom = document.getElementById('table-wrap')
            this.tableHeight = dom.offsetHeight - 30
        })
    }
}
</script>
<style scoped lang="less">
@import "./ManageClass.less";
</style>
<style>
.mgt-class-container #loadingBox {
    margin-top: 0px !important;
}
.group-title-wrap .ivu-input[disabled] {
    color: white;
    vertical-align: super;
    font-weight: 800;
}
.ghost {
    opacity: 0;
    background: #c8ebfb;
}
#add-group-box .ivu-input {
    background: #2b2b2e;
}
.group-title-wrap .ivu-input[disabled],
.group-title-wrap fieldset[disabled] .ivu-input {
    cursor: pointer;
}
</style>