<template>
  <div class="page-content" v-loading="queryLoading">
    <div class="page-title">
      <span class="default-title">错题组卷</span>
      <div>
        <el-select
          v-model="formData.grade"
          placeholder=""
          style="width: 100px"
          @change="changeGrade"
        >
          <el-option
            v-for="item in gradeList"
            :key="item.grade"
            :label="item.gradeName"
            :value="item.grade"
          >
          </el-option>
        </el-select>
        <el-select
          @change="changeSubject"
          v-model="formData.subjectName"
          placeholder=""
          style="width: 100px; margin-left: 10px"
        >
          <el-option
            v-for="(item, index) in subjectList"
            :key="index"
            :label="item.toString()"
            :value="item"
          >
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="info">
      <div class="box-search page-padding">
        <el-row :gutter="20">
          <el-col class="col-margin" :span="24"
            ><span style="font-weight: 600">班级：</span>
            <div
              @click="handleClass(item.classId)"
              class="select-box"
              :class="item.classId === formData.classId ? 'Selected' : ''"
              v-for="(item, index) in classList"
              :key="index"
            >
              {{ item.className }}
            </div>
          </el-col>
          <el-col class="col-margin" :span="12">
            <span style="font-weight: 600">时间：</span>
            <el-date-picker
              :clearable="false"
              value-format="yyyy-MM-dd"
              class="filter-datePicker"
              v-model="formData.dateRange"
              type="daterange"
              range-separator="-"
            >
            </el-date-picker>
            <div
              @click="handleDate(item.type)"
              class="select-box"
              :class="item.type === formData.type ? 'Selected' : ''"
              v-for="(item, index) in dateList"
              :key="index"
            >
              {{ item.name }}
            </div>
          </el-col>
          <el-col class="col-margin" :span="8">
            <span style="font-weight: 600">得分率：</span>
            <div>
              <el-input
                v-model="formData.startScoreRate"
                type="number"
                :min="minValue"
                :max="maxValue"
                @change="startValidateInput(formData.startScoreRate)"
                placeholder="请输入一个数字"
                style="width: 70px; margin-right: 4px"
              ></el-input
              >% ~
              <el-input
                v-model="formData.endScoreRate"
                type="number"
                :min="minValue"
                :max="maxValue"
                @change="endValidateInput(formData.endScoreRate)"
                placeholder="请输入一个数字"
                style="width: 70px; margin-right: 4px"
              ></el-input>
              %
            </div>
          </el-col>
          <el-col class="col-margin" :span="7"
            ><span
              style="font-weight: 600; width: fit-content; white-space: nowrap"
              >题型：</span
            >
            <div
              @click="handleQuestion(item.value)"
              class="select-box"
              :class="item.value === formData.questionType ? 'Selected' : ''"
              v-for="(item, index) in questionList"
              :key="index"
            >
              {{ item.label }}
            </div></el-col
          >
          <el-col class="col-margin" :span="2"
            ><el-button
              @click="handleSearch"
              style="background: #6b73f5"
              type="primary"
              y
              >筛选错题</el-button
            ></el-col
          >
        </el-row>
      </div>
      <div class="box-info">
        <div class="box-info-title">
          错题列表
          <span
            >(共<span style="color: #000000; padding: 0 3px">{{
              this.listPage.total
            }}</span
            >道题)</span
          >
        </div>
        <div class="topic" v-for="(item, index) in topicList" :key="index">
          <div class="topic-title">
            <div style="display: flex">
              <div style="display: flex; align-items: center">
                <span class="size"> 第 {{ item.questionIndex }} 题 </span>
                <div
                  class="select-box Selected size"
                  style="padding: 3px 5px; margin-right: 20px"
                >
                  {{
                    questionList.find(
                      (subItem) => subItem.value == item.questionType
                    ).label
                  }}
                </div>
              </div>
              <div>
                <span class="color size"> 得分率： </span>
                <span class="score-color size">{{ item.scoreRate }}%</span>
                <span class="size">({{ item.joinClassNames }})</span>
              </div>
            </div>
            <div>
              <span class="color size">来自试卷：</span
              ><span class="size">{{ item.paperName }}</span>
              <span class="color size" style="margin-left: 20px"
                >测试时间：</span
              ><span class="size">{{ item.testTime }}</span>
            </div>
          </div>

          <iframe
            class="topic-info"
            :src="item.screenshot"
            :ref="'iframe' + index"
            style="width: 100%"
            @load="onIFrameLoad(index)"
          />
          <!-- <div class="topic-info" v-html="item.modifiedHtml"></div> -->
          <div class="topic-bottom">
            <div>
              <span
                v-if="item.answerScreenshot"
                class="knowledge size"
                @click="handleAnalysis(item.answerScreenshot)"
                ><i class="el-icon-key"></i>查看解析</span
              >
              <span class="color size">知识点：</span>
              <span class="size">{{ item.knowledge }}</span>
            </div>
            <el-button
              v-if="!questions.some((obj) => item.id === obj.id)"
              class="button"
              type="primary"
              @click="handleAddTest(item)"
              >加入试卷</el-button
            >
            <el-button
              v-else
              plain
              style="padding: 5px 10px"
              @click="handleDel(item)"
              >移除试卷</el-button
            >
          </div>
        </div>
      </div>
    </div>
    <div class="paging">
      <div></div>
      <el-pagination
        @current-change="pageSizeChange"
        background
        layout="prev, pager, next"
        :page-size="listPage.size"
        :current-page="listPage.page"
        :total="listPage.total"
      >
      </el-pagination>

      <el-button
        class="button button-size"
        type="primary"
        v-if="
          !arraysEqual(
            topicList.map((item) => item.id),
            questions.map((item) => item.id)
          )
        "
        @click="handleAllTest()"
        >全选本页</el-button
      >
      <el-button
        @click="handleDelTest()"
        class="button-size"
        v-else
        plain
        style="padding: 5px 10px"
        >移除本页</el-button
      >
    </div>
    <div class="shopping" @click="handleShop">
      <div class="shopping-select">{{ questions.length }}</div>
      <i class="el-icon-shopping-cart-full" style="padding: 5px 0 0 0"></i>
      <div>
        <div class="size">试</div>
        <div class="size">题</div>
        <div class="size">篮</div>
      </div>
    </div>
    <wrongQuestionDialog
      :visible.sync="visible"
      :list="questions"
      :subjectName="formData.subjectName"
      :sectionId="formData.sectionId"
      :gradeId="formData.grade"
      @setQuestions="setQuestions"
    />
    <analysisDialog
      :visible.sync="analysisVisible"
      :analysisUrl="analysisUrl"
    />
  </div>
</template>

<script>
import { setDateRules, getKnowledge } from "@/utils";
import wrongQuestionDialog from "./components/wrongQuestionDialog.vue";
import analysisDialog from "./components/analysisDialog.vue";

export default {
  components: {
    wrongQuestionDialog,
    analysisDialog,
  },
  data() {
    return {
      loading: false,
      minValue: 0, // 最小值
      maxValue: 100, // 最大值
      visible: false, // 购物车弹框控制
      queryLoading: false, //loading
      analysisUrl: null, // 解析url
      analysisVisible: false, // 解析弹框
      // 分页
      listPage: {
        page: 1,
        size: 10,
        total: 0,
      },
      // 科目搜索
      subjectList: [],
      // 年级
      gradeList: [],

      // 班级选择
      classList: [],
      // 时间选择
      dateList: [
        { type: "onDay", name: "今天" },
        { type: "onWeek", name: "本周" },
        { type: "term", name: "本学期" },
      ],
      // 题型选择
      questionList: [
        { label: "全部", value: null },
        { label: "单选", value: 2 },
        { label: "多选", value: 3 },
        { label: "判断", value: 4 },
        { label: "主观", value: 5 },
      ],
      // 题目列表
      topicList: [],
      // 搜索内容
      formData: {
        classId: 1, // 班级选中
        // type: "onDay", // 时间类型
        type: "onDay", // 时间类型
        dateRange: ["2022-03-01", "2023-05-01"], // 开始结束时间
        startScoreRate: 0, // 开始区间
        endScoreRate: 60, // 结束区间
        questionType: null, // 题型
        subjectName: null, // 科目
        grade: null, // 年级
        gradeName: null, // 年级名称
      },
      questions: [],
    };
  },
  created() {
    this.handleDate(this.formData.type);
    this.queryLoading = true;
    this.getGradeList();
    if (!localStorage.getItem("testlist")) {
      localStorage.setItem("testlist", JSON.stringify(this.questions));
    } else {
      this.questions = JSON.parse(localStorage.getItem("testlist"));
      console.log(this.questions, "===");
    }
  },
  methods: {
    async loadAndModifyHTML(array) {
      let list = array;
      for (let item of list) {
        try {
          // 使用 fetch 获取 HTML 内容
          const response = await fetch(item.screenshot);
          const htmlContent = await response.text();
          // 创建一个临时的 DOM 节点，方便操作 HTML 内容
          const parser = new DOMParser();
          const doc = parser.parseFromString(htmlContent, "text/html");

          // // 修改 HTML 内容，例如删除第一个 <p> 标签
          const firstP = doc.querySelector("p");
          // if (firstP) {
          //   firstP.remove(); // 删除第一个 <p> 标签
          // }

          // 或者修改第一个 < p > 标签的内容;
          // if (firstP) {
          //   // console.log(firstP.innerHTML);

          //   let a = this.processString(firstP.innerHTML);

          //   firstP.innerHTML = a;
          //   // console.log(firstP.textContent);
          // }

          // 更新列表中的对象，保存修改后的 HTML
          item.modifiedHtml = doc.documentElement.outerHTML; // 或者将 doc.body.innerHTML 保存到 item 中
        } catch (error) {
          console.error(
            `Error fetching or modifying HTML for item ${item.id}:`,
            error
          );
        }
      }
      return list;
    },
    // 获取列表
    async getList(type) {
      if (type) {
        this.listPage.page = 1;
      }
      let param = {
        ...this.listPage,
        ...this.formData,
        startScoreRate: this.formData.startScoreRate.toString(),
        endScoreRate: this.formData.endScoreRate.toString(),
        startDate: this.formData.dateRange[0],
        endDate: this.formData.dateRange[1],
      };
      let data = await this.$request.getWrongQuestionList(param);
      this.queryLoading = false;
      this.topicList = data.data.records.map((item) => {
        return { ...item, knowledge: getKnowledge(item.knowledge) };
      });
      this.listPage.total = data.data.total;
      // this.topicList = await this.loadAndModifyHTML(data.data.records);
    },
    pageSizeChange(value) {
      this.listPage.page = value;
      this.getList();
    },

    // 全选按钮
    handleAll() {
      console.log(123123);
    },

    // 班级选中
    handleClass(id) {
      this.formData.classId = id;
    },

    // 题型选中

    handleQuestion(id) {
      this.formData.questionType = id;
    },
    // 时间选中
    handleDate(type) {
      this.formData.type = type;
      let params = setDateRules(type);
      this.formData.dateRange = [params.startDay, params.endDay];
    },

    // 输入不超过100
    startValidateInput(value) {
      if (value < this.minValue) {
        this.formData.startScoreRate = this.minValue; // 修正值
      }
      if (value > this.maxValue) {
        this.formData.startScoreRate = this.maxValue; // 修正值
      }
      if (value > this.formData.endScoreRate) {
        this.formData.startScoreRate = this.formData.endScoreRate;
      }
      if (!value) {
        this.formData.startScoreRate = 0;
      }
    },
    // 输入不超过100
    endValidateInput(value) {
      if (value < this.minValue) {
        this.formData.endScoreRate = this.minValue; // 修正值
      }
      if (value > this.maxValue) {
        this.formData.endScoreRate = this.maxValue; // 修正值
      }
      if (value < this.formData.startScoreRate) {
        this.formData.endScoreRate = this.formData.startScoreRate;
      }
      if (!value) {
        this.formData.endScoreRate = 0;
      }
    },

    // 搜索按钮
    handleSearch() {
      this.queryLoading = true;
      this.getList("type");
    },

    // 加入试卷
    handleAddTest(item) {
      // if (this.questions.includes(item.id)) return;
      if (this.questions.some((obj) => obj.id === item.id)) return;
      this.questions = JSON.parse(localStorage.getItem("testlist")) || [];
      this.questions.push(item);
      localStorage.setItem("testlist", JSON.stringify(this.questions));
    },
    // 移除试卷
    handleDel(item) {
      let _index = this.questions.findIndex((obj) => obj.id === item.id);
      if (_index !== -1) {
        this.questions.splice(_index, 1); // 从索引位置删除一个元素
        localStorage.setItem("testlist", JSON.stringify(this.questions));
      }
    },
    // 全部选中
    handleAllTest() {
      // 获取原来的localStorage
      let list = JSON.parse(localStorage.getItem("testlist")) || [];

      let ids = this.topicList.map((item) => {
        return item;
      });
      console.log(list, "-=-11-=");

      this.questions = this.removeDuplicates([...ids, ...list]);
      localStorage.setItem("testlist", JSON.stringify(this.questions));
    },
    // 全部删除
    handleDelTest() {
      let list = this.removeMatchingValues(this.topicList, this.questions);
      this.questions = list;
      console.log("移除本业", this.questions);

      localStorage.setItem("testlist", JSON.stringify(this.questions));
    },
    // 重置 去除locastorage 以及 questions
    handleRest() {
      this.questions = [];
      localStorage.setItem("testlist", JSON.stringify(this.questions));
    },
    // 去重
    removeDuplicates(arr) {
      const seen = new Set();
      return arr.filter((item) => {
        if (!seen.has(item.id)) {
          seen.add(item.id);
          return true;
        }
        return false;
      });
    },
    // 去除第二数组中存在第一数组中的值
    removeMatchingValues(arr1, arr2) {
      const arr1Ids = arr1.map((item) => item.id);
      const res = arr2.filter((item) => !arr1Ids.includes(item.id));
      console.log(res, "res");

      return res;
    },

    // 判断第一个数组在第二个种是否全部存在
    arraysEqual(arr1, arr2) {
      // 将第二个数组转为 Set
      const valuesSet = new Set(arr2);

      // 判断第一个数组中的值是否都在 Set 中
      return arr1.every((value) => valuesSet.has(value));
    },

    // 购物车触发弹框
    handleShop() {
      this.visible = true;
    },

    // 获取科目列表
    async getSubject(params) {
      console.log(params, "params");

      let data = await this.$request.getSubjectList(params);
      console.log(data, "--------");

      this.subjectList = data.data.subjectNames;
      console.log(this.subjectList, "我被打印了");

      this.formData.subjectName = this.subjectList[0];
      this.getClassList();
    },
    // 获取年级列表
    async getGradeList() {
      let data = await this.$request.getClassList();
      console.log(data, "----------data");

      this.gradeList = Array.from(
        new Map(data.data.list.map((item) => [item.grade, item])).values()
      );
      console.log(this.gradeList, "gradeList");

      this.formData.grade = this.gradeList[0].grade;
      this.formData.sectionId = this.gradeList[0].section;
      this.formData.gradeName = this.gradeList.find(
        (itme) => itme.grade == this.formData.grade
      ).gradeName;
      this.getSubject({ gradeName: this.formData.gradeName });
    },
    // 获取班级信息
    async getClassList() {
      console.log(this.formData, "this.formDate");

      let data = await this.$request.getGradeList({
        grade: this.formData.grade,
        subjectName: this.formData.subjectName,
      });
      this.classList = [
        { className: "全部", classId: null },
        ...data.data.map((item) => {
          return { className: item.className, classId: item.id };
        }),
      ];
      this.formData.classId = null;
      this.getList("type");
    },

    // 年级改变
    changeGrade(value) {
      let item = this.gradeList.find((subItem) => subItem.grade == value);
      this.formData.sectionId = item.section;
      this.formData.gradeName = item.gradeName;
      this.queryLoading = true;
      this.getSubject({ gradeName: this.formData.gradeName });
    },
    // 科目改变
    changeSubject() {
      this.queryLoading = true;
      this.getClassList();
    },
    processString(input) {
      // 正则表达式：
      const regexs = [/[0-9]+[.)]/, /（\d+分）/, /^(\d{1,3})/];

      // 使用正则表达式匹配并处理输入字符串
      for (const regex of regexs) {
        const match = input.match(regex);
        if (match) {
          if (regex === regexs[2]) {
            // 如果匹配第三条规则，使用substring截取返回结果的长度加1
            const matchLength = match[0].length;
            return input.substring(matchLength + 1).trim();
          } else {
            // 如果匹配第一条或第二条规则，替换匹配的部分
            input = input.replace(regex, "");
          }
        }
      }

      return input;
    },

    // 获取ref
    onIFrameLoad(index) {
      const iframeRef = this.$refs["iframe" + index][0]; // 获取对应的 iframe
      const doc = iframeRef.contentDocument || iframeRef.contentWindow.document;
      const body = iframeRef.contentWindow.document.body;
      body.style.overflowX = "hidden"; // 不允许出现横向滚动条
      const height = body.scrollHeight; // 获取内容的高度
      iframeRef.style.height = `${height}px`; // 设置 iframe 的高度
      // 获取第一个P标签
      const firstP = doc.getElementsByTagName("p")[0];
      // 或者修改第一个 < p > 标签的内容;
      if (firstP) {
        let a = this.processString(firstP.innerHTML);
        firstP.innerHTML = a;
      }
    },

    // 子集删除后 父级需要更新
    setQuestions() {
      this.questions = JSON.parse(localStorage.getItem("testlist")) || [];
    },

    //  查看解析
    handleAnalysis(url) {
      this.analysisUrl = url;
      this.analysisVisible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.page-content {
  box-sizing: border-box;
  padding: 0 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f6fa;
  font-size: 14px;
  color: #000000;
  position: relative;
  .page-title {
    padding: 20px 0;
    display: flex;
    justify-content: space-between;
  }
  .info {
    flex: 1;
    overflow: auto;
    display: flex;
    flex-direction: column;
    .box-search {
      background: #ffffff;
      border-radius: 5px;
    }
    .box-info {
      margin-top: 15px;
      background: #ffffff;
      flex: 1;
      padding: 10px 20px;
      .box-info-title {
        font-size: 16px !important;
        font-weight: 600;
        color: #000000;
        span {
          font-size: 14px !important;
          color: #999999;
        }
      }
      .topic {
        height: fit-content;
        max-height: 500px;
        margin-top: 15px;
        display: flex;
        flex-direction: column;
        box-shadow: 0px 0px 9px 0px #999999;
        border-radius: 5px;
        .topic-title {
          height: 45px;
          background: rgb(243, 243, 243);
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-weight: 600;
          padding: 0 20px;
          border-radius: 5px 5px 0 0;
        }
        .topic-info {
          overflow-y: auto;
          max-height: 300px;
        }
        .topic-bottom {
          height: 45px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin: 0 20px;
          font-weight: 600;
          box-sizing: border-box;
          border-top: 1px solid #d2cdcd;
          .knowledge {
            color: rgb(105, 134, 205);
            margin-right: 30px;
            cursor: pointer;
          }
        }
      }
    }
  }
  .paging {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #666666;
    background: #ffffff;
    box-shadow: 0 0 3px 0 #666666;
    padding: 5px 20px 0 20px;
  }

  .shopping {
    width: 40px;
    height: 120px;
    position: fixed;
    top: 30%;
    right: 0;
    background: #6b73f5;
    border-radius: 10px 0 0 10px;
    color: #ffffff;
    font-size: 12px !important;
    font-weight: 600;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
    box-sizing: border-box;
    padding: 10px 0;
    text-align: center;
    cursor: pointer;
    .shopping-select {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background: yellow;
      color: red;
      line-height: 20px;
      font-size: 12px !important;
    }
    .size {
      font-size: 14px !important;
    }
  }
}

.page-padding {
  box-sizing: border-box;
  padding: 14px 20px;
}
.col-margin {
  margin: 10px 0;
  display: flex;
  align-items: center;
}
.button {
  background: #6b73f5;
  padding: 5px 10px;
}
.select-box {
  padding: 5px 10px;
  border-radius: 5px;
  margin: 0 8px;
  cursor: pointer;
  white-space: nowrap;
  width: fit-content;
}
.Selected {
  background: rgba(223, 229, 253, 1);
  color: rgb(105, 134, 205);
  cursor: pointer;
}

.color {
  color: #999999;
}
.score-color {
  color: rgb(234, 160, 73);
  margin-right: 10px;
}
.size {
  font-size: 14px !important;
}
</style>
