$(function () {
    $(document).on('contextmenu', onContextmenu);
    $(document).on("click", hideAnswerTime);
    function hideAnswerTime(e) {
        $(".question-answertime-items").hide();
    }
    function onContextmenu(e) {
        return false;
    }
    init();
    function init() {
        bingEvents();

    };

    function bingEvents() {
        bindQuestionType();
        bindQuestionSingle();
        bindQuestionMultiple();
        bindQuestionTime();
        bindQuestionSend();
    }

    function bindQuestionType() {
        $('.question-type-item').bind('click', function () {
            if (!$(this).hasClass('question-type-itemSelected')) {
                $(this).append(
                    $(this).parent()
                    .find('.question-type-itemSelected .question-item-icontrue')
                ).siblings()
                 .removeClass('question-type-itemSelected')
                 .end()
                 .addClass('question-type-itemSelected');
                var type = $(this).attr('data-qtype')
                switch (type) {
                    case 'single_selection':
                        $('.question-option-type[data-qtype="single_selection"]').siblings().hide().end().show()
                        break;
                    case 'multiple_selection':
                        $('.question-option-type[data-qtype="multiple_selection"]').siblings().hide().end().show()
                        break;
                    case 'boolean_selection':
                        $('.question-option-type[data-qtype="boolean_selection"]').siblings().hide().end().show()
                        break;
                    case 'subjective':
                        $('.question-option-type[data-qtype="subjective"]').siblings().hide().end().show()
                        break;
                    default:
                        break;
                }
                resetTime();
            }
        })
    }

    function bindQuestionSingle() {
        $('[data-qtype="single_selection"] .question-option-operat-remove').bind('click', function () {
            var qsis = $('.question-option-type[data-qtype="single_selection"] .question-option-item');
            if (qsis.length == 2) { return false; }
            qsis[qsis.length - 1].remove();
            var value = '';
            $('.question-option-type[data-qtype="single_selection"] .question-option-icon').each(function (index, item) {
                if (index == 0) {
                    value += item.textContent
                } else {
                    value += ' ' + item.textContent
                }
            })
            $('#singleTypeValue').text(value);
        })
        $('[data-qtype="single_selection"] .question-option-operat-add').bind('click', function () {
            var qsis = $('.question-option-type[data-qtype="single_selection"] .question-option-item');
            if (qsis.length == 6) { return false }
            var v = String.fromCharCode((qsis.length + 1 + "").charCodeAt(0) + 16); //将数字转换为ABCDEF
            $(qsis[0].parentElement).append('<div class="question-option-item"><div class="question-option-icon">' + v + '<div/></div>')
            var value = '';
            $('.question-option-type[data-qtype="single_selection"] .question-option-icon').each(function (index, item) {
                if (index == 0) {
                    value += item.textContent
                } else {
                    value += ' ' + item.textContent
                }
            })
            $('#singleTypeValue').text(value);
        })
    }

    function bindQuestionMultiple() {
        $('[data-qtype="multiple_selection"] .question-option-operat-remove').bind('click', function () {
            var qsis = $('.question-option-type[data-qtype="multiple_selection"] .question-option-item');
            if (qsis.length == 3) { return false; }
            qsis[qsis.length - 1].remove();
            var value = '';
            $('.question-option-type[data-qtype="multiple_selection"] .question-option-icon').each(function (index, item) {
                if (index == 0) {
                    value += item.textContent
                } else {
                    value += ' ' + item.textContent
                }
            })
            $('#multipleTypeValue').text(value);
        })
        $('[data-qtype="multiple_selection"] .question-option-operat-add').bind('click', function () {
            var qsis = $('.question-option-type[data-qtype="multiple_selection"] .question-option-item');
            if (qsis.length == 6) { return false }
            var v = String.fromCharCode((qsis.length + 1 + "").charCodeAt(0) + 16); //将数字转换为ABCDEF
            $(qsis[0].parentElement).append('<div class="question-option-item"><div class="question-option-icon">' + v + '<div/></div>')
            var value = '';
            $('.question-option-type[data-qtype="multiple_selection"] .question-option-icon').each(function (index, item) {
                if (index == 0) {
                    value += item.textContent
                } else {
                    value += ' ' + item.textContent
                }
            })
            $('#multipleTypeValue').text(value);
        })
    }

    function bindQuestionTime() {
        $('.question-answertime-default').bind('click', function (e) {
            e.stopPropagation();
            $('.question-answertime-items').show();
        });
        $('.question-answertime-items li').bind('click', function (e) {
            e.stopPropagation();
            $('#limitTime').text($(this).attr('value'));
            $('.question-answertime-default').text($(this).text());
            $(this).parent().hide();
        })
    }

    function bindQuestionSend() {
        $('.question-card-sendbtn').bind('click', function (e) {
            //testSend()
            var qtype = $('#exercise_type .question-type-itemSelected').attr('data-qtype');
            var qselectlist;
            if (qtype == 'single_selection') {
                qselectlist = $('.question-option-type[data-qtype="single_selection"] .question-option-item').length;
            } else if (qtype == 'multiple_selection') {
                qselectlist = $('.question-option-type[data-qtype="multiple_selection"] .question-option-item').length;
            }
            var qtime = $('#limitTime').text();
            var qbodyimgs = $('.question-body-content .qimg');

            var quiz = {
                type: 'Quiz',
                on: true,
                id: '' + Math.random(),
                lifeSpan: qtime == 0 ? -1 : parseInt(qtime) * 60 * 1000,
                questions: [{
                    type: qtype,
                    optionsCount: qselectlist
                }]
            };
            if (sendimage.length > 0) {
                quiz.questions[0]['body'] = {
                    'images': sendimage
                }
            }

            fetch("/classroomControl", {
                method: "POST",
                body: JSON.stringify(quiz)
            }).then(function (res) {
                if (res.ok) {
                    SendMsg("开始提问");
                    fetch('/classroomControl', {
                        method: 'POST',
                        body: JSON.stringify({
                            type: 'LessonRecord',
                            on: true,
                            lifeSpan: qtime == 0 ? -1 : parseInt(qtime) * 60 * 1000,
                            data: null,
                            expired: true
                        })
                    })
                    window.location.href = 'http://localhost:7017/client/answerDetails.html';
                    //window.open('http://localhost:7017/client/answerDetails.html');
                } else {
                    console.log("发送题目出错");
                }
            }, function (err) {
                console.log("发送题目出错");
            })
        });
    }

    function testSend() {
        var qtype = 'single_selection';
        //var qtype = 'multiple_selection';
        //var qtype = 'boolean_selection';
        //var qtype = 'subjective';
        var qtime = 3;
        var qselectlist;
        qselectlist = 4;
        fetch("/classroomControl", {
            method: "POST",
            body: JSON.stringify({
                type: 'Quiz',
                on: true,
                id: '' + Math.random(),
                lifeSpan: qtime == 0 ? -1 : parseInt(qtime) * 60 * 1000,
                questions: [{
                    type: qtype,
                    optionsCount: qselectlist
                }]
            }),
        }).then(function (res) {
            if (res.ok) {
                window.location.href = 'http://localhost:7017/client/answerDetails.html';
            } else {
                console.log("发送题目出错");
            }
        }, function (err) {
            console.log("发送题目出错");
        })
    }

    function resetTime() {
        $('.question-answertime-default').text('不限时');
        $('#multipleTypeValue').text('A B C D');
        $('#singleTypeValue').text('A B C D');
    }

});

var sendimage = [];
function getAskQuestionImages(data) {
    var udata = JSON.parse(data);
    var innerhtml = ''
    for (var i = 0; i < udata.UserImages.length; i++) {
        var imgurl = udata.UserImages[i]['ImageUrl'];
        var turl = 'http://localhost:7017/' + imgurl;
        var cc = '';
        if (/admin/.test(imgurl)) {
            cc = 'qimg';
            sendimage.push(imgurl);
        }
        innerhtml += '<img src="' + turl + '" class="' + cc + '" style="max-height:100%;max-width:100%;object-fit:contain;"/>';
    }
    //var rectBC = $('question-body-content').get(0).getBoundingClientRect();
    //alert(imgs[0]);
    //for (var i = 0; i < imgs.length; i++) {
    //    var img = new Image();
    //    img.src = 'http://localhost:7017/userContent/admin/' + imgs[i];
    //    alert(img.outerHTML);
    //    var rwidth = img.naturalWidth;
    //    var rheight = img.naturalHeight;
    //    if (rwidth > rectBC.width) {
    //        img.width = rectBC.width;
    //    } else {
    //        img.width = rwidth;
    //    }
    //    if (rheight > rectBC.height) {
    //        img.height = rectBC.height;
    //    } else {
    //        img.height = rheight;
    //    }
    //    innerhtml += img.outerHTML;
    //}
    $('.question-body-content').empty().append(innerhtml);
}