<template>
    <div class="mgt-stu-list dark-iview-split dark-iview-input">
        <Split v-model="split1">
            <div slot="left" class="stu-list-box">
                <div class="list-header">
                    {{$t('cusMgt.nameList')}}
                    <div v-if="!isSearch" style="float:right;">
                        <Icon class="action-btn-icon" type="md-trash" @click="delStuList()" />
                        <!-- <Icon class="action-btn-icon" type="md-create" /> -->
                        <Icon class="action-btn-icon" type="md-add" @click="createList" />
                        <!-- <Icon class="action-btn-icon" type="ios-search" @click="isSearch = true" /> -->
                    </div>
                    <Input v-else icon="ios-close" v-model="keyWord" :placeholder="$t('cusMgt.searchHolder')" @on-click="isSearch = false" size="small" style="float:right;width: 180px;margin-top:10px;margin-right:10px" />
                </div>
                <div class="list-content">
                    <vuescroll>
                        <div v-for="(item,index) in stuList" @click="selectList(index)" :key="index" :class="['list-item','block-bg',curIndex == index ? 'block-bg-active':'']">
                            <p class="list-name">
                                {{item.name}}
                            </p>
                            <p>
                                <span class="attr-label">
                                    {{$t('cusMgt.stuCount')}}
                                </span>
                                <span class="stu-count">
                                    {{item.students ? item.students.length : 0}}{{$t('unit.text7')}}
                                </span>
                            </p>
                        </div>
                    </vuescroll>
                </div>
            </div>
            <div slot="right" class="stu-info-box">
                <div class="stu-info-header">
                    <div class="action-btn-wrap">
                        <span class="action-btn" style="margin-right:30px" @click="pushStudents">
                            <Icon type="md-add" size="16" />
                            <span>{{$t('cusMgt.addStu')}}</span>
                        </span>
                        <span class="action-btn" @click="batchRemove">
                            <Icon type="md-remove-circle" size="16"/>
                            <span>{{$t('cusMgt.remvStu')}}</span>
                        </span>
                        <!-- <span class="action-btn" @click="goBack">
                            <Icon type="md-arrow-back" size="16" />
                            <span>{{$t('cusMgt.goBack')}}</span>
                        </span> -->
                    </div>
                </div>
                <div class="stu-list-table dark-iview-table">
                    <vuescroll>
                        <Table :columns="listColumn" v-if="stuList[curIndex]" :data="students" @on-selection-change="(selction)=>{rmSelctions = selction}" :loading="tableLoading" :no-data-text="$t('cusMgt.noStu')">
                            <Loading slot="loading" :top="0" bgColor="rgba(103, 103, 103, 0.27)"></Loading>
                            <template slot-scope="{ row }" slot="picture">
                                <PersonalPhoto :name="row.name ? row.name : ''" :picture="row.picture" />
                            </template>
                            <template slot-scope="{ row,index }" slot="no">
                                <span v-show="editIndex !== index">{{row.no}}</span>
                                <Input v-model="students[index].no" v-show="editIndex == index" style="width: 60px;" type="number" />
                                <Icon type="md-checkmark" v-show="editIndex == index" @click="confirmSetNo()" class="reset-no-btn" />
                                <Icon type="md-close" v-show="editIndex == index" @click="cancelSetNo()" class="reset-no-btn" />
                            </template>
                            <template slot-scope="{ row ,index}" slot="action">
                                <div class="item-tools" v-if="$access.can('admin.*|student-upd')">
                                    <Icon type="md-create" size="18" color="white" @click="resetNo(index)" :title="$t('schoolBaseInfo.editSeat')" />
                                    <Icon type="md-remove-circle" size="18" color="white" style="margin-left:10px" @click="removeStudent(index)" :title="$t('schoolBaseInfo.delStuBtn')" />
                                </div>
                            </template>
                            <template slot-scope="{ row, index }" slot="action">
                                <!-- <Icon type="md-trash" color="white"/> -->
                                <div class="item-tools">
                                    <Icon type="md-remove-circle" @click="removeStu(row,index)" color="white" size="18" :title="$t('cusMgt.remvStu')" />
                                </div>
                            </template>
                        </Table>
                    </vuescroll>
                </div>
            </div>
        </Split>
        <!-- 创建名单 -->
        <Modal v-model="addStuStatus" :title="$t('cusMgt.createList')" width="1200" @on-ok="confirmAddStu" class-name="dark-iview-modal" :loading="modalLoading">
            <div class="dark-iview-input list-name-box" v-show="isCreate">
                <span>{{$t('cusMgt.name')}}</span>
                <Input v-model="listName" :placeholder="$t('cusMgt.nameHolder')" style="width: 300px" />
            </div>
            <StudentList ref="studentList" @getSelectInfo="(selction)=>{selections = selction}"></StudentList>
        </Modal>
    </div>
</template>
<script>
import PersonalPhoto from '@/components/public/personalPhoto/Index.vue'
import StudentList from '@/components/coursemgt/StudentList.vue'
export default {
    components: {
        PersonalPhoto, StudentList
    },
    data() {
        return {
            rmSelctions:[],
            isCreate: false,
            schoolBase: {
                period: []
            },
            classList: [],
            modalLoading: true,
            selections: '',//选中的学生了列表
            listName: '',
            keyWord: '',
            addStuStatus: false,
            isSearch: false,
            split1: 0.2,
            stuList: [],
            curIndex: 0,
            tableLoading: false,
            students: [],
            listColumn: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: ' ',
                    slot: 'picture',
                    align: 'center ',
                    width: '150'
                },
                {
                    title: this.$t('courseManage.classroom.studentTableC2'),
                    key: 'name',
                    align: 'center '
                },
                {
                    title: this.$t('courseManage.classroom.studentTableC7'),
                    key: 'id',
                    align: 'center',
                    sortable: true
                },
                // {
                //     title: '来源',
                //     key: 'source',
                //     align: 'center'
                // },
                {
                    title: this.$t('cusMgt.className'),
                    key: 'className',
                    align: 'center'
                },
                {
                    title: ' ',
                    slot: 'action',
                    align: 'center'
                }
            ],
        }
    },
    methods: {
        // 批量移除学生
        batchRemove(){
            if(this.rmSelctions.length){
                this.$Modal.confirm({
                    title:'移除学生',
                    content:`确认移除选择的${this.rmSelctions.length}位学生吗?`,
                    okText:'是',
                    cancelText:'否',
                    onOk:()=>{
                        let rmIds = this.rmSelctions.map(item=>{
                            return item.id
                        })
                        for(let i = 0; i < this.stuList[this.curIndex].students.length; i++){
                            if(rmIds.indexOf(this.stuList[this.curIndex].students[i].id) > -1){
                                this.stuList[this.curIndex].students.splice(i,1)
                                i--
                            }
                        }
                        this.saveStuList(this.stuList[this.curIndex])
                    }
                })
            }else{
                this.$Message.warning('请选择需要移除的学生')
            }
        },
        // 单个移除学生
        removeStu(row,index){
            this.$Modal.confirm({
                title:'移除学生',
                content:`是否确认移除${row.name}?`,
                okText:'是',
                cancelText:'否',
                onOk:()=>{
                    this.stuList[this.curIndex].students.splice(index,1)
                    this.saveStuList(this.stuList[this.curIndex])
                }
            })
        },
        // 新建名单
        createList() {
            this.isCreate = true
            this.addStuStatus = true
        },
        // 添加学生
        pushStudents() {
            this.isCreate = false
            this.addStuStatus = true
        },
        selectList(index) {
            this.curIndex = index
            if (this.stuList[this.curIndex].full) {
                this.students = this.stuList[this.curIndex].students
            } else {
                this.$api.courseMgmt.findStuSummary({
                    students: this.stuList[this.curIndex].students
                }).then(
                    res => {
                        res.stus = res.stus || []
                        res.stus.forEach(item => {
                            //TODO 设置班级名称
                            item.source = '校内账号'
                            let curClass = this.classList.find(classItem => {
                                return classItem.id == item.classId
                            })
                            item.className = curClass ? curClass.name : '- -'
                        })
                        console.log(res)
                        this.stuList[this.curIndex].students = res.stus
                        this.students = res.stus
                        this.stuList[this.curIndex].full = true
                    }
                )
            }
        },
        confirmAddStu() {
            //新建名单
            if (this.isCreate) {
                if (!this.listName) {
                    this.$Message.warning(this.$t('cusMgt.nameWarning'))
                    this.modalLoading = false
                    setTimeout(() => {
                        this.modalLoading = true
                    }, 0)
                    return
                }
                let stuList = {
                    name: this.listName,
                    id: this.$tools.guid(),
                    code: this.$store.state.userInfo.schoolCode,
                    students: this.selections.map(item => { //这里没有学生名字， 需要先查看id集合再查学生信息？
                        return {
                            id: item.id,
                            // code: item.code //学生所在学校的编码，这里先传当前学校编码，暂无未考虑跨校名单
                            code: 'Base-' + this.$store.state.userInfo.schoolCode
                        }
                    }),
                    tmids: [],
                    course: null
                }
                this.saveStuList(stuList)
            }
            //名单添加学生
            else {
                let ids = this.stuList[this.curIndex].students.map(item => {
                    return item.id
                })
                this.selections.forEach(item => {
                    if (ids.indexOf(item.id) < 0) {
                        this.stuList[this.curIndex].students.push({
                            id: item.id,
                            code: 'Base-' + this.$store.state.userInfo.schoolCode,
                            name: item.name,
                            className: item.className
                        })
                    }
                })
                this.stuList[this.curIndex].code = this.$store.state.userInfo.schoolCode
                this.saveStuList(this.stuList[this.curIndex])
            }
        },
        goBack() {
            this.$router.push({
                name: 'NewCusMgt'
            })
        },
        //查询名单列表
        findStuList() {
            let params = {
                code: this.$store.state.userInfo.schoolCode,
                scope: 'school'
            }
            this.$api.courseMgmt.findStulist(params).then(
                res => {
                    this.stuList = res.stuList
                    this.selectList(0)
                },
                err => {
                    this.$Message.error('API error')
                }
            )
        },
        // 删除课程名单
        delStuList() {
            this.$Modal.confirm({
                title: this.$t('cusMgt.delListTitle'),
                content: `${this.$t('cusMgt.delContent')}${this.stuList[this.curIndex].name}?`,
                onOk: () => {
                    let id = this.stuList[this.curIndex].id
                    let requestData = {
                        code: this.$store.state.userInfo.schoolCode,
                        scope: 'school',
                        id: id
                    }
                    this.$api.courseMgmt.delStuList(requestData).then(
                        res => {
                            this.$Message.success(this.$t('cusMgt.delOk'))
                            this.stuList.forEach((item, index) => {
                                if (item.id == id) {
                                    this.stuList.splice(index, 1)
                                }
                            })
                        },
                        err => {
                            this.$Message.error(this.$t('cusMgt.delErr'))
                        }
                    )
                }
            })

        },
        // 保存名单
        saveStuList(stuList) {
            stuList.code = this.$store.state.userInfo.schoolCode
            let params = {
                stuList,
                scope: "school"
            }
            this.$api.courseMgmt.upsertStulist(params).then(
                res => {
                    this.$Message.success(this.$t('cusMgt.updOk'))
                    this.addStuStatus = false
                    if (this.isCreate) {
                        this.stuList.unshift(params.stuList)
                    }
                    this.rmSelctions = []
                    this.$refs['studentList'].clearTable()
                },
                err => {
                    this.modalLoading = false
                    setTimeout(() => {
                        this.modalLoading = true
                    }, 0)
                }
            )
        },
        //查询学生详细信息
        findStuInfo(stus) {

        },
        upsertStuList() {
            this.$api.courseMgmt.upsertStulist(params).then(
                res => {

                },
                err => {

                }
            )
        },
    },
    created() {
        //直接读取登录成功拿到得学校基础信息
        this.$store.dispatch('user/getSchoolProfile').then(
            res => {
                this.schoolBase = res.school_base
                this.classList = res.school_classes
            },
            err => {
                this.$Message.warning(this.$t('cusMgt.noSchool'))
            }
        )
        this.findStuList()
    }
}
</script>
<style scoped lang="less">
@import "./MgtStuList.less";
</style>
<style>
.mgt-stu-list .ivu-table-row-hover .item-tools {
    display: inline-block;
    cursor: pointer;
}
</style>