<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">班级：</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]" style="margin-left: 10px;color: #aaaaaa;">
                学生人数：{{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">保存分组</Button>
            <span :class="classList.length > 0 ? 'action-btn-wrap': 'disable-text-icon action-btn-wrap'" @click="customGroupStatus = true">
                <Icon type="md-shuffle" size="14" />
                自动分组
            </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" />
                导出名单
            </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 ? '分组视图':'列表视图' }}
            </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="暂无学生">
                    <Loading slot="loading" bgColor="rgba(103, 103, 103, 0.27)"></Loading>
                    <template slot-scope="{ row,index }" slot="header">
                        <span class="name-header" :style="{background:bgColor[index % 12]}">{{getFirstChart(row.name)}}</span>
                    </template>
                    <template slot-scope="{ row,index }" slot="action">
                        <div class="item-tools">
                            <Icon type="md-refresh" size="18" style="cursor:pointer;" title="重置密码" @click="resetPassword(index)"/>
                        </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 : '未分组'}}</span>
                    </template>
                </Table>
                <EmptyData v-else textContent="暂无您管理的班级" :top="150"></EmptyData>
            </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">{{parseInt(item.groupId)}}</span>
                        <Input v-model="item.groupName" class="group-name-tag" placeholder="组名..." 
                               :disabled="nameEdStatus" @click.native.stop="nameEdStatus = false" title="修改组名" @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="暂无学生" v-if="item.students.length == 0"></EmptyData>
                    </Draggable>
                </div>
                <div id="add-group-box">
                    <Input v-model="groupName" placeholder="输入组名......" 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">新增组别</p>
                </div>
            </vuescroll>
        </div>
        <Modal v-model="customGroupStatus"
               :title="$t('courseManage.classroom.autoGroupBtn')"
               @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('courseManage.classroom.studentCountLabel')">
                    <span v-if="customGroupStatus">{{classList[curClassIndex].students.length}}人</span>
                </FormItem>
                <FormItem :label="$t('courseManage.classroom.groupCountLabel')">
                    <InputNumber :max="10" :min="1" v-model="groupNum"></InputNumber>
                </FormItem>
                <FormItem :label="$t('courseManage.classroom.groupTypeLabel')">
                    <RadioGroup v-model="groupType">
                        <Radio label="1">
                            <span>{{$t('courseManage.classroom.groupType1')}}</span>
                        </Radio>
                        <Radio label="2">
                            <span>{{$t('courseManage.classroom.groupType2')}}</span>
                        </Radio>
                        <Radio label="3">
                            <span>{{$t('courseManage.classroom.groupType3')}}</span>
                        </Radio>
                    </RadioGroup>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
    import Draggable from 'vuedraggable'
    import excel from '@/utils/excel.js'
    export default {
        components: {
            Draggable
        },
        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: '组别',
                        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: '组名',
                        key: 'groupName',
                        align: 'center',
                        sortable: true,
                        //width: 80
                    },
                    {
                        slot: 'action',
                        title: '操作',
                        align: 'center'
                    }
                ]
            }
        },
        methods: {
            resetPassword(index) {
                this.$Message.warning('暂未对接重置密码API')
            },
            //切换班级
            selectClass(index) {
                this.curClassIndex = index
                if (this.viewType == 0) {
                    this.handelGroup()
                    console.log('123')
                }
            },
            //设置组名
            setGroupName(index) {
                console.log('执行函数')
                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
                        console.log(this.groupData[index].groupName)
                        console.log(this.classList[this.curClassIndex].students[i])
                    }
                }
                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])
                    }
                }
                console.log(this.groupData)
                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('至少保留一组')
                }
                console.log(this.groupData)
                this.updated = true
            },
            //新增分组
            addGroup() {
                if (this.groupName == '') {
                    this.$Message.warning('请先输入组名再创建组别')
                } else if (this.classList[this.curClassIndex].students.length == 0) {
                    this.$Message.warning('暂无学生可以进行分组')
                } 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() {
                console.log('保存分组。。。')
                console.log(this.classList[this.curClassIndex])
                this.tableLoading = true
                this.$api.schoolSetting.upsertGroup({
                    classroom: this.classList[this.curClassIndex]
                }).then(
                    (res) => {
                        if (!res.error) {
                            this.$Message.success('保存成功!')
                        } 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('分组数量不能为0')
                } else if (this.groupType == 0) {
                    this.$Message.warning('请设置分组方式')
                } 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()
                }
            },
            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 < maxCount; i++) {
                    for (let j = 0; j < this.groupNum; j++) {
                        let startIndex = this.groupNum * i
                        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)+ '组' )
                        } else {
                            break
                        }
                    }
                }
                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)+ '组')
                        } 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 + '组')
                    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: ['姓名','账号','座号','组别','组名'],
                    key: ['name','id','no','groupId','groupName'],
                    data: this.classList[this.curClassIndex].students,
                    autoWidth: true,
                    filename: '学生名单'
                }
                excel.export_array_to_excel(params)
            },
            //查询自己管理的班级
            findClass() {
                this.tableLoading = true
                let params = {
                    'school_code': this.$store.state.userInfo.schoolCode,
                    'teacher.id': this.$store.state.userInfo.TEAMModelId,
                    'scope':'school'
                }
                this.$api.schoolSetting.getClassroomStudent(params).then(
                    (res) => {
                        if (!res.error) {
                            this.classList = res.classrooms
                            if (this.classList.length > 0) {
                                this.curClassCode = this.classList[0].id
                            }
                        } 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
            })
        },
        mounted() {
            
        },
        computed: {
        }
    }
</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>