{% extends 'base.html' %}
{% block tittle %}随机题目{% endblock tittle %}
{% block body %}
    <h1>题目</h1>
    {% if question %}
    <form id="loginForm" onsubmit="event.preventDefault(); submitForm();" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="hidden" name="questionID" value="{{ question.uid }}">
        <h2>题目文本：</h2>
        <p>{{ question.question_text }}</p><br>
        {% if question.image %}
        <img id="image-preview" width="50%" src="{{ question.image.url }}"/><br>
        {% endif %}
        <label>选择:</label><br>
        <input type="radio" id="A" name="answer" value="A" checked>
        <label for="A">A</label><br>
        <input type="radio" id="B" name="answer" value="B">
        <label for="B">B</label><br>
        <input type="radio" id="C" name="answer" value="C">
        <label for="C">C</label><br>
        <input type="radio" id="D" name="answer" value="D">
        <label for="D">D</label><br>

        <button type="submit">提交题目</button>
    </form>
    {% else %}
        <p>没有提穆啦</p>
        <h3>你的分数是：{{ user.score }}</h3>
    {% endif %}

    <!-- 错误信息显示区域 -->
    <div id="errorMessage" style="display: none;"></div>
{% endblock body %}

{% block script %}
        <script>

        function imgChange(obj) {
            var file = document.getElementById("image");
            var imgUrl = window.URL.createObjectURL(file.files[0]);
            var img = document.getElementById('image-preview');
            img.setAttribute('src', imgUrl); // 修改img标签src属性值
        };

        function submitForm() {
            var formData = new FormData($('#loginForm')[0]);
            $.ajax({
                url: "{% url 'exam:answer' %}", // Django模板标签，用于生成URL
                type: "POST",
                data: formData,
                contentType: false, // 告诉jQuery不要设置Content-Type请求头
                processData: false, // 告诉jQuery不要处理发送的数据
                success: function(response) {
                    if (response.code === 200) {
                        alert(response.message); // 成功时的消息框
                    } else {
                        alert(response.message); // 显示错误信息
                        displayErrors(response.data);
                    }
                },
                error: function() {
                    alert("An error occurred while processing your request.");
                }
            });
        }

        function displayErrors(errors) {
            $('#errorMessage').html('');
            for (let key in errors) {
                if (errors.hasOwnProperty(key)) {
                    let message = errors[key];
                    $('#errorMessage').append('<p>' + message + '</p>');
                }
            }
            $('#errorMessage').show();
        }
    </script>
{% endblock script %}