import { genId } from "@/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash-es";
import dayjs from "dayjs";
import { nextTick } from "vue";
import { updateStaffChapterJson, getStaffChapterJson } from "@/api";
import animate from "animejs/lib/anime.es.js";

const usePaperStore = defineStore("paper", {
  state: () => ({
    search: {
      keyword: "",
      keywordType: 0, // 搜索类型 0-试题 1-试卷
      stagePid: "", // 阶段
      subjectId: "", // 学科
      bookId: "", // 教材ID （章节选题传入年级）
      chapterId: "", // 章节ID
      knowledgeId: "", // 知识点
      type: "", // 试卷类型
      provinces: "", // 省份
    },
    userConfig: {
      textbookId: "", // 章节教材ID
      gradeId: "", // 章节教材年级ID
    },
    searchFun: () => {},
    paperConfig: {
      maxQuantity: 60,
      showLabelType: 0, // 0-章节选题 1-知识点选题 2-同步专区 3-备考专区 4-升学专区
      paneActive: 0, // 0-试题 1-同步套题
      subjectName: "", // 阶段名
      chapterName: "", // 学科名
    },
    paper: {
      name: "",
      // updateTime: "",
      // watchTime: 32,
      // type: "同步测试",
      score: 0,
      content: [],
    },
  }),
  getters: {
    paperInitName: (state) =>
      `${dayjs().format("YYYY年MM月DD日")}${state.paperConfig.subjectName}${
        state.paperConfig.chapterName
      }试卷`,
    paperQuestionIds: (state) =>
      state.paper.content?.reduce((prev, next) => {
        prev.push(...next.children.filter((i) => !!i).map((i) => i.id));
        return prev;
      }, []) || [],
    paperTotalScore: (state) =>
      state.paper.content?.reduce(
        (prev, next) => (prev += Number(next.score)),
        0
      ) || 0,
    questionTotal: (state) =>
      state.paper.content?.reduce((prev, next) => {
        if (next.children && next.children.length > 0) {
          prev += next.children.length;
        } else {
          prev += 1;
        }
        return prev;
      }, 0) || 0,
    questionDifficulty: (state) =>
      state.questionTotal
        ? (
            state.paper.content?.reduce((prev, next) => {
              if (next.children && next.children.length > 0) {
                prev += next.children
                  .map((i) => i.difficulty)
                  .reduce((prev, next) => prev + next, 0);
              } else {
                prev += next.difficulty;
              }
              return prev;
            }, 0) / state.questionTotal
          ).toFixed(2)
        : 0,
  },
  actions: {
    // 重置筛选
    clearSearch(isAll = false) {
      if (isAll) {
        this.search = {
          keyword: "",
          keywordType: 0, // 搜索类型 0-试题 1-试卷
          stagePid: "", // 阶段
          subjectId: "", // 学科
          bookId: "", // 教材ID （章节选题传入年级）
          chapterId: "", // 章节ID
          knowledgeId: "", // 知识点
          type: "", // 试卷类型
          provinces: "", // 省份
        };
        return;
      }
      this.search.chapterId = "";
      this.search.bookId = "";
      this.search.knowledgeId = "";
      this.search.type = "";
    },
    toggleAnswer(show = null) {
      switchAnswer(this.paper.content);
      function switchAnswer(data) {
        for (let i of data) {
          if (i.children && i.children.length > 0) {
            switchAnswer(i.children);
          }
          if (show == null) {
            i.show = !i.show;
          } else {
            i.show = show;
          }
        }
      }
    },
    // 切换筛选
    switchFilter(type) {
      this.clearSearch();
      switch (type) {
        case 0: // 章节选题
          this.paperConfig.showLabelType = 0;
          this.paperConfig.paneActive = 0;
          break;
        case 1: // 知识点选题
          this.paperConfig.showLabelType = 1;
          break;
        case 2: // 同步专区
          this.paperConfig.showLabelType = 2;
          this.paperConfig.paneActive = 1;
          break;
        case 3: // 备考专区
          this.paperConfig.showLabelType = 3;
          break;
        case 4: // 升学专区
          this.paperConfig.showLabelType = 4;
          break;
      }
    },
    // 添加试题
    async addQuestions(_data, cover = false) {
      const data = cloneDeep(_data);
      if (cover) {
        this.paper.content = [];
        await nextTick();
      }
      if (!this.paper.name) {
        this.paper.name = this.paperInitName;
      }
      // 学科不一致
      const diffData = data.find(
        (i) =>
          this.search.stagePid !== i.stagePid ||
          this.search.subjectId !== i.subjectId
      );
      if (diffData) {
        await ElMessageBox.confirm(
          `试题不属于${this.paperConfig.subjectName}${this.paperConfig.chapterName}, 是否切换试卷对应的阶段学科（将清空试题篮）`,
          "提示",
          { type: "warning" }
        );
        this.search.stagePid = diffData.stagePid;
        this.search.subjectId = diffData.subjectId;
        await nextTick();
      }

      let num = 0;
      for (let i of data) {
        if (this.questionTotal >= this.paperConfig.maxQuantity) {
          ElMessage.error(
            `试题篮限制${this.paperConfig.maxQuantity}道题，请删除一些题目后重新添加`
          );
          break;
        }

        if (this.paperQuestionIds.includes(i.id)) continue; // 重复添加无效
        const d = this.paper.content.find((g) => g.type === i.type);

        // 初始化分数
        function initScore(item) {
          if (item.children && item.children.length) {
            for (let i of item.children) {
              initScore(i);
            }
          }
          item.score = 0;
          return item;
        }

        if (d) {
          d.children.push(initScore(i));
        } else {
          this.paper.content.push({
            id: genId(),
            type: i.type,
            typeId: i.typeId,
            score: 0,
            children: [initScore(i)],
          });
        }
        num++;
      }
      this.updateQNum();
      if (num > 0 && cover === false) {
        const cartDom = document.getElementById("test-basket");
        animate({
          targets: cartDom,
          scale: [1.3, 0.9, 1],
          easing: "easeInOutQuad",
        });
        ElMessage.success(`成功添加${num}道题`);
      }
    },
    // 删除试题
    removeQuestions(_data) {
      const data = cloneDeep(_data);
      let num = 0;
      for (let i of data) {
        if (!this.paperQuestionIds.includes(i.id)) continue; // 重复删除无效
        const d = this.paper.content.find((g) => g.type === i.type);
        d.children = d.children.filter((j) => j.id !== i.id);
        if (!d.children.length) {
          this.paper.content = this.paper.content.filter(
            (i) => !(i.id === d.id)
          );
        }
        num++;
      }
      this.updateQNum();
      if (num > 0) {
        const cartDom = document.getElementById("test-basket");
        animate({
          targets: cartDom,
          rotate: [0, -180, 0],
          easing: "easeInOutQuad",
        });
        ElMessage.success(`成功删除${num}道题`);
      }
    },
    // 更新题号
    updateQNum() {
      if (!this.paper.content.length) return;
      let index = 1;
      this.paper.content.forEach((i) => {
        i.children?.forEach((j) => {
          j.qNo = index;
          let qIndex = 1;
          j.children?.forEach((q) => {
            q.qNo = `${index}-${qIndex}`;
            qIndex++;
          });
          index++;
        });
      });
    },
    // 知识点跳转
    jumpToKnowledge(data) {
      if (!data.knowledgeBaseId) return;
      this.search.knowledgeId = data.knowledgeBaseId;
    },
    // 清空试题
    async clearQuestion(node, parentNode) {
      await ElMessageBox.confirm(`此操作无法恢复，确定删除吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      const parent = this.paper.content.find((i) => i.id === parentNode.id);
      parent.children = parent.children.filter((i) => !(i.id === node.id));
      if (parent.children.length === 0) {
        this.paper.content = this.paper.content.filter(
          (i) => !(i.id === parentNode.id)
        );
      }
      this.updateQNum();
    },
    // 清空试题组
    async clearQuestionGroup(data) {
      await ElMessageBox.confirm(
        `此操作无法恢复，确定删除${data.type}吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      );
      this.paper.content = this.paper.content.filter(
        (i) => !(i.id === data.id)
      );
      this.updateQNum();
    },
    // 清空试卷
    async clearPaper(alert = true) {
      if (alert) {
        await ElMessageBox.confirm(
          "此操作无法恢复，确定清空试题篮吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );
      }
      this.paper = {
        name: "",
        score: 0,
        content: [],
      };
    },
    // 保存个性化记录
    saveStaffChapter() {
      updateStaffChapterJson({
        jsonStr: JSON.stringify(this.userConfig),
      });
    },
    // 获取个性化记录
    async getStaffChapter() {
      const res = await getStaffChapterJson();
      this.userConfig.gradeId = res.gradeId;
      this.userConfig.textbookId = res.textbookId;
    },
  },
});

export default usePaperStore;
