$(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();
        bindQuestionTime();
        bindQuestionSend();
        bindDelete();
    }

    function bindDelete() {
        $('.question-option-delete').bind('click', function () {

        })
    }

    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');
            }
        })
    }


    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() {
        if (!onSendBtn) {
            $('.question-card-sendbtn').css({ 'background-color': 'gray' });
        }
        $('.question-card-sendbtn').bind('click', function (e) {
            //testSend()
            var questions = [], qselectlist, qtype;
            if ($(".question-option-type").length > 0) {
                $(".question-option-type").each(function () {
                    // exerciseType = ;
                    qselectlist = 1;
                    qtype = this.dataset.qtype;
                    if (qtype == 'single_selection' || qtype == 'multiple_selection') {
                        qselectlist = $(this).find('.question-option-item').length;
                    }
                    questions.push({
                        type: qtype,
                        optionsCount: qselectlist - 1
                    })
                })
            } else {
                alert("至少添加一道题");
                return;
            }

            // var qtype = $('#exercise_type .question-type-itemSelected').attr('data-qtype');


            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: questions
            };
            if (sendimage.length > 0) {
                quiz.questions.forEach(function (e, index) {
                    e['body'] = { 'images': sendimage }
                })
                // quiz.questions[0]['body'] = {
                //     'images': sendimage
                // }
            }
            console.log(quiz);
            if (!onSendBtn) {
                console.log("发送题目出错 或 发送按钮不可用。");
                return;
            }

            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?skin='+skin;
                    //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?skin='+skin;
            } else {
                console.log("发送题目出错");
            }
        }, function (err) {
            console.log("发送题目出错");
        })
    }

    function resetTime() {
        $('.question-answertime-default').text('不限时');
        $('#multipleTypeValue').text('ABCD');
        $('#singleTypeValue').text('ABCD');
    }
    SendMsg("webReady");
});

var onSendBtn = false;
function getOnSendBtn(data) {
    // var udata = JSON.parse(data);
    onSendBtn = data;//udata.UserSendBtn;
    if (onSendBtn) {
        $('.question-card-sendbtn').css({ 'background-color': '' });
    }
}

function onAddQuestion() {
    var $selected = $(".question-type-content").find(".question-type-itemSelected");
    var type = $selected.attr('data-qtype');
    var $container = $(".question-card-questionoption");
    var count = $container.children().length + 1;
    //if (count > 4) {
    //    $(".question-item-add").hide();
    //}
    var html = makeHtml(type, count);
    $container.append(html);
    if (count > 4) {
        $(".question-item-add").hide();
        //.css("color", "#666").unbind();
    }
}
function makeHtml(type, count) {
    var html = "";
    switch (type) {
        case 'single_selection':
            // $('.question-option-type[data-qtype="single_selection"]').siblings().hide().end().show()
            html = '<div class="question-option-type" data-qtype="single_selection">' +
                '<div class="question-option-content clearfix">' +
                '<div class="typeValue" style="display:none">ABCD</div>' +
                '<div class="question-option-item"><div class="question-number">' + count + '.</div></div>' +
                '<div class="question-option-item"><div class="question-option-icon">A</div></div>' +
                '<div class="question-option-item"><div class="question-option-icon">B</div></div>' +
                '<div class="question-option-item"><div class="question-option-icon">C</div></div>' +
                '<div class="question-option-item"><div class="question-option-icon">D</div></div>' +
                '</div>' +
                '<div class="question-option-operat"><div class="question-option-operat-remove" onclick="removeOption(this)"></div><div class="question-option-operat-add" onclick="addOption(this)"></div></div>' +
                '<div class="question-option-delete" onclick="delItem(this)"></div>' +
                '</div>';
            break;
        case 'multiple_selection':
            html = '<div class="question-option-type" data-qtype="multiple_selection">' +
                '<div class="question-option-content clearfix">' +
                '<div class="typeValue" style="display:none">ABCD</div>' +
                '<div class="question-option-item"><div class="question-number">' + count + '.</div></div>' +
                '<div class="question-option-item"><div class="question-option-icon">A</div></div>' +
                '<div class="question-option-item"><div class="question-option-icon">B</div></div>' +
                '<div class="question-option-item"><div class="question-option-icon">C</div></div>' +
                '<div class="question-option-item"><div class="question-option-icon">D</div></div>' +
                '</div>' +
                '<div class="question-option-operat"><div class="question-option-operat-remove" onclick="removeOption(this)"></div><div class="question-option-operat-add" onclick="addOption(this)"></div></div>' +
                '<div class="question-option-delete" onclick="delItem(this)"></div>' +
                '</div>';
            // $('.question-option-type[data-qtype="multiple_selection"]').siblings().hide().end().show()
            break;
        case 'boolean_selection':
            html = '<div class="question-option-type" data-qtype="boolean_selection">' +
                '<div class="question-option-content clearfix">' +
                '<div class="question-option-title" style="display:none;">判断题</div>' +
                '<div class="question-option-item"><div class="question-number">' + count + '.</div></div>' +
                '<div class="question-option-item"><div class="question-option-icon">√</div></div>' +
                '<div class="question-option-item"><div class="question-option-icon">×</div></div>' +
                '</div>' +
                '<div class="question-option-delete" onclick="delItem(this)"></div>' +
                '</div>';
            // $('.question-option-type[data-qtype="boolean_selection"]').siblings().hide().end().show()
            break;
        case 'subjective':
            html = '<div class="question-option-type" data-qtype="subjective">' +
                '<div class="question-option-content clearfix">' +
                '<div class="question-option-title" style="display: none;">作答方式</div>' +
                '<div class="question-type-content clearFix" style="display: none;">' +
                '<div class="question-type-item question-type-itemSelected" style="width:170px;">' +
                '<div class="question-type-icon"><img src="img/photo.png" /></div>' +
                '<div class="question-item-txt">拍照作答</div>' +
                '<div class="question-item-icontrue"></div>' +
                '</div>' +
                '</div>' +
                '<div class="question-option-item"><div class="question-number">' + count + '.</div></div>' +
                '<div class="question-option-item"><span>主观题</span></div></div>' +
                '<div class="question-option-delete" onclick="delItem(this)"></div>' +
                '</div>'
            // $('.question-option-type[data-qtype="subjective"]').siblings().hide().end().show()
            break;
        default:
            break;
    }
    return html;
}
function removeOption(e) {
    var $qContent = $(e).parent().parent().find(".question-option-content");
    var qtype = $(e).parent().parent().attr("data-qtype");
    var typeValue = $qContent.find(".typeValue").text();
    if (qtype == "single_selection" && typeValue.length <= 2) return;
    if (qtype == "multiple_selection" && typeValue.length <= 3) return;
    $qContent.find(".typeValue").text(typeValue.substr(0, typeValue.length - 1));
    $qContent.children(".question-option-item:last-child").remove();
}

function addOption(e) {
    var $qContent = $(e).parent().parent().find(".question-option-content");
    var typeValue = $qContent.find(".typeValue").text();
    var qtype = $qContent.parent().attr("data-qtype");
    if (qtype == "single_selection") {
        if (typeValue.length > 5) return;
    } else {
        if (typeValue.length > 11) return;
    }
    var code = typeValue.charCodeAt(typeValue.length - 1);
    var temp = String.fromCharCode(code + 1);
    $qContent.find(".typeValue").text(typeValue + temp);
    $qContent.append('<div class="question-option-item"><div class="question-option-icon">' + temp + '</div></div>')
}

function delItem(e) {
    var $qContent = $(e).parents(".question-option-type");
    var $qContentParent = $qContent.parent();
    $qContent.remove();
    $qContentParent.find(".question-number").each(function (index, e) { $(e).text(index + 1 + ".") });

    if ($(".question-card-questionoption").children().length < 11) {
        $(".question-item-add").show();
    }
}



var skin = "";
var sendimage = [];
function getAskQuestionImages(data) {
    var udata = JSON.parse(data);
    skin = udata.Skin;
    setStyles();
    var innerhtml = ''
    for (var i = 0; i < udata.UserImages.length; i++) {
        var imgurl = udata.UserImages[i]['ImageUrl'];
        // var turl = 'http://localhost:7017/' + imgurl;
        var turl = 'img/topic/question-stem.jpg';
        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;"/>';
    }

    $('.question-body-content').empty().append(innerhtml);
    getOnSendBtn('true');
}

function setStyles() {
    var newHref = skin + '/' + $('#askquestion').attr('href');
    $('#askquestion').attr('href', newHref);
}

