(function () {

    function ready(fn) {
        if (document.readyState === 'complete') fn();
        else window.addEventListener('load', fn);
    }

    ready(function () {

        /* ===== 日志面板 ===== */
        var panel = document.createElement('textarea');
        panel.id = '__AUTO_LOG__';
        panel.readOnly = true;
        panel.style.cssText =
            'position:fixed;right:10px;top:10px;width:420px;height:300px;' +
            'z-index:999999;background:#000;color:#0f0;font-size:12px;' +
            'padding:8px;border:1px solid #0f0;resize:none;';
        document.body.appendChild(panel);

        /* ===== 关闭按钮 ===== */
        var closeBtn = document.createElement('button');
        closeBtn.innerText = '关闭窗口';
        closeBtn.style.cssText =
            'position:fixed;right:10px;top:320px;z-index:999999;' +
            'padding:4px 8px;font-size:12px;background:#222;color:#0f0;border:1px solid #0f0;cursor:pointer;';
        document.body.appendChild(closeBtn);

        closeBtn.addEventListener('click', function() {
            panel.style.display = 'none';
            closeBtn.style.display = 'none';
            console.log('[AUTO] 面板已隐藏，脚本继续运行');
        });

        function log(qid, msg) {
            var text = '[题号:' + qid + '] ' + msg;
            panel.value += text + '\n';
            panel.scrollTop = panel.scrollHeight;
            console.log('[AUTO]', text);
        }

        document.addEventListener('keydown', function (e) {
            if (e.ctrlKey && e.key.toLowerCase() === 'l') {
                panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
            }
        });

        log('系统', '日志系统已启动');

        /* ===== 类型映射 ===== */
        var TYPE_MAP = {
            '单选题': 0,
            '多选题': 1,
            '填空题': 2,
            '判断题': 3,
            '简答题': 4
        };

        /* ===== XHR 请求 ===== */
        function request(body, cb) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'https://api.tiku.xhwlgzs.cn/v1/questions/search', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.setRequestHeader('Authorization', '712d9ed5e4734a3f852e1bddf030a335');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    try { cb(JSON.parse(xhr.responseText)); }
                    catch (e) { cb(null); }
                }
            };
            xhr.send(JSON.stringify(body));
        }

        /* ===== 填空/简答题 UEditor处理 ===== */
        function fillUEditor(qid, answer) {
            var editors = [];
            var inputElements = document.querySelectorAll('[name^="answerEditor' + qid + '"], [name="answer' + qid + '"]');

            log(qid, '查找UEditor编辑器，找到 ' + inputElements.length + ' 个元素');

            inputElements.forEach(function(input) {
                var editorId = input.id || input.name;
                var editor = window.UE ? window.UE.getEditor(editorId) : null;
                if (editor) {
                    editors.push(editor);
                    log(qid, '找到UEditor实例: ' + editorId);
                }
            });

            if (editors.length === 0) return;

            editors.forEach(function(editor) {
                try {
                    editor.ready(function() {
                        editor.setContent(answer);
                        editor.fireEvent('contentchange');
                        log(qid, 'UEditor设置答案成功');

                        var editorIdNum = editor.key.replace('answerEditor','');
                        var saveBtn = document.querySelector('#save_' + editorIdNum);
                        if (saveBtn) {
                            saveBtn.click();
                            log(qid, '自动点击保存按钮: ' + saveBtn.id);
                        }
                    });
                } catch (e) {
                    log(qid, 'UEditor设置失败: ' + e.message);
                }
            });
        }

        /* ===== 答案规范化 ===== */
        function normalizeAnswer(ans) {
            if (!ans) return '';
            ans = ans.trim();
            if (ans === '正确' || ans === '对') return '对';
            if (ans === '错误' || ans === '错') return '错';
            return ans;
        }

        /* ===== 填答案 ===== */
        function fill(q, type, answer) {
            var qid = q.getAttribute('data');
            function norm(s) { return s.replace(/\s+/g, '').trim(); }

            if (type === 2 || type === 4) {
                log(qid, '处理填空/简答题，答案: ' + answer);
                fillUEditor(qid, answer);
                return;
            }

            var options = [];
            q.querySelectorAll('.answerBg').forEach(function (d) {
                var span = d.querySelector('span');
                var txt = d.querySelector('.answer_p');
                if (span && txt) {
                    options.push({ raw: txt.innerText.trim(), norm: norm(txt.innerText), span: span });
                }
            });

            function matchAndClick(val) {
                var nVal = normalizeAnswer(norm(val));

                for (var i = 0; i < options.length; i++) {
                    if (normalizeAnswer(options[i].norm) === nVal) {
                        options[i].span.click();
                        log(qid, '精确匹配: ' + options[i].raw);
                        return true;
                    }
                }

                for (var j = 0; j < options.length; j++) {
                    var optVal = normalizeAnswer(options[j].norm);
                    if (optVal.indexOf(nVal) !== -1 || nVal.indexOf(optVal) !== -1) {
                        options[j].span.click();
                        log(qid, '模糊匹配: ' + options[j].raw);
                        return true;
                    }
                }

                log(qid, '未匹配答案值: ' + val);
                return false;
            }

            if (type === 0 || type === 3) {
                matchAndClick(answer);
            } else if (type === 1) {
                answer.split('###').forEach(function (v) {
                    if (v.trim()) matchAndClick(v);
                });
            }
        }

        /* ===== 获取题目文本 ===== */
        function getQuestionText(q) {
            var titleDiv = q.querySelector('h3 > div') || q.querySelector('h3');
            return titleDiv ? titleDiv.innerText.trim() : '';
        }

        /* ===== 主流程 ===== */
        var list = document.querySelectorAll('div.questionLi');
        log('系统', '检测到题目数: ' + list.length);

        var index = 0;
        function next() {
            if (index >= list.length) {
                log('系统', '全部完成');
                return;
            }

            var q = list[index++];
            var qid = q.getAttribute('data');
            var title = getQuestionText(q);
            var typeNameInput = q.querySelector('input[name^="typeName"]');
            var typeName = typeNameInput ? typeNameInput.value : '';
            var type = TYPE_MAP[typeName] || 0;

            log(qid, '开始处理 - 类型: ' + typeName + ', 题目: ' + (title.length > 50 ? title.substring(0, 50) + '...' : title));

            var opts = {};
            if (type === 0 || type === 1 || type === 3) {
                q.querySelectorAll('.answerBg').forEach(function (d) {
                    var txt = d.querySelector('.answer_p');
                    if (txt) opts[txt.innerText.trim()] = txt.innerText.trim();
                });
            }

            request({
                value: title,
                type: type,
                options: opts
            }, function (res) {
                if (res && res.code === 200 && res.data && res.data.answer) {
                    log(qid, '命中答案: ' + res.data.answer);
                    fill(q, type, res.data.answer);
                } else {
                    log(qid, '未匹配答案');
                }

                setTimeout(next, type === 4 ? 500 : 300);
            });
        }

        setTimeout(next, 1000);
    });

})();
