

let classmem_app = new Vue({
    el: '#classmem_app',
    mounted: function () {
        this.getMemberList(g_data.classId, 0, true, (ret, json) => {
            this.parseMemListRet(ret, json);
        });
        this.class_type = g_data.classInfo.class_video_type;
        this.class_status = g_data.classInfo.class_status;
        this.assistant_id = g_data.classInfo.assistant_id;
        if (g_data.userId == this.assistant_id){
            this.spec_id = this.assistant_id;
        }
        setInterval(()=>{
            this.refresh(false);
        }, 3000);
    },
    data: {
        userid: '',
        nickName: '',
        user_icon: null,
        memlist: [
            // {user_id: 'student', stage: false, auth: false, mic: false, camera: false, hand: false, talk: false, kick: false}
        ],
        wholelist: [],
        index: 1,
        total: 0,
        showmemlist: [],
        fetchmemcount: 0,
        searchkey: '',
        teachernum: 1,
        teacher: '',
        loading: false,
        nodata: '',
        is_show_dialog: false,
        dialog_title: '',
        dialog_msg: '',
        dialog_button: [],
        dialog_callback: 0,
        video_user_count: 0,
        is_teacher: isTeacherRole(),
        class_type: 'public',
        assistant_id: '',
        spec_id: ''         // 特殊id,灰掉踢人及禁言
    },
    created: function () {
        this.userid = g_data.userId;
        this.nickName = g_data.nickName;
        getUserInfo(g_data.classInfo.teacher_id, (json)=>{
            this.teacher = (json && json.nickname && json.nickname.length>0) ? json.nickname : g_data.classInfo.teacher_id;
            this.user_icon = (json && json.avatar && json.avatar.length>0) ? json.avatar : 'https://main.qcloudimg.com/raw/660a0f4ffed15f717dbc7c6e357bfbdc.svg'
        });

    },
    watch: {
        searchkey: function (val) {
            if (val === '') {
                this.memlist = this.wholelist;
            } else {
                this.memlist = [];
                for (item of this.wholelist) {
                    if (item.nick.indexOf(val) !== -1) {
                        this.memlist.push(item);
                    }
                }
            }
            this.onPageChange(1);
        },
    },
    methods: {
        close: function () {
            sendIpcMessage('WIN_MEMBER:CLOSE', g_data.classId);
        },
        refresh: function (showLoading = true) {
            this.getMemberList(g_data.classId, 0, showLoading, (ret, json) => {
                this.parseMemListRet(ret, json);
                sendIpcMessage('MEMBER:CLEARHANDUP', 'refresh');
            });
            this.searchkey = '';
            this.index = 1;
        },
        getMemberList(classId, index, showloading, callback) {
            this.loading = showloading;
            if (showloading) this.nodata = '';
            data = JSON.stringify({
                class_id: classId,
                index: index,
            });
            log.info("[TAG-CLASS] getMemberList->enter");
            $.ajax({
                headers: {
                    "Content-Type": "application/json"
                },
                type: "POST",
                url: getServerDomain() + "/saas/v1/member/runtime/list?sdkappid=" + g_data.sdkAppId + "&user_id=" + g_data.userId + "&token=" + g_data.token + "&random=" + Math.floor(Math.random() * 10000),
                data: data,
                success: function (json) {
                    if (json && json.error_code === 0) {
                        log.info("[TAG-CLASS]  getMemberList->success: " + JSON.stringify(json, null, 2));
                        callback(true, json);
                    } else {
                        log.error("[TAG-CLASS]  getMemberList->failed: " + JSON.stringify(json, null, 2));
                        callback(false, JSON.stringify(json));
                    }
                },
                error: function (xhr, status, err) {
                    callback(false, "", xhr.status + ': ' + xhr.statusText);
                    log.info("[TAG-CLASS] getMemberList->error: " + xhr.status + ': ' + xhr.statusText);
                }
            });
        },
        permissionControl: function(data, successcb){
            reportEvent(g_data.classId, "PermissionControl", data, (ret, json)=>{
                if (!ret || json.error_code != 0){  // 失败了
                    var error_msg = (json.error_code==10228) ? "已达到上麦上限" :json.error_msg;
                    this.showDialog("失败:"+error_msg, ['确定'], null);
                }else{
                    successcb && successcb();
                }
            })
        }, 
        changeStage(user_id){
            let index = 0;
            for (let i = 0; i < this.memlist.length; ++i) {
                if (this.memlist[i].user_id === user_id) {
                    index = i;
                    break;
                }
            }
            if (index >= this.memlist.length) return;
            let stageOn = this.memlist[index].mic || this.memlist[index].camera;            
            this.permissionControl({
                enable: !stageOn ? 1: 0,
                rights: ["mic", "camera"],
                objectId: [this.memlist[index].user_id]
            }, ()=>{
                this.memlist[index].mic = !stageOn;
                this.memlist[index].camera = !stageOn;
                this.memlist[index].hand = false;
            })
            //ctlSetRights(!stageOn, ["mic", "camera"], [this.memlist[index].user_id]);
            //reportEvent(g_data.classId, "apply", {user_id: this.memlist[index].user_id, operate: "stage", enable: stageOn ? 1 : 0});
        },
        changeAuth(user_id){
            if (this.class_status != 'ing'){
                this.showDialog("还没有开始上课", ['确定'], null);
                return ;
            }
            let index = 0;
            for (let i = 0; i < this.memlist.length; ++i) {
                if (this.memlist[i].user_id === user_id) {
                    index = i;
                    break;
                }
            }
            if (index >= this.memlist.length) return;
            this.memlist[index].auth = !this.memlist[index].auth;
            this.memlist[index].hand = false;
            ctlSetRights(this.memlist[index].auth, ["draw"], [this.memlist[index].user_id]);
            //reportEvent(g_data.classId, "apply", {user_id: this.memlist[index].user_id, operate: "auth", enable: this.memlist[index].auth ? 1 : 0});
            this.permissionControl({
                enable: this.memlist[index].auth ? 1: 0,
                rights: ["enable_draw"],
                objectId: [this.memlist[index].user_id]
            })
        },
        changeMic(user_id) {
            let index = 0;
            for (let i = 0; i < this.memlist.length; ++i) {
                if (this.memlist[i].user_id === user_id) {
                    index = i;
                    break;
                }
            }
            if (index >= this.memlist.length) return;
            let micon = this.memlist[index].mic;
            //ctlSetRights(!micon, ["mic"], [this.memlist[index].user_id]);            
            //reportEvent(g_data.classId, "apply", {user_id: this.memlist[index].user_id, operate: "mic", enable: !micon ? 1 : 0});
            this.permissionControl({
                enable: !micon ? 1: 0,
                rights: ["mic"],
                objectId: [this.memlist[index].user_id]
            }, ()=>{
                this.memlist[index].mic = !micon;
                this.memlist[index].hand = false;
            })
        },
        changeCamera(user_id) {
            let index = 0;
            for (let i = 0; i < this.memlist.length; ++i) {
                if (this.memlist[i].user_id === user_id) {
                    index = i;
                    break;
                }
            }
            if (index >= this.memlist.length) return;
            let cameraon = this.memlist[index].camera;
            //ctlSetRights(!cameraon, ["camera"], [this.memlist[index].user_id]);            
            //reportEvent(g_data.classId, "apply", {user_id: this.memlist[index].user_id, operate: "camera", enable: !cameraon ? 1 : 0});
            this.permissionControl({
                enable: !cameraon ? 1: 0,
                rights: ["camera"],
                objectId: [this.memlist[index].user_id]
            }, ()=>{
                this.memlist[index].camera = !cameraon;
                this.memlist[index].hand = false;
            })
        },
        changeTalk(user_id) {
            if (user_id == this.spec_id) return;
            let index = 0;
            for (let i = 0; i < this.memlist.length; ++i) {
                if (this.memlist[i].user_id === user_id) {
                    index = i;
                    break;
                }
            }
            if (index >= this.memlist.length) return;
            let talkon = this.memlist[index].talk;
            ctlControl(talkon ? "mutemsg" : "unmutemsg", [this.memlist[index].user_id]);
            this.memlist[index].talk = !talkon;
            this.memlist[index].hand = false;
            //reportEvent(g_data.classId, "apply", {user_id: this.memlist[index].user_id, operate: "slience", enable: talkon ? 1 : 0});
            this.permissionControl({
                enable: talkon ? 1: 0,
                rights: ["silence"],
                objectId: [this.memlist[index].user_id]
            })
        },
        dropHand(user_id){
            let index = 0;
            for (let i = 0; i < this.memlist.length; ++i) {
                if (this.memlist[i].user_id === user_id) {
                    index = i;
                    break;
                }
            }
            if (index >= this.memlist.length) return;
            this.memlist[index].hand = false;
            reportEvent(g_data.classId, "PermissionControl", {
                enable: 1,
                rights: [],
                objectId: [this.memlist[index].user_id]
            })
        },
        kickOff(user_id) {
            if (user_id == this.spec_id) return;
            let memindex = 0;
            for (let i = 0; i < this.memlist.length; ++i) {
                if (this.memlist[i].user_id === user_id) {
                    memindex = i;
                    break;
                }
            }
            if (memindex >= this.memlist.length) return;
            this.showDialog('是否踢出学生 ' + this.showmemlist[memindex].nick, ['是', '否'],(index)=>{
                if (index === 0) {
                    for (let i = 0; i < this.wholelist.length; ++i) {
                        if (this.showmemlist[memindex].user_id === this.wholelist[i].user_id) {
                            this.wholelist.splice(i, 1);
                            break;
                        }
                    }
                    this.total--;
                    ctlControl("kickoff", [this.showmemlist[memindex].user_id]);
                    this.onPageChange(this.index);
                }
            });
        },
        muteAll: function(){
            this.showDialog('是否收到所有学生麦克风权限', ['是', '否'], (index)=>{
                if (index === 0){
                    var members = [];
                    for (let i=0; i<this.wholelist.length; i++){
                        members.push(this.wholelist[i].user_id);
                    }
                    this.permissionControl({
                        enable: 0,
                        rights: ["mic"],
                        objectId: members
                    }, ()=>{
                        this.refresh(false);
                    })
                }
            })
        },
        stageOffAll: function(){
            this.showDialog('是否收到所有学生音视频权限', ['是', '否'], (index)=>{
                if (index === 0){
                    var members = [];
                    for (let i=0; i<this.wholelist.length; i++){
                        members.push(this.wholelist[i].user_id);
                    }
                    this.permissionControl({
                        enable: 0,
                        rights: ["mic", "camera"],
                        objectId: members
                    }, ()=>{
                        this.refresh(false);
                    })
                }
            })
        },
        onDlgClick: function(index){
          if (null != this.dialog_callback){
            this.dialog_callback(index);
          }
          this.is_show_dialog = false;
          this.is_show_msg = false;
        },
        showDialog: function(message, buttons, callback){
          this.dialog_title = '成员管理';
          this.dialog_msg = message,
          this.dialog_button = buttons;
          this.dialog_callback = callback;
          this.is_show_dialog = true;
          this.is_show_msg = true;
        },
        onPageChange: function (index) {
            this.index = index;
            --index;
            const start = index * 5;
            let end = start + 5;
            if (end > this.wholelist.length && this.wholelist.length < this.total - this.teachernum) {
                // ++this.fetchDocIndex;
                // todo
                // this.getClassDocList(this.publicdoc, this.fetchDocIndex, (success, data) => {
                //     if (success) {
                //         this.parseDocListRet(success, data);
                //     }
                // });
            } else {
                end = end > this.memlist.length ? this.memlist.length : end;
                this.showmemlist = this.memlist.slice(start, end);
            }
        },
        parseMemListRet: function (ret, json) {            
            if (ret) {
                let members = json.list;
                this.total = json.total;
                this.memlist = [];
                let index = 0;
                for (let i = 0; i < members.length; ++i) {
                    if (g_data.classInfo.teacher_id === members[i].user_id) {
                        this.total--;
                        continue;
                    }
                    let member = {
                        user_id: members[i].user_id,
                        nick: members[i].nickname + (this.assistant_id===members[i].user_id ? "(助教)": ""),
                        mic: members[i].status.mic,
                        camera: members[i].status.camera,
                        hand: members[i].status.hand_up,
                        talk: !members[i].status.silence,
                        auth: members[i].status.enable_draw,
                        kick: false,
                        index: index,
                    };
                    this.memlist.push(member);
                    ++index;
                }
                // this.memlist.sort((a, b) => {
                //     return a.nick.localeCompare(b.nick);
                // });
                this.wholelist = this.memlist;
                this.showmemlist = this.memlist.slice(0, 5);

            }
            this.loading = false;
            if (this.wholelist.length == 0) {
                this.nodata = '还没有学生加入课堂';
            }
        }
    }
});

ipcRenderer.on('start', (e, videoUserCount) => {
  log.info("[TAG-CLASS] CTL:Class->open class member list with count: " + videoUserCount);
  classmem_app.video_user_count = videoUserCount;
})

ipcRenderer.on('TRTC:Update', (e, videoUserCount) => {
  log.info("[TAG-CLASS] CTL:Class->update trtc video user count: " + videoUserCount);
  classmem_app.video_user_count = videoUserCount;
})

Vue.config.errorHandler = (err, vm) =>{
    let { message, name, script, line, column, stack } = err;
    // 在vue提供的error对象中，script、line、column目前是空的。但这些信息其实在错误栈信息里可以看到。
    script = script ? script : '';
    line = line ? line : 0;
    column = line ? line : 0;
    // 解析错误栈信息
    let stackStr = stack ? stack.toString() : `${name}:${message}`;

    log.error("[TAG-MEM] exception->"+stackStr);
}