// ==UserScript==
// @name         小杭学习通答题
// @namespace    https://scriptcat.org/
// @version      1.0
// @description  自动匹配题库并填写答案，支持单选、多选、填空、简答题（点击浮动按钮启动）
// @author       ChatGPT
// @match        *://*mooc1-api.chaoxing.com/*
// @grant        none
// ==/UserScript==

(function () {
  'use strict';

  function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  function normalize(text) {
    return text
      .replace(/正确|对/g, "对")
      .replace(/错误|错/g, "错")
      .replace(/\s+/g, "")
      .toUpperCase();
  }

  async function findAnswerForQuestion(questionDiv) {
    const qid = questionDiv.getAttribute("data");
    const typeNameInput = questionDiv.querySelector("input[name^='typeName']");
    const typeName = typeNameInput ? typeNameInput.value.trim() : "";

    const textDiv = questionDiv.querySelector("h3 > div");
    if (!textDiv) return;

    const questionText = textDiv.innerText.trim().replace(/\s+/g, " ");
    if (!questionText) return;

    console.log(`📘 查询题目（${typeName}）: ` + questionText);

    try {
      const res = await fetch("https://tiku.xhwlgzs.cloud/api/questions/search?keyword=" + encodeURIComponent(questionText));
      const json = await res.json();
      if (!json || json.length === 0) {
        console.warn("❌ 无匹配题目");
        return;
      }

      const match = json[0];
      const answerText = match.answer;

      if (typeName.includes("填空题")) {
        console.log("📝 填空题，填写答案：", answerText);
        const textarea = questionDiv.querySelector("textarea[name^='answerEditor']");
        if (textarea) {
          textarea.value = answerText;
          if (window.UE && window.UE.getEditor) {
            const editor = window.UE.getEditor(textarea.id);
            if (editor) editor.setContent(answerText);
          }
          await delay(800);
          const saveBtnId = "save_" + textarea.id.replace("answerEditor", "");
          const saveBtn = document.getElementById(saveBtnId);
          if (saveBtn) saveBtn.click();
        }

      } else if (typeName.includes("简答题")) {
        console.log("📝 简答题，写入 iframe");
        const iframe = questionDiv.querySelector("iframe[id^='ueditor_']");
        if (iframe && iframe.contentDocument && iframe.contentDocument.body) {
          iframe.contentDocument.body.innerHTML = answerText.replace(/\n/g, "<br>");
        }
        await delay(800);
        const saveBtn = document.getElementById("save_" + qid);
        if (saveBtn) saveBtn.click();

      } else {
        // ✅ 单选、多选处理
        const answers = answerText.split("|").map(a => normalize(a.trim()));
        const options = questionDiv.querySelectorAll(".answerBg");
        let matchedCount = 0;

        for (const opt of options) {
          const el = opt.querySelector(".answer_p");
          const optText = el ? normalize(el.innerText.trim()) : "";
          if (answers.includes(optText)) {
            console.log("✅ 匹配成功，选择：" + optText);
            const event = new MouseEvent("click", { bubbles: true, cancelable: true });
            opt.dispatchEvent(event);
            matchedCount++;
            await delay(300);
          }
        }

        if (!matchedCount) {
          console.warn("⚠️ 没有匹配选项：" + answers.join(", "));
        }
      }

    } catch (err) {
      console.error("❌ 请求题库失败：", err);
    }
  }

  async function start() {
    console.log("🧪 开始扫描题目区域...");
    const questions = document.querySelectorAll(".questionLi");
    console.log(`📚 当前题目数：${questions.length}`);
    if (questions.length === 0) {
      console.log("⏳ 页面未加载完毕，延迟重试...");
      return setTimeout(start, 1000);
    }

    for (let i = 0; i < questions.length; i++) {
      await findAnswerForQuestion(questions[i]);
      await delay(2000);
    }
  }

  function createFloatingButton() {
    const btn = document.createElement("div");
    btn.innerText = "🎯 启动答题";
    btn.style.cssText = `
      position: fixed;
      top: 100px;
      left: 20px;
      z-index: 9999;
      background: linear-gradient(to right, #4facfe, #00f2fe);
      color: white;
      padding: 10px 18px;
      font-size: 16px;
      font-weight: bold;
      border-radius: 12px;
      cursor: pointer;
      box-shadow: 0 4px 12px rgba(0,0,0,0.2);
      user-select: none;
    `;

    // 拖动功能
    let isDragging = false;
    let offsetX, offsetY;

    btn.addEventListener("mousedown", (e) => {
      isDragging = true;
      offsetX = e.clientX - btn.offsetLeft;
      offsetY = e.clientY - btn.offsetTop;
    });

    document.addEventListener("mousemove", (e) => {
      if (isDragging) {
        btn.style.left = `${e.clientX - offsetX}px`;
        btn.style.top = `${e.clientY - offsetY}px`;
      }
    });

    document.addEventListener("mouseup", () => {
      isDragging = false;
    });

    btn.addEventListener("click", () => {
      if (!btn.dataset.clicked) {
        btn.innerText = "⏳ 正在答题...";
        btn.dataset.clicked = "true";
        start();
      }
    });

    document.body.appendChild(btn);
  }

  if (document.readyState === "complete" || document.readyState === "interactive") {
    createFloatingButton();
  } else {
    window.addEventListener("DOMContentLoaded", createFloatingButton);
  }

})();
