/**
 * CC.CALLBACK.QA
 *
 * Created by shanglt on 2017/2/6.
 */
!(function(window, document) {

    console.log('dp v.0.1.0');

    function qa(meta) {
        var questions = meta.question;
        if (questions && questions.length) {
            for (var i = 0; i < questions.length; i++) {
                var question = questions[i];
                on_cc_live_qa_question({
                    "action": "question",
                    "value": {
                        "id": question.encryptId,
                        "content": question.content,
                        "userId": question.questionUserId,
                        "userName": question.questionUserName
                    }
                });
            }
        }

        var answers = meta.answer;
        if (answers && answers.length) {
            for (var i = 0; i < answers.length; i++) {
                var answer = answers[i];
                on_cc_live_qa_answer({
                    "action": "answer",
                    "value": {
                        "questionId": answer.encryptId,
                        "content": answer.content,
                        "userId": answer.answerUserId,
                        "isPrivate": answer.isPrivate,
                        "userName": answer.answerUserName
                    }
                });
            }
        }
    }


    // 提问
    function on_cc_live_qa_question(data) {
        var question = data.value;
        $("#qas").append(this.question({
            id: question.id,
            questionUserId: question.userId,
            questionUserName: question.userName,
            content: question.content
        }));

        qaScroll();
    }

    // 回答
    function on_cc_live_qa_answer(data) {
        var answer = data.value;
        // 私密回答只能自己看
        if (answer.isPrivate) {
            return;
        }

        $("#" + answer.questionId).append(this.answer({
            answerUserName: answer.userName,
            content: answer.content,
            isFromMe: Viewer.isMe(answer.questionUserId)
        })).attr('isAnswer', 1);

        var isOnlyMyOwnQas = $(this).find('i').hasClass('active');
        if (isOnlyMyOwnQas && !Viewer.isMe(answer.questionUserId)) {
            return;
        }
        $("#" + answer.questionId).show();

        qaScroll();
    }

    if ($("#questionTemplate").length) {
        this.question = Handlebars.compile($("#questionTemplate").html());
    }
    if ($("#answerTemplate").length) {
        this.answer = Handlebars.compile($("#answerTemplate").html());
    }


    var Viewer = {
        id: $('#viewerId').val(),
        name: $('#viewerName').val(),
        role: $('#viewerRole').val(),
        // sessionId: $.cookie('sessionid'),
        isMe: function(viwerId) {
            return viwerId == this.id;
        }
    };

    function qaScroll() {
        $("#qas").parent().scrollTop($("#qas").height());
    }

    window.qa = qa;
})(window, document, undefined);