const client = require(path.join(__dirname, '../', 'js', 'module', 'client.js'))
const heartbeat = require(path.join(__dirname, '../', 'js', 'module', 'heartbeat.js'))

let class_app = new Vue({
    el: '#classlist_app',
    mounted: function () {
        this.onWindowLoad();
    },
    data: {
        /** 机构信息 */
        sdk_appid: 0,
        app_name: "互动课堂",
        icon_url: "",
        userInfo: {},
        /** 课堂列表 */
        class_list: [],
        class_mask: {},
        /** 状态 */
        class_filter: "will",
        cur_class_info: {},
        teacherInfo: {},  // 老师简介
        /** 弹出窗 */
        is_show_dialog: false,
        dialog_title: '',
        dialog_msg: '',
        dialog_button: [],
        dialog_callback: 0,
    },
    methods:{
        /** 窗口方法 */
        onWindowLoad: function(){
            client.init(g_data.test);
            this.login((ret, info)=>{
                if (ret){
                    g_storage.setItem('mode', g_data.mode);
                    g_storage.setItem('companyId', g_data.companyId);
                    g_storage.setItem('userId', g_data.userId);
                    g_storage.setItem('userToken', g_data.userToken);
                    this.freshClassList('will');
                }else{
                    this.showErrorMessage(info, true);
                }
            })
        },
        closeWindow: function () {
            sendIpcMessage('ComWin:Sys', 'close');
        },
        minWindow: function () {
            sendIpcMessage('ComWin:Sys', 'min');
        },
        maxWindow: function () {
            sendIpcMessage('ComWin:Sys', 'max');
        },
        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;
        },
        showErrorMessage: function (message, isBackLogin = false) {
            log.error("[TAG-LIST] showErrorMessage->" + message);
            this.showDialog(message, ['确定'], (index) => {
                if (isBackLogin) {
                    sendIpcMessage('WIN_LOGIN:OPEN');
                    sendIpcMessage('WIN_CLASSLIST:CLOSE');
                } else {
                    sendIpcMessage('QUITAPP');
                }
            });
        },

        /** 布局方法 */
        setClassFilter: function(filter){
            this.class_filter = filter;
            this.freshClassList(filter);
        },
        enterClass: function(classId){
            if (this.class_filter != 'end'){
                g_data.classId = classId;
                log.info("[TAG-LIST] enterClass->class_id:"+classId);
                sendIpcMessage('WIN_CLASS:OPEN', {});
                sendIpcMessage('ComWin:Sys', 'close');
            }            
        },
        activeClass: function(classInfo){
            this.cur_class_info = classInfo;
            this.teacherInfo = {};
            client.getUserInfo(classInfo.teacher_id, (ret, json)=>{
                if (ret){
                    this.teacherInfo = json;
                    if (!this.teacherInfo.avatar || this.teacherInfo.avatar.length < 1){
                        this.teacherInfo.avatar = "https://main.qcloudimg.com/raw/077e472486e6c6faeecf043a25f9b9ac.png";
                    }
                }
            })
        },

        /** 业务方法 */
        login: function(callback){
            client.getCompanyInfo(g_data.companyId, (ret, json) => {
                if (ret) {
                    g_data.sdkAppId = json.sdkappid;
                    this.sdk_appid = json.sdkappid;
                    this.app_name = json.name;
                    this.icon_url = json.icon;
    
                    client.getUserSig(g_data.userId, g_data.userToken, (ret, json) => {
                        if (!ret) {
                            callback(ret, '获取用户信息失败: ' + json.error_code + "|" + this.getClientErrorMsg(json));
                            return;
                        }
                        g_data.token = client.getToken();;
                        g_data.userSig = json.user_sig;
                        callback(true, '');
                        client.getUserInfo(g_data.userId, (ret, json)=>{
                            if (ret){
                                this.userInfo = json;
                                if (!this.userInfo.avatar || this.userInfo.avatar.length < 1){
                                    this.userInfo.avatar = "https://main.qcloudimg.com/raw/077e472486e6c6faeecf043a25f9b9ac.png";
                                }
                            }
                        })

                        // 心跳
                        heartbeat.init(g_data.test, this.sdk_appid, g_data.userId, g_data.userSig, (type, sub, data)=>{
                            if (type == "common"){
                                g_data.lastReportTime = heartbeat.getLastReportTime();;
                            }                            
                        }, g_data.lastReportTime);
                        heartbeat.updateModule("saas", "");
                        heartbeat.updateHeartbeat();
                    });
                } else {
                    callback(ret, '获取机构信息失败: ' + json.error_code + "|"+ this.getClientErrorMsg(json));
                }
            })
        },
        appendClassList: function(list){
            for (var i=0; i<list.length; i++){
                if (!this.class_mask.hasOwnProperty(""+list[i].class_id)){   // 当前课堂不存在
                    list[i].show_time = formatDateTime(new Date(list[i].start_time*1000), true);

                    this.class_mask[""+list[i].class_id] = true;
                    this.class_list.push(list[i]);

                    if (this.class_list.length == 1){   // 默认选中首个元素
                        this.activeClass(this.class_list[0]);
                    } 
                }else{
                    log.info("[TAG-LIST] appendClassList->ignore repeat classid: "+list[i].class_id);
                }
            }
        },
        freshClassList: function(filter){
            log.info("[TAG-LIST] freshClassList->filter: "+filter);
            this.class_list = [];
            this.class_mask = {};
            this.cur_class_info = {};
            client.getClassList(0, 100, [filter], (ret, json)=>{
                if (ret && this.class_filter == filter){
                    if (json.list)
                        this.appendClassList(json.list)             
                }
            })
            client.getPublicClassList(0, 100, [filter], (ret, json)=>{
                if (ret && this.class_filter == filter){
                    if (json.list)
                        this.appendClassList(json.list)             
                }else{
                    this.showDialog(this.getClientErrorMsg(json), ["确定"], null);
                }
            })            
        },
        getClientErrorMsg: function(json){
            if (json.error_code == '10216'){
                return 'Token过期';
            }else if (json.error_code == '10300'){
                return '最多只能提前一个小时进入课堂';
            }else if (json.error_code == '10270'){
                return '机构信息不存在';
            }else{
                return json.error_msg;
            }            
        }
    },    
})

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-LOGIN] exception->"+stackStr);
}