<template>
    <div class="my-course-container">
        <Loading v-if="listLoading" bgColor="rgba(103, 103, 103, 0.27)"></Loading>
        <!--课程列表-->
        <div class="course-list">
            <!--列表内容-->
            <vuescroll>
                <div class="dark-iview-tabs-line cus-list-tab">
                    <Tabs v-model="listType" @on-click="tabClick">
                        <div slot="extra">
                            <transition name="fade">
                                <div style="margin-top:5px;">
                                    <Icon type="md-create" v-show="(listType == 'school' && courseListS.length) || (listType == 'private' && courseListP.length) " class="add-icon" title="编辑课程" @click="editCus()" />
                                    <Icon type="md-add" v-show="listType == 'private'" class="add-icon" title="新增课程" @click="showAddCourse()" />
                                    <Icon type="md-trash" v-show="listType == 'private'" class="add-icon" title="删除课程" @click="delCourse" />
                                </div>
                            </transition>
                        </div>
                        <TabPane label="标准课程" name="school">
                            <div v-for="(item,index) in courseListS" :key="index" @click="selectCourse(index)" :class="index === curCusIndex ? 'course-list-item block-bg block-bg-active':'course-list-item block-bg'">
                                <p class="course-name">
                                    {{item[0].courseName}}
                                    <Icon type="ios-information-circle-outline" @click="toggleCusInfo" title="课程信息" />
                                </p>
                                <p class="course-code">
                                    <Icon type="md-pricetags" />
                                    {{item[0].courseId}}
                                </p>
                            </div>
                            <div v-if="courseListS.length == 0">
                                <EmptyData :top="150" textContent="暂无学校课程"></EmptyData>
                            </div>
                        </TabPane>
                        <TabPane label="个人课程" name="private">
                            <div v-for="(item,index) in courseListP" :key="index" @click="selectCourse(index)" :class="index === curCusIndex ? 'course-list-item block-bg block-bg-active':'course-list-item block-bg'">
                                <p class="course-name">
                                    {{item.name}}
                                    <Icon type="ios-information-circle-outline" @click="toggleCusInfo" title="课程信息" />
                                </p>
                                <p class="course-code">
                                    <Icon type="md-pricetags" />
                                    {{item.id}}
                                </p>
                            </div>
                            <div v-if="courseListP.length == 0">
                                <EmptyData :top="150" textContent="暂未创建课程"></EmptyData>
                            </div>
                        </TabPane>
                    </Tabs>
                </div>
            </vuescroll>
        </div>
        <div class="course-info-wrap">
            <!--课程班级列表-->
            <div class="course-classroom-list">
                <div class="course-classroom-list-header">
                    <span class="course-classroom-label">{{$t('courseManage.classroom.classroomList')}}</span>
                    <Icon type="md-add" class="add-icon" style="margin-top:12px;" @click="addClassroom()" />
                    <Icon type="md-create" v-show="listType == 'private'" class="add-icon" style="margin-top:12px;" @click="editClassStatus = true" />
                    <Icon type="md-trash" v-show="listType == 'private'" class="add-icon" style="margin-top:12px;" @click="deleteClass()" />
                </div>
                <div class="course-classroom-list-content">
                    <div v-for="(item,index) in classList" :key="index" @click="changeClassroom(index)" :class="curClassIndex === index ? 'course-classroom-item block-bg block-bg-active':'course-classroom-item block-bg'">
                        <p class="classroom-code">
                            <span :class="listType === 'private' ? 'class-type-dym': item.openType == 1 ? 'class-type-sys':'class-type-custom'">
                                {{getClassType(item.scope,item.openType).text}}
                            </span>
                            <!--{{item.no}}-->
                        </p>
                        <p class="classroom-name">{{item.name}}</p>
                        <p class="classroom-info " v-if="item.openType == 1 || item.scope == 'private'">
                            <!--<span class="classroom-info-label">{{$t('courseManage.classroom.studentCount')}}</span>
                            <span class="classroom-info-value">{{item.studentCount}}</span>-->
                            <span class="classroom-info-label">{{$t('courseManage.classroom.headmaster')}}</span>
                            <span class="classroom-info-value">{{item.teacher.name}}</span>
                        </p>
                        <Icon size="20" custom="iconfont icon-qr-code" class="qr-code-icon" @click="showQrCode" v-if="'private' == listType" />
                    </div>
                    <div v-if="classList.length == 0">
                        <EmptyData :top="160" textContent="暂无上课班级"></EmptyData>
                    </div>
                </div>
            </div>
            <div class="course-classroom-info" id="table-height">
                <div class="course-classroom-info-header" style="padding-right:50px;">
                    <span @click="tabName = 'record'" :class="tabName == 'record' ? 'course-classroom-label line-bottom line-bottom-active':'course-classroom-label line-bottom'">课堂记录</span>
                    <span @click="tabName = 'stus'" :class="tabName == 'stus' ? 'course-classroom-label line-bottom line-bottom-active':'course-classroom-label line-bottom'">{{$t('courseManage.classroom.studentList')}}</span>
                    <div style="float:right;color:white;" v-if="(listType == 'private' && tabName == 'stus') || (listType == 'school' && tabName == 'stus' && classList[curClassIndex].openType == 2)">
                        <span class="action-btn-wrap" @click="delStudents">
                            <Icon type="md-trash" size="16" />
                            删除学生
                        </span>
                        <span class="action-btn-wrap" @click="addStuStatus = true" v-if="classList[curClassIndex] && listType == 'private'">
                            <Icon type="md-add" size="16" />
                            添加学生
                        </span>
                        <!--<span class="disable-text-icon action-btn-wrap">
                            <Icon type="md-shuffle" size="16" />
                            自动分组
                        </span>
                        <span class="disable-text-icon action-btn-wrap">
                            <Icon :type="viewType ? 'md-card':'md-list'" size="16" />
                            分组视图
                        </span>-->
                    </div>
                </div>
                <div class="course-classroom-info-content dark-iview-table animated fadeIn" v-show="tabName == 'stus'">
                    <vuescroll style="height:100%;">
                        <Table :columns="studentColumn" :data="students" @on-selection-change="(selections)=>{delSelection = selections}" :height="tableHeight" class="system-classroom-table" :loading="stuLoading" no-data-text="暂无学生">
                            <Loading slot="loading" bgColor="rgba(103, 103, 103, 0.27)"></Loading>
                            <template slot-scope="{ row ,index}" slot="action">
                                <strong></strong>
                            </template>
                            <template slot-scope="{ row, index }" slot="groupId">
                                <span>{{(row.groupId && listType == 'school') ? row.groupId : '- -'}}</span>
                            </template>
                            <template slot-scope="{ row, index }" slot="groupName">
                                <span>{{(row.groupName && listType == 'school') ? row.groupName : '未分组'}}</span>
                            </template>
                        </Table>
                    </vuescroll>
                </div>
                <div v-show="tabName == 'record'" class="animated fadeIn class-record-wrap">
                    <vuescroll>
                        <List>
                            <ListItem v-for="(item,index) in itemNum" :key="index" style="border-color:#505050;">
                                <ListItemMeta @click.native="toClassRecoerd">
                                    <p slot="title" class="record-name">力的组成</p>
                                    <span slot="avatar" style="margin-top:4px;display: inline-block;margin-left:10px;">
                                        <Icon custom="iconfont icon-whiteboard" size="30" color="white" />
                                    </span>
                                    <div slot="description" style="color:white;">
                                        <span class="hiteacher-version">
                                            系统版本：3.0.32
                                        </span>
                                        <Time class="record-time" :time="((new Date()).getTime() - 60 * 3 * 1000)" />
                                        <div class="record-action-wrap">
                                            <Icon class="action-icon" type="md-analytics" title="课程记录" @click="toClassRecoerd" />
                                            <Icon class="action-icon" type="ios-stats" title="苏格拉底报告" @click="toClassRecoerd" />
                                            <Icon class="action-icon" custom="iconfont icon-video" title="苏格拉底影片/桌面" @click="toClassRecoerd" />
                                            <Icon class="action-icon" custom="iconfont icon-hi" title="电子笔记" @click="toClassRecoerd" />
                                            <Icon class="action-icon" custom="iconfont icon-textbook" title="课例教材" @click="toClassRecoerd" />
                                            <Icon class="action-icon" type="md-share" title="分享到频道" @click="toClassRecoerd" />
                                        </div>
                                    </div>
                                </ListItemMeta>
                            </ListItem>
                        </List>
                        <p style="width:100%;text-align:center;color:#808080;margin-top:20px;">暂未对接HiTeach上传数据</p>
                    </vuescroll>
                </div>
            </div>
        </div>
        <Drawer title="课程信息" class-name="dark-iview-drawer" width="450" :closable="false" v-model="showCusInfo" @on-close="baseEditStatus = true">
            <!--基础信息-->
            <div class="course-base-info-content dark-iview-form disabled-iview-select dark-wang-editor">
                <Form ref="courseBaseInfo" label-position="top">
                    <FormItem label="课程名称" prop="name" class="disabled-iview-select">
                        <Input v-if="listType == 'school' && courseListS[curCusIndex]" v-model="courseListS[curCusIndex][0].courseName" :disabled="true" style="width:100%" placeholder="课程名称" :clearable="true"></Input>
                        <Input v-else-if="listType == 'private' && courseListP[curCusIndex]" v-model="courseListP[curCusIndex].name" :disabled="baseEditStatus" style="width:100%" placeholder="课程名称" :clearable="true"></Input>
                    </FormItem>
                    <FormItem label="课程编码" prop="id" class="disabled-iview-select">
                        <Input v-if="listType == 'school' && courseListS[curCusIndex]" v-model="courseListS[curCusIndex][0].courseId" :disabled="true" style="width:100%" placeholder="课程编码" :clearable="true"></Input>
                        <Input v-else-if="listType == 'private' && courseListP[curCusIndex]" v-model="courseListP[curCusIndex].id" :disabled="true" style="width:100%" placeholder="课程编码" :clearable="true"></Input>
                    </FormItem>
                    <FormItem :label="$t('courseManage.base.courseNotice')">
                        <div ref="courseNotice" v-show="!baseEditStatus"></div>
                        <div v-show="baseEditStatus" style="height:fit-content;color:white;font-size:16px;padding-left:10px;width:100%;">
                            <vuescroll>
                                <div v-if="listType == 'school' && courseListS[curCusIndex] && checkNotice(courseListS[curCusIndex][0].notice)" v-html="courseListS[curCusIndex][0].notice" style=""></div>
                                <div v-else-if="listType == 'private' && courseListP[curCusIndex] && checkNotice(courseListP[curCusIndex].notice)" v-html="courseListP[curCusIndex].notice" style=""></div>
                                <div v-else style="">暂无公告！</div>
                            </vuescroll>
                        </div>
                    </FormItem>
                    <FormItem label="">
                        <Button style="width:100%;margin-top:10px;" @click="edNotice">{{baseEditStatus ? '编辑':'保存'}}</Button>
                    </FormItem>
                </Form>
            </div>
        </Drawer>
        <Modal v-model="newPrivateStatus" :title="$t('courseManage.classroom.personalClassroomTitle')" @on-ok="confirmNewClass" class-name="dark-iview-modal dark-iview-form">
            <Form ref="personalClassroom" :model="privateClass" label-position="top" label-colon>
                <FormItem label="班级名称" prop="name">
                    <Input v-model="privateClass.name" :placeholder="$t('courseManage.classroom.classroomName')">
                    </Input>
                </FormItem>
                <FormItem :label="$t('courseManage.classroom.invitationCode')" prop="id">
                    <span style="font-size:18px;color:white;">{{privateClass.id}}</span>
                </FormItem>
            </Form>
        </Modal>
        <Modal v-model="editClassStatus" title="修改班级信息" @on-ok="confirmUpdClass" class-name="dark-iview-modal dark-iview-form">
            <Form v-if="editClassStatus" ref="personalClassroom" :model="courseListP[curCusIndex].classes[curClassIndex]" label-position="top" label-colon>
                <FormItem label="班级名称" prop="name">
                    <Input v-model="courseListP[curCusIndex].classes[curClassIndex].name" :placeholder="$t('courseManage.classroom.classroomName')">
                    </Input>
                </FormItem>
                <FormItem :label="$t('courseManage.classroom.invitationCode')" prop="id">
                    <span style="font-size:18px;color:white;">{{courseListP[curCusIndex].classes[curClassIndex].id}}</span>
                </FormItem>
            </Form>
        </Modal>
        <Modal v-model="addCusStatus" title="新增课程" @on-ok="confirmAddCus" class-name="dark-iview-modal dark-iview-form">
            <Form ref="addCusInfo" :model="addCusInfo" :rules="ruleAddCus">
                <FormItem prop="courseName" label="课程名称">
                    <Input type="text" v-model="addCusInfo.courseName" placeholder="课程名称..."></Input>
                </FormItem>
            </Form>
            <Form ref="addCusInfo" :model="addCusInfo" :rules="ruleAddCus">
                <FormItem prop="courseCode" label="课程编码">
                    <Input type="text" v-model="addCusInfo.courseCode" placeholder="课程编码..."></Input>
                </FormItem>
            </Form>
        </Modal>
        <Modal v-model="addStuStatus" title="添加学生" width="1200" @on-ok="confirmAddStu" class-name="dark-iview-modal">
            <StudentList @getSelectInfo="(selction)=>{selections = selction}"></StudentList>
        </Modal>
        <div class="qr-code-wrap" v-show="showQrStatus" @click="showQrStatus = false">
            <div id="qrcode" :class="showQrStatus ? 'animated fadeIn':'animated fadeOut'" ref="qrcode" style="padding:20px;background-color:white;width:320px;margin:auto;"></div>
        </div>
    </div>
</template>
<script>
import QRCode from 'qrcodejs2'
import E from '@/utils/wangEditor.js'
import StudentList from '@/components/coursemgt/StudentList.vue'
export default {
    components: {
        StudentList
    },
    data() {
        // 验证只能是字母和数字
        const validateCode = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('课程编码不能为空！'))
            }
            let zg = /^[0-9a-zA-Z]+$/
            if (zg.test(value)) {
                callback()
            } else {
                callback(new Error('课程编码只能由字母和数字组成！'))
            }
        }
        return {
            delSelection: [],
            selections: [],
            schoolClassList: [],
            tableHeight: 100,
            studentColumn: [
                {
                    title: ' ',
                    type: 'selection',
                    width: 80,
                    align: 'center'
                },
                {
                    title: this.$t('courseManage.classroom.studentTableC2'),
                    key: 'name',
                    align: 'left '
                },
                {
                    title: '账号',
                    key: 'id',
                    align: 'center',
                    sortable: true
                },
                {
                    title: this.$t('courseManage.classroom.studentTableC1'),
                    key: 'no',
                    align: 'center',
                    sortable: true
                },
                {
                    title: this.$t('courseManage.classroom.studentTableC5'),
                    slot: 'groupId',
                    align: 'center',
                    sortable: true
                },
                {
                    title: this.$t('courseManage.classroom.studentTableC6'),
                    slot: 'groupName',
                    align: 'center'
                }
            ],
            itemNum: 5,
            editClassStatus: false,
            baseEditStatus: true,
            showQrStatus: false,
            showCusInfo: false,
            listLoading: false,
            newPrivateStatus: false,
            stuLoading: false,
            selectClassStatus: false,
            listType: 'school',
            tabName: 'record',
            addCusStatus: false,
            addStuStatus: false,
            joinQRcode: undefined,
            curCusIndex: 0,
            curClassIndex: 0,
            courseListS: [],
            courseListP: [],
            addCusInfo: {
                courseName: '',
                courseCode: ''
            },
            ruleAddCus: {
                courseName: [
                    { required: true, message: '课程名称不能为空', trigger: 'change' }
                ],
                courseCode: [
                    { required: true, validator: validateCode, trigger: 'change' }
                ]
            },
            privateClass: {
                id: '',
                name: '',
                notice: ''
            },
            sysClass: {
                id: '',
                name: ''
            },
        }
    },
    methods: {
        getClassType(scope, openType) {
            if (this.listType == 'private') {
                return {
                    text: '动态名单',
                    class: ''
                }
            } else if (openType == 1) {
                return {
                    text: '常规教室',
                    class: ''
                }
            } else {
                return {
                    text: '专科教室',
                    class: ''
                }
            }
        },
        //删除学生
        delStudents() {
            if (this.delSelection.length > 0) {
                let names = this.delSelection.map(item => {
                    return item.name
                })
                this.$Modal.confirm({
                    title: '删除学生',
                    content: `确认删除${names.join(', ')}共${names.length}名学生吗？`,
                    onOk: () => {
                        this.listLoading = true
                        this.delSelection.forEach(item => {
                            let index = this.courseListP[this.curCusIndex].classes[this.curClassIndex].students.findIndex(stu => {
                                return stu.id == item.id
                            })
                            this.courseListP[this.curCusIndex].classes[this.curClassIndex].students.splice(index, 1)
                        })
                        this.$api.schoolSetting.classUpsert({
                            classroom: this.courseListP[this.curCusIndex].classes[this.curClassIndex],
                            option: 'update',
                            school_code: this.$store.state.userInfo.TEAMModelId
                        }).then(
                            (res) => {
                                if (!res.error) {
                                    this.selections = []
                                    this.$Message.success('删除成功！')
                                } else {
                                    this.$Message.error('删除失败！')
                                }
                            },
                            (err) => {
                                this.$Message.error('删除失败！')
                            }
                        ).finally(() => {
                            this.listLoading = false
                            this.baseEditStatus = !this.baseEditStatus
                        })
                    }
                })
            } else {
                this.$Message.warning('请先选择需要删除的学生！')
            }

        },
        //确认添加学生
        confirmAddStu() {
            if (this.selections.length > 0) {
                if (!this.courseListP[this.curCusIndex].classes[this.curClassIndex].students) {
                    this.$set(this.courseListP[this.curCusIndex].classes[this.curClassIndex], 'students', [])
                }
                let stuIds = this.courseListP[this.curCusIndex].classes[this.curClassIndex].students.map(item => {
                    return item.id
                })
                if (stuIds.length > 0) {
                    //如果已经有学生，根据账号去重
                    let hasRepeat = false
                    this.selections.forEach(item => {
                        if (stuIds.indexOf(item.id) == -1) {
                            this.courseListP[this.curCusIndex].classes[this.curClassIndex].students.push({
                                id: item.id,
                                name: item.name,
                                no: item.no
                            })
                        } else {
                            hasRepeat = true
                        }
                    })
                    if (hasRepeat) {
                        //this.$Message.warning('已经自动帮您去掉账号重复的学生！')
                    }
                } else {
                    let stus = this.selections.map(item => {
                        return {
                            id: item.id,
                            name: item.name,
                            no: item.no
                        }
                    })
                    this.courseListP[this.curCusIndex].classes[this.curClassIndex].students.push(...stus)
                }
                //保存操作
                this.listLoading = true
                this.courseListP[this.curCusIndex].code = this.$store.state.userInfo.TEAMModelId
                //调整为更新个人班级
                //this.$api.courseMgmt.upsertPrivateCus({
                //    course: this.courseListP[this.curCusIndex],
                //    option: 'update'
                //}).then(
                //    (res) => {
                //        if (!res.error) {
                //            this.selections.length = 0
                //            this.$Message.success('添加成功！')
                //        } else {
                //            this.$Message.error('添加失败！')
                //        }
                //    },
                //    (err) => {
                //        this.$Message.error('添加失败！')
                //    }
                //).finally(() => {
                //    this.listLoading = false
                //    this.baseEditStatus = !this.baseEditStatus
                //})
                this.$api.schoolSetting.classUpsert({
                    classroom: this.courseListP[this.curCusIndex].classes[this.curClassIndex],
                    option: 'update',
                    'school_code': this.$store.state.userInfo.TEAMModelId
                }).then(
                    (res) => {
                        if (!res.error) {
                            this.selections.length = 0
                            this.$Message.success('添加成功！')
                        } else {
                            this.$Message.error('添加失败！')
                        }
                    },
                    (err) => {
                        this.$Message.error('添加失败！')
                    }
                ).finally(() => {
                    this.listLoading = false
                    this.baseEditStatus = !this.baseEditStatus
                })
            }
        },
        //查询班级学生名单
        findClassStu() {
            this.stuLoading = true
            let params = {
                'school_code': this.listType == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,
                'id': this.classList[this.curClassIndex].id,
                //school：校本班级 teacher：私人课程校本名单 private：私人课程动态名单
                'scope': this.listType == 'school' ? 'school' : this.classList[this.curClassIndex].scope == 'school' ? 'teacher' : 'private'
            }
            this.$api.schoolSetting.getClassroomStudent(params).then(
                (res) => {
                    if (!res.error) {
                        if (res.classrooms.length > 0) {
                            if (this.listType == 'school') {
                                this.$set(this.courseListS[this.curCusIndex][this.curClassIndex], 'students', res.classrooms[0].students)
                            }
                            else {
                                this.$set(this.courseListP[this.curCusIndex].classes[this.curClassIndex], 'students', res.classrooms[0].students)
                            }
                        }
                    } else {
                        this.$Message.error('API error!')
                    }
                },
                (err) => {
                    this.$Message.error('API error!')
                }
            ).finally(() => {
                setTimeout(() => {
                    this.stuLoading = false
                }, 500)
            })
        },
        //检查课程是否为“空”
        checkNotice(content) {
            if (!content || content == '' || content == '<p><br></p>') {
                return false
            } else {
                return true
            }
        },
        //确认修改班级信息
        confirmUpdClass() {
            this.listLoading = true
            this.courseListP[this.curCusIndex].code = this.$store.state.userInfo.TEAMModelId
            this.$api.courseMgmt.upsertPrivateCus({
                course: this.courseListP[this.curCusIndex],
                option: 'update'
            }).then(
                (res) => {
                    if (!res.error) {
                        this.$Message.success('修改成功！')
                    } else {
                        this.$Message.error('修改失败！')
                    }
                },
                (err) => {
                    this.$Message.error('修改失败！')
                }
            ).finally(() => {
                this.listLoading = false
                this.editClassStatus = false
            })
        },
        //删除上课班级
        deleteClass() {
            let _this = this
            let delClass = this._.cloneDeep(this.classList[this.curClassIndex])
            this.$Modal.confirm({
                title: '删除班级',
                content: `确认删除${this.classList[this.curClassIndex].name}吗？`,
                onOk: function () {
                    _this.listLoading = true
                    let index = _this.curClassIndex
                    _this.curClassIndex = 0
                    _this.courseListP[_this.curCusIndex].classes.splice(index, 1)
                    _this.courseListP[_this.curCusIndex].code = _this.$store.state.userInfo.TEAMModelId
                    _this.$api.courseMgmt.upsertPrivateCus({
                        course: _this.courseListP[_this.curCusIndex],
                        option: 'update'
                    }).then(
                        (res) => {
                            if (!res.error) {
                                //删除个人班级数据
                                _this.$api.schoolSetting.delClassroom({
                                    id: delClass.id,
                                    scope: delClass.scope,
                                    school_code: _this.$store.state.userInfo.TEAMModelId
                                }).then(
                                    res => {
                                        _this.$Message.success('删除成功！')
                                    },
                                    err => {
                                        _this.$Message.error('删除失败！')
                                    }
                                )
                            } else {
                                _this.$Message.error('删除失败！')
                            }
                        },
                        (err) => {
                            _this.$Message.error('删除失败！')
                        }
                    ).finally(() => {
                        _this.listLoading = false
                    })
                }
            })
        },
        editCus() {
            this.toggleCusInfo()
            this.edNotice()
        },
        //保存个人课程
        saveNotice() {
            this.listLoading = true
            this.courseListP[this.curCusIndex].code = this.$store.state.userInfo.TEAMModelId
            this.$api.courseMgmt.upsertPrivateCus({
                course: this.courseListP[this.curCusIndex],
                option: 'update'
            }).then(
                (res) => {
                    if (!res.error) {
                        this.$Message.success('修改成功！')
                    } else {
                        this.$Message.error('修改失败！')
                    }
                },
                (err) => {
                    this.$Message.error('修改失败！')
                }
            ).finally(() => {
                this.listLoading = false
                this.baseEditStatus = !this.baseEditStatus
            })
        },
        edNotice() {
            if (this.baseEditStatus) {
                this.baseEditStatus = !this.baseEditStatus
                this.initEditor()
            } else {
                if (this.listType == 'private') {
                    this.saveNotice()
                } else {
                    this.baseEditStatus = !this.baseEditStatus
                    this.courseListS[this.curCusIndex][this.curClassIndex].code = this.$store.state.userInfo.schoolCode
                    this.$api.courseMgmt.upsertNotice(this.courseListS[this.curCusIndex][this.curClassIndex]).then(
                        res => {
                            if (!res.error) {
                                this.$Message.success('保存成功')
                            } else {
                                this.$Message.error('保存失败')
                            }
                        },
                        err => {
                            this.$Message.error('保存失败')
                        }
                    )
                }
            }
        },
        toggleCusInfo() {
            this.showCusInfo = !this.showCusInfo
        },
        //初始化富文本编辑器
        initEditor() {
            if (!this.noticeEditor) {
                let noticeEditor = new E(this.$refs.courseNotice)
                noticeEditor.customConfig.onchange = (html) => {
                    if (this.listType == 'school') {
                        this.courseListS[this.curCusIndex][0].notice = html
                    } else if (this.listType == 'private') {
                        this.courseListP[this.curCusIndex].notice = html
                    }
                }
                noticeEditor.customConfig.menus = [
                    'bold', // 粗体
                    'italic', // 斜体
                    'underline', // 下划线
                    'list', // 列表
                    'link', // 插入链接
                    'image' // 插入图片
                ],
                    noticeEditor.customConfig.showLinkImg = false
                noticeEditor.customConfig.uploadFileName = 'files'
                noticeEditor.create()
                noticeEditor.txt.html(this.listType == 'school' ? this.courseListS[this.curCusIndex][0].notice : this.courseListP[this.curCusIndex].notice)
                this.noticeEditor = noticeEditor
            } else {
                console.log(this.courseListS[this.curCusIndex][0].notice)
                let schoolNotice = this.courseListS[this.curCusIndex][0].notice ? this.courseListS[this.curCusIndex][0].notice : ''
                this.noticeEditor.txt.html(this.listType == 'school' ? schoolNotice : this.courseListP[this.curCusIndex].notice)
                console.log(this.courseListS)
            }

        },
        //创建二维码
        createQRCode(url) {
            this.$nextTick(() => {
                // 此时已经渲染完成
                if (this.joinQRcode == undefined) {
                    let qrcode = new QRCode('qrcode', {
                        width: 280, // 设置宽度，单位像素
                        height: 280, // 设置高度，单位像素
                        text: url // 设置二维码内容或跳转地址
                    })
                    this.joinQRcode = qrcode
                } else {
                    this.joinQRcode.clear()
                    this.joinQRcode.makeCode(url)
                }
            })
        },
        showQrCode() {
            this.showQrStatus = true
            let tId = this.$store.state.userInfo.TEAMModelId
            let tName = this.$store.state.userInfo.name
            let cId = this.classList[this.curClassIndex].id
            let cName = this.classList[this.curClassIndex].name
            this.createQRCode(`http://teammodelos-test.chinacloudsites.cn/joinclass?tId=${tId}&cId=${cId}&tName=${tName}&cName=${cName}`)
        },

        //添加上课班级
        addClassroom() {
            let randomCode = 'P'
            for (let i = 0; i < 8; i++) {
                randomCode += this.$jsFn.getBtwRandom(0, 9)
            }
            this.privateClass.id = randomCode
            this.newPrivateStatus = true
        },
        //确认添加上课班级
        confirmNewClass() {
            this.privateClass['scope'] = 'private'
            this.privateClass['code'] = this.$store.state.userInfo.TEAMModelId
            this.privateClass['teacher'] = {
                id: this.$store.state.userInfo.TEAMModelId,
                name: this.$store.state.userInfo.name
            }
            this.courseListP[this.curCusIndex].classes.push(this._.cloneDeep(this.privateClass))
            this.courseListP[this.curCusIndex].code = this.$store.state.userInfo.TEAMModelId
            this.$api.courseMgmt.upsertPrivateCus({
                course: this.courseListP[this.curCusIndex],
                option: 'update'
            }).then(
                (res) => {
                    if (!res.error) {
                        this.$Message.success('动态名单创建成功！')
                    } else {
                        this.$Message.error('动态名单创建失败！')
                    }
                },
                (err) => {
                    this.$Message.error('动态名单创建失败！')
                }
            )
        },
        //课程选项卡点击事件
        tabClick(name) {
            this.curCusIndex = 0
            if (name == 'school' && this.courseListS.length == 0) {
                this.getCourseList()
            } else if (name == 'private' && this.courseListP.length == 0) {
                this.getPrivateCus()
            } else {
                this.changeClassroom(0)
            }
        },
        changeClassroom(index) {
            this.curClassIndex = index
            if (this.listType == 'school' && !this.courseListS[this.curCusIndex][this.curClassIndex].students) {
                this.findClassStu()
            } else if (this.listType == 'private' && !this.courseListP[this.curCusIndex].classes[this.curClassIndex].students) {
                this.findClassStu()
            }
        },
        toClassRecoerd() {
            this.listLoading = true
            setTimeout(() => {
                this.$router.push({ path: '/home/classRecord' })
            }, 500)
        },
        //删除个人课程
        delCourse() {
            this.$Modal.confirm({
                title: '删除课程',
                content: `确认删除${this.courseListP[this.curCusIndex].name}吗？`,
                onOk: () => {
                    this.$api.courseMgmt.deleteCourse({
                        id: this.courseListP[this.curCusIndex].id,
                        code: this.$store.state.userInfo.TEAMModelId,
                        scope: this.courseListP[this.curCusIndex].scope
                    }).then(
                        res => {
                            if (!res.error) {
                                let index = this.curCusIndex
                                this.curCusIndex = 0
                                this.courseListP.splice(index, 1)
                                this.$Message.success('删除成功！')
                            } else {
                                this.$Message.error('删除失败！')
                            }
                        },
                        err => {
                            this.$Message.error('删除失败！')
                        }
                    )
                }
            })
        },
        selectCourse(index) {
            this.curClassIndex = 0
            this.curCusIndex = index
            if (this.classList.length > 0) {
                this.changeClassroom(0)
            }
        },
        //添加个人课程
        showAddCourse() {
            this.addCusStatus = true
        },
        confirmAddCus() {
            this.$refs['addCusInfo'].validate((valid) => {
                if (valid) {
                    let requestData = {
                        option: 'insert',
                        course: {
                            name: this.addCusInfo.courseName,
                            id: this.addCusInfo.courseCode,
                            code: this.$store.state.userInfo.TEAMModelId,
                            classes: [],
                            scope: 'private'
                        }
                    }
                    this.$api.courseMgmt.upsertPrivateCus(requestData).then(
                        (res) => {
                            if (res.error == null) {
                                this.$Message.success('保存成功!')
                                this.courseListP.push(requestData.course)
                            } else {
                                this.$Message.success('保存失败!')
                            }
                        },
                        (err) => {

                        }
                    )
                } else {
                    this.$Message.error('请完善信息再保存!');
                }
            })
        },
        //获取个人课程列表
        getPrivateCus() {
            this.listLoading = true
            let requestData = {
                id: this.$store.state.userInfo.TEAMModelId
            }
            this.$api.courseMgmt.getPrivateCusMgt(requestData).then(
                (res) => {
                    if (res.error == null) {
                        res.courses.forEach(curItem => {
                            curItem.classes.forEach(claItem => {
                                let c = this.schoolClassList.find((classItem) => {
                                    return claItem.id == classItem.id
                                })
                                if (c) {
                                    claItem.no = c.no
                                    claItem.openType = c.openType
                                }
                            })
                        })
                        this.courseListP = res.courses

                        this.selectCourse(0)
                    } else {
                        this.$Message.error('API error!')
                    }
                },
                (err) => {
                    this.$Message.error('API error!')
                }
            ).finally(() => {
                this.listLoading = false
            })
        },
        //获取标准课程列表
        getCourseList() {
            this.listLoading = true
            let requestData = {
                'code': this.$store.state.userInfo.schoolCode,
                'id': this.$store.state.userInfo.TEAMModelId
            }
            this.$api.courseMgmt.getSchoolCusMgt(requestData).then(
                (res) => {
                    if (res.error == null) {
                        res.courses.forEach((item, index) => {
                            let c = this.schoolClassList.find((classItem) => {
                                return item.id == classItem.id
                            })
                            if (c) {
                                item.no = c.no
                                item.openType = c.openType
                            }
                        })
                        console.log('res', res)
                        this.courseListS = this.$jsFn.groupBy(res.courses, 'courseId')
                        this.selectCourse(0)
                    } else {
                        this.$Message.error('API ERROR!')
                    }
                },
                (err) => {
                    this.$Message.error('API ERROR!')
                }
            ).finally(() => {
                this.listLoading = false
            })
        }
    },
    created() {
        //直接读取登录成功拿到得学校基础信息
        this.$store.dispatch('user/getSchoolProfile').then(res => {
            this.schoolClassList = res.school_classes
            this.getCourseList()
        })

        this.$nextTick(() => {
            let dom = document.getElementById('table-height')
            console.log(dom)
            console.log(dom.offsetHeight)
            this.tableHeight = dom.offsetHeight - 60
        })
    },
    computed: {
        classList() {
            if (this.listType == 'school') {
                if (this.courseListS.length > 0) {
                    return this.courseListS[this.curCusIndex]
                } else {
                    return []
                }
            } else if (this.listType == 'private') {
                if (this.courseListP.length > 0) {
                    return this.courseListP[this.curCusIndex].classes
                } else {
                    return []
                }
            }
        },
        students() {
            if (this.listType == 'school') {
                if (this.courseListS[this.curCusIndex] && this.courseListS[this.curCusIndex][this.curClassIndex]) {
                    return this.courseListS[this.curCusIndex][this.curClassIndex].students
                } else {
                    return []
                }
            } else if (this.listType == 'private') {
                if (this.courseListP[this.curCusIndex] && this.courseListP[this.curCusIndex].classes && this.courseListP[this.curCusIndex].classes[this.curClassIndex]) {
                    return this.courseListP[this.curCusIndex].classes[this.curClassIndex].students
                } else {
                    return []
                }
            } else {
                return []
            }
        }
    }
}
</script>
<style scoped lang="less">
@import "./NewMyCourse.less";
@import "./CourseClassroom.less";
</style>
<style>
.cus-list-tab .ivu-tabs-bar {
    height: 45px;
}
.cus-list-tab .ivu-tabs-nav {
    height: 45px;
    line-height: 30px;
}
.course-classroom-list-header .ivu-poptip-inner {
    background-color: #404040;
    color: white;
}

.course-classroom-list-header .ivu-poptip-arrow::after {
    display: none;
}

.course-classroom-list-header .ivu-poptip-title:after,
.course-classroom-list-header .ivu-poptip-title {
    display: none;
}
.course-classroom-info-content #loadingBox {
    margin-top: 0px !important;
}
</style>