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

let question_app = new Vue({
    el: '#question_app',
    mounted: function(){
        this.onWindowLoad();
    },
    data: {
        /** 答题卡信息 */
        class_id: 0,
        question_id: 0,
        options: ['A', 'B', 'C', 'D'],
        answers: [],
        correct_answer: [],
        /** 状态信息 */
        is_question_set: false,
        is_student: false,
        sync_timer: null,
        use_time: "",
        /** 统计信息 */
        reply_detail: [],
        //reply_detail: [{nick_name: "studentA", reply_answer: ['A', 'B'], reply_cost_time: 3}, {nick_name: "mine01", reply_answer: ['A', 'B'], reply_cost_time: 5}, {nick_name: "eric", reply_answer: ['A', 'B'], reply_cost_time: 6}, {nick_name: "小程序", reply_answer: ['A', 'C'], reply_cost_time: 6}],
        //select_count: [4, 3, 1, 0],
        select_count: [],
        drop_count: 0,
        correct_percent: 0,
        /** 学生信息展示 */
        is_commit: false,
        is_correct: false,
        cost_time: '',
        /** 弹出窗 */
        is_show_dialog: false,
        dialog_title: '',
        dialog_msg: '',
        dialog_button: [],
        dialog_callback: 0,
    },
    methods: {
        /** 窗口事件 */
        onWindowLoad: function(){
            // 查询答题卡状态
            client.init(g_data.test, g_data.sdkAppId, g_data.userId, g_data.token);
            this.class_id = g_data.classId;
            if (g_data.userId == g_data.classInfo.teacher_id && g_data.curQuestionId){ // 是老师，尝试恢复
                client.queryQuestionInfo(this.class_id, g_data.curQuestionId, g_data.userId, (ret, json)=>{
                    this.init(json);
                });
            }
        },
        closeWindow: function(){
            if(this.is_student && !this.is_commit){
                client.commitAnswer(this.class_id, this.question_id, [], (ret, json)=>{
                    sendIpcMessage('ComWin:Sys', 'close');
                })
            }else{
                sendIpcMessage('ComWin:Sys', 'close');
            }            
        },
        onCreateQuestion: function(){            
            this.question_id = this.generateQuestionId();
            client.createQuestion(this.class_id, this.question_id, this.options, this.correct_answer, (ret, json)=>{
                if (ret){
                    this.is_question_set = true;
                    g_data.curQuestionId = this.question_id;
                    for (var i=0; i<this.options.length; i++){
                        this.select_count[i] = 0;
                    }
                    this.showActionResult();
                }else{
                    this.showDialog("创建答题卡失败: "+this.getErrorInfo(json.error_code), ['确定'], (index)=>{                        
                    })
                }               
            })            
        },
        onCommitAnswer: function(){            
            if (null != this.sync_timer){
                clearInterval(this.sync_timer);
                this.sync_timer = null;
            }
            client.commitAnswer(this.class_id, this.question_id, this.answers, (ret, json)=>{
                if(ret){
                    this.is_commit = true;
                    this.correct_answer = json.correct_answer;
                    if (this.answers.join("") == json.correct_answer.join("")){
                        this.is_correct = true;
                    }
                    this.cost_time = formatSecs(json.reply_cost_time);
                }
            })
        },
        onCancelQuestion: function(){
            client.cancelQuestion(this.class_id, this.question_id, "cancel_question", (ret, json)=>{
                g_data.curQuestionId = 0;
                g_data.curTickCount = 0;
                sendIpcMessage('ComWin:Sys', 'close');
            })
        },
        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;
        },

        /** 布局方法 */
        addOption: function(){
            if (this.options.length > 7){
                return;
            }else if (this.options.length>0){
                this.options.push(String.fromCharCode(this.options[this.options.length-1].charCodeAt()+1));
            }else{
                this.options.push('A');
            }
        },
        removeOption: function(){
            var op = this.options.pop();
            // 从答案中移除
            var index = this.correct_answer.indexOf(op);
            if (index != -1){
                this.correct_answer.splice(index, 1);
            }
        },
        selectAnswer: function(op){
            if (this.is_student){
                if (this.is_commit) return;
                var index = this.answers.indexOf(op);
                if (index != -1){
                    this.answers.splice(index, 1);
                }else{
                    this.answers.push(op);
                }
                this.answers = this.answers.sort();
            }else{
                var index = this.correct_answer.indexOf(op);
                if (index != -1){
                    this.correct_answer.splice(index, 1);
                }else{
                    this.correct_answer.push(op);
                }
                this.correct_answer = this.correct_answer.sort();
            }
        },

        /** 内部方法 */
        init: function(data){
            log.info("[TAG-QUESTION] init->"+JSON.stringify(data));
            this.question_id = data.question_id;
            this.options = data.options;
            if (g_data.userId == g_data.classInfo.teacher_id){
                this.is_student = false;
                this.is_question_set = true;
                g_data.curQuestionId = this.question_id;
                for (var i=0; i<this.options.length; i++){
                    this.select_count[i] = 0;
                }
                this.showActionResult();
            }else{
                this.is_student = true;
                g_data.curTickCount = 0;
                this.sync_timer = setInterval((questionId) => {
                    g_data.curTickCount ++;
                    this.cost_time = formatSecs(this.curTickCount);              
                }, 1000, this.question_id);    
            }                        
        },
        generateQuestionId: function(){
            return g_data.classId+"_"+new Date().getTime();
        },
        showActionResult: function(){
            sendIpcMessage('WIN_QUESTION:RESIZE', 300);
            var timerSync = (questionId)=>{
                g_data.curTickCount ++;
                this.use_time = formatSecs(g_data.curTickCount);
                if (g_data.curTickCount%3 == 1){
                    this.syncResult();
                }
            }
            timerSync(this.question_id);
            this.sync_timer = setInterval(timerSync, 1000, this.question_id);
            //timerSync(this.question_id);
        },
        syncResult: function(){
            client.queryQuestionResult(this.class_id, this.question_id, (ret, json)=>{
                if (ret){
                    this.drop_count = 0;
                    var correct_count = 0;
                    if (this.correct_answer.length==0){
                        this.correct_answer = json.correct_answer;
                    }
                    if (json.reply_detail != null){
                        this.reply_detail = json.reply_detail;
                        for (var i=0; i<this.reply_detail.length; i++){
                            var cur_detail = this.reply_detail[i];
                            cur_detail.correct = false;
                            if (cur_detail.reply_answer.length == 0){
                                this.drop_count ++;
                            }else if (cur_detail.reply_answer.join('') == this.correct_answer.join('')){
                                cur_detail.correct = true;
                                correct_count++;
                            }
                            cur_detail.nick_name=cur_detail.reply_id;      // 先置空
                            cur_detail.cost_time=formatSecs(cur_detail.reply_cost_time, false);
                            cur_detail.nick_name = client.getQuickUserNick(cur_detail.reply_id);
                            //client.getUserInfo(cur_detail.reply_id, (ret, json) => {
                            //    if (ret){
                            //        cur_detail.nick_name = json.nickname;  
                            //    }
                            //});
                        }
                        this.correct_percent = Math.floor(correct_count / this.reply_detail.length * 100);
                        for (var i=0; i<this.options.length; i++){
                            this.select_count[i] = 0;
                            for (var j=0; j<this.reply_detail.length; j++){
                                if (this.reply_detail[j].reply_answer.indexOf(this.options[i]) != -1){
                                    this.select_count[i] ++;
                                }
                            }
                        }
                    }
                }                
            });
        },
        getErrorInfo: function(errorCode){
            switch(errorCode){
                case 10003: return "没有设置正确答案";
                default: return errorCode;
            }
        }
    }
})

ipcRenderer.on('start', function (e, data) {
    if (data.hasOwnProperty("question_id")){
        question_app.init(data);
    }
})