<template>
  <el-dialog
    :visible.sync="visible"
    width="70%"
    :before-close="handleClose"
    :modal-append-to-body="false"
  >
    <div class="test-box" v-if="groups">
      <div class="test">
        <div class="test-title" @click="enableEditing">
          <div
            class="test-title"
            v-if="!isEditing"
            @mouseenter="handleMouseEnter"
            @mouseleave="handleMouseLeave"
            :class="isHovered ? 'hover' : ''"
          >
            {{ inputValue }}
          </div>
          <div
            v-if="isHovered"
            class="tooltip"
            :style="{
              top: tooltipPosition.y + 'px',
              left: tooltipPosition.x + 'px',
            }"
          >
            单击设置试卷标题
          </div>
          <el-input
            class="test-title"
            ref="editInput"
            v-if="isEditing"
            v-model="inputValue"
            @blur="save"
            @keyup.enter.native="save"
            style="padding: 0 200px"
          />
        </div>
        <div></div>
        <div class="test-group">
          <div
            class="outer-item"
            v-for="(group, index) in groups"
            :key="group.questionType"
            :class="{
              border: selectedIndex === group.questionType,
            }"
            @mouseenter="handleGroupMouseEnter(group.questionType, 'all')"
            @mouseleave="handleGroupMouseLeave"
          >
            <div
              v-if="selectedIndex == group.questionType"
              class="border-del"
              @click="handleDel(group.questionType, 'all')"
            >
              删除
            </div>
            <!-- 每个组的标题 -->
            <div
              class="test-group-title"
              :class="{
                borderTitle: selectedIndex == group.questionType,
              }"
              @mouseenter="handleGroupMouseEnter(group.questionType, 'all')"
            >
              <div class="size-16" style="font-weight: 600">
                {{ index + 1 }}、
                <span
                  @mouseenter="
                    (event) => handleItemMouseEnter(event, group.questionType)
                  "
                  @mouseleave="handleItemMouseLeave"
                  :class="isItemHovered == group.questionType ? 'hover' : ''"
                  class="size-16"
                  @click="groupEditing(index)"
                  v-show="!group.input"
                  >{{ group.questionTitle }}</span
                >

                <el-input
                  :ref="'refInput' + index"
                  class="size-16"
                  size="mini"
                  v-show="group.input"
                  v-model="group.questionTitle"
                  @blur="groupSave(index)"
                  @keyup.enter.native="groupSave(index)"
                  style="width: fit-content"
                />
                <div
                  v-if="isItemHovered == group.questionType"
                  class="tooltip"
                  :style="{
                    top: tooltipPosition.y + 'px',
                    left: tooltipPosition.x + 'px',
                  }"
                >
                  单击修改大题名称
                </div>

                <span
                  v-if="group.subQuestionIds"
                  class="size-16"
                  style="margin-left: 10px"
                  >(共{{ group.subQuestionIds.length }}题 / 共{{
                    group.questionScore * group.subQuestionIds.length
                  }}分)</span
                >
              </div>
            </div>

            <!-- 内部的题目列表，允许组内排序 -->
            <div
              style="display: flex"
              v-for="question in group.subQuestionIds"
              :key="question.id"
              :class="{
                border: selectedItemIndex === question.id,
              }"
              @mouseenter="handleGroupMouseEnter(question.id, 'number')"
              @mouseleave="handleGroupMouseLeave"
              class="inner-item"
            >
              <div
                v-if="selectedItemIndex === question.id"
                class="border-del"
                @click="handleDel(question.id, group.questionType)"
              >
                删除
              </div>
              <div class="size color" style="margin-top: 20px">
                <div
                  style="max-width: 100px; white-space: nowrap; /* 不换行 */"
                >
                  {{ question.globalIndex }}、
                </div>
              </div>

              <iframe
                :src="question.screenshot"
                :ref="'iframe' + question.id"
                @load="onIFrameLoad(question.id)"
                style="
                  width: 100%;
                  pointer-events: none;
                  border: none; /* 启用点击穿透 */
                "
              ></iframe>
            </div>
          </div>
        </div>
      </div>
      <div class="edit">
        <div class="edit-title">
          <div class="edit-title-info">
            共<span>{{ list.length }}</span
            >小题，卷面分<span>{{ sumValues() }}</span
            >分
          </div>
          <div class="edit-button">
            <el-button
              :disabled="testData.length < 1"
              class="button-width"
              type="primary"
              @click="handleSava"
              >保存试卷</el-button
            >
            <el-button
              :disabled="testData.length < 1"
              class="button-width"
              plain
              @click="handleSava('print')"
              >保存并打印</el-button
            >
            <el-button
              class="button-width"
              type="danger"
              plain
              @click="handleClear"
              >清空题目</el-button
            >
            <el-button class="button-width" plain @click="handleSelect"
              >继续选题</el-button
            >
          </div>
        </div>
        <div class="edit-info">
          <div class="title size color" style="padding: 10px 0 5px 10px">
            题目排序
            <span class="title size font-weight" style="color: #999999"
              >(拖拽题号可排序)</span
            >
          </div>
          <!-- 外层容器，允许拖拽整个组 -->
          <draggable v-model="groups" group="groups" @end="onEnd">
            <div
              v-for="(group, index) in groups"
              :key="group.id"
              class="group-item"
            >
              <!-- 每个组的标题 -->
              <div class="group-title">
                <div class="size" style="font-weight: 600">
                  {{ index + 1 }}、{{ group.questionTitle }}
                </div>
                <div class="size">
                  单题分值：
                  <el-input-number
                    size="mini"
                    v-model="group.questionScore"
                    :min="1"
                    :max="30"
                    style="width: 120px"
                    :precision="1"
                    :step="0.5"
                    @change="handleInput"
                  ></el-input-number>
                </div>
              </div>

              <!-- 内部的题目列表，允许组内排序 -->
              <draggable
                class="questions"
                v-model="group.subQuestionIds"
                group="questions"
                @end="onItemEnd(group)"
              >
                <div
                  v-for="question in group.subQuestionIds"
                  :key="question.id"
                  class="question-item"
                >
                  {{ question.globalIndex }}
                </div>
              </draggable>
            </div>
          </draggable>
        </div>
      </div>
    </div>

    <span slot="title" class="title"> 试卷预览 </span>
  </el-dialog>
</template>
<script>
import draggable from "vuedraggable";
import { paperPrint } from "@/utils";
export default {
  components: { draggable },
  name: "wrongQuestionDialog",
  props: {
    visible: {
      type: Boolean,
      default() {
        return false;
      },
    },
    list: {
      // 用于请求详情接口
      type: Array,
      default() {
        return [];
      },
    },
    subjectName: {
      // 科目
      type: String,
      default() {
        return null;
      },
    },
    gradeId: {
      // 科目
      type: [String, Number],
      default() {
        return null;
      },
    },
    sectionId: {
      // 科目
      type: [String, Number],
      default() {
        return null;
      },
    },
    userId: {
      // uid
      type: [String, Number],
      default() {
        return null;
      },
    },
  },
  data() {
    return {
      score: 0, // 分数
      inputValue: " 2024年11月11日数学-错题复习", // 标题
      isEditing: false, // 用于判断是否处于编辑模式
      selectedIndex: null, // 当前选中的外层对象的索引
      selectedItemIndex: null, // 当前选中的内层对象的索引
      isHovered: false, // 用于控制边框和提示文字的显示
      isItemHovered: false, // 用于控制边框和提示文字的显示
      tooltipPosition: { x: 0, y: 0 }, // 提示文字的位置
      time: "",
      testData: [], // 存一份list
      questionList: [
        { label: "全部", value: null },
        { label: "单选题", value: 2 },
        { label: "多选题", value: 3 },
        { label: "判断题", value: 4 },
        { label: "主观题", value: 5 },
      ],
      groups: [],
    };
  },

  watch: {
    visible(val) {
      if (val) {
        // 上面数据测试
        this.testData =
          JSON.parse(localStorage.getItem(this.userId + "testData")) || [];
        this.groups =
          JSON.parse(localStorage.getItem(this.userId + "question")) || [];
        // 如果都没有直接return 执行初始化
        if (this.groups.length == 0) {
          this.init();
          localStorage.setItem(
            this.userId + "testData",
            JSON.stringify(this.list)
          );
          return;
        }
        // 如果一致 就直接赋值
        if (
          this.arraysHaveSameIds(this.testData, this.list) &&
          JSON.parse(localStorage.getItem(this.userId + "question"))
        ) {
          return;
        } else {
          let data = this.findMissingIds(this.testData, this.list);
          this.testData = this.list;
          localStorage.setItem(
            this.userId + "testData",
            JSON.stringify(this.testData)
          );
          this.testAddDel(this.groups, data.addArr, data.delArr);
        }
      } else {
        this.testDataFun();
      }
    },
  },
  methods: {
    // 初始化
    init() {
      console.log("初始化");
      this.time = this.getFormattedDate();
      this.inputValue = this.time + this.subjectName + "--错题复习";
      this.groups = this.classifyByType(
        this.list.map((item, index) => {
          return { ...item, globalIndex: index + 1 };
        })
      );
      this.updateGlobalIndexes();
    },
    // 随时保存testData
    testDataFun() {
      this.testData =
        this.groups.reduce((accumulator, current) => {
          return accumulator.concat(current.subQuestionIds);
        }, []) || [];
      localStorage.setItem(
        this.userId + "testData",
        JSON.stringify(this.testData)
      );
    },
    /** 按钮 - 取消 */
    handleClose() {
      this.$emit("update:visible", false);
    },
    onEnd(event) {
      // 拖拽结束时，更新所有项目的 globalIndex
      this.updateGlobalIndexes();
    },
    onItemEnd() {
      // 每次组内排序结束时，更新所有项目的 globalIndex
      this.updateGlobalIndexes();
    },
    updateGlobalIndexes() {
      if (!this.groups) return;
      // 获取所有组的所有项目
      let allItems = [];
      this.groups.forEach((group) => {
        allItems = allItems.concat(group.subQuestionIds);
      });
      allItems.forEach((item, index) => {
        item.globalIndex = index + 1;
      });
      localStorage.setItem(
        this.userId + "question",
        JSON.stringify(this.groups)
      );
    },
    classifyByType(arr) {
      const result = {};
      arr.forEach((item) => {
        const type = item.questionType;
        if (!result[type]) {
          result[type] = [];
        }
        result[type].push(item);
      });

      // 将结果对象转换为数组
      return Object.keys(result).map((type) => ({
        questionType: type,
        input: false,
        questionTitle: this.questionList.find((item) => item.value == type)
          .label,
        questionScore: 1,
        subQuestionIds: result[type],
      }));
    },
    onIFrameLoad(id) {
      const iframeRef = this.$refs["iframe" + id][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 + 20}px`; // 设置 iframe 的高度
      // 获取第一个P标签
      const firstP = doc.getElementsByTagName("p")[0];
      // 或者修改第一个 < p > 标签的内容;
      if (firstP) {
        let a = this.processString(firstP.innerHTML);
        firstP.innerHTML = a;
      }
    },

    // 启动编辑模式
    enableEditing() {
      this.isEditing = true;
      this.isHovered = false;
      this.$nextTick(() => {
        // 在 DOM 更新完成后让输入框获取焦点
        this.$refs.editInput.focus();
      });
    },

    // 保存修改后的内容，回车或失去焦点时触发
    save() {
      this.isEditing = false;
      localStorage.setItem(
        this.userId + "question",
        JSON.stringify(this.groups)
      );
    },

    // 单题title修改
    groupEditing(index) {
      this.isItemHovered = null;
      this.$set(this.groups[index], "input", true);

      // DOM 更新完成后让对应的输入框获取焦点
      this.$nextTick(() => {
        const refName = `refInput${index}`;
        this.$refs[refName][0].focus(); // 通过动态 ref 获取元素
      });
    },
    // 单体title保存
    groupSave(index) {
      this.$set(this.groups[index], "input", false);
      localStorage.setItem(
        this.userId + "question",
        JSON.stringify(this.groups)
      );
    },
    // 高亮
    selectItem(id, type) {
      if (type == "all") {
        this.selectedIndex = id;
        this.selectedItemIndex = null;
      } else {
        this.selectedItemIndex = id;
        this.selectedIndex = null;
      }
    },
    // 删除题目
    handleDel(id, type) {
      if (type == "all") {
        let _index = this.groups.findIndex((item) => item.questionType == id);
        if (_index != -1) {
          this.groups.splice(_index, 1);
          localStorage.setItem(
            this.userId + "question",
            JSON.stringify(this.groups)
          );
          this.updateGlobalIndexes();
          this.testDataFun();
          localStorage.setItem(
            this.userId + "testlist",
            JSON.stringify(this.testData)
          );
          this.$emit("setQuestions");
        }
      } else {
        this.groups.forEach((item) => {
          if (type == item.questionType) {
            item.subQuestionIds = item.subQuestionIds.filter(
              (item) => item.id !== id
            );
          }
        });
        localStorage.setItem(
          this.userId + "question",
          JSON.stringify(this.groups)
        );
        this.updateGlobalIndexes();
        this.testDataFun();
        localStorage.setItem(
          this.userId + "testlist",
          JSON.stringify(this.testData)
        );
        this.$emit("setQuestions");
      }
    },
    handleMouseEnter(event) {
      this.isHovered = true;
      // 计算提示文字位置 (鼠标右下角)
      this.tooltipPosition = {
        x: event.clientX / 2 + 30,
        y: event.clientY / 2 + 30,
      };
      this.selectedIndex = null;
      this.selectedItemIndex = null;
    },
    handleMouseLeave() {
      this.isHovered = false;
    },

    getFormattedDate() {
      const today = new Date();
      const year = today.getFullYear(); // 获取年份
      const month = today.getMonth() + 1; // 获取月份（0-11，需要+1）
      const day = today.getDate(); // 获取日期
      return `${year}年${month}月${day}日`;
    },

    // 接收两个参数
    arraysHaveSameIds(arr1, arr2) {
      // 检查两个数组长度是否相同
      if (arr1.length !== arr2.length) {
        return false;
      }
      // 提取两个数组中所有的 id
      const ids1 = arr1.map((item) => item.id);
      const ids2 = arr2.map((item) => item.id);
      // 将 id 数组排序
      ids1.sort();
      ids2.sort();
      // 比较两个 id 数组是否一致
      for (let i = 0; i < ids1.length; i++) {
        if (ids1[i] !== ids2[i]) {
          return false;
        }
      }
      return true;
    },
    // 接收两个参数
    arrContrast(arr1, arr2) {
      // 如果两个数组的长度不同，直接返回 true
      if (arr1.length !== arr2.length) {
        return true;
      }

      // 创建一个 id 集合来存放 arr1 中的 id
      const idsSet1 = new Set(arr1.map((obj) => obj.id));
      // 创建一个 id 集合来存放 arr2 中的 id
      const idsSet2 = new Set(arr2.map((obj) => obj.id));

      // 比较两个集合的大小，如果不同，返回 true
      if (idsSet1.size !== idsSet2.size) {
        return true;
      }

      // 比较两个集合的内容
      for (const id of idsSet1) {
        if (!idsSet2.has(id)) {
          return true;
        }
      }

      // 如果所有的 id 都一致，返回 false
      return false;
    },
    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;
    },

    // 接受两个参数，返回需要删除的数据以及需要添加的数据
    findMissingIds(array1, array2) {
      // 找出第一个数组中存在但第二个数组中不存在的 id
      const delArr = array1.filter(
        (item1) => !array2.some((item2) => item2.id === item1.id)
      );
      // 找出第二个数组中存在但第一个数组中不存在的 id
      const addArr = array2.filter(
        (item2) => !array1.some((item1) => item1.id === item2.id)
      );

      return {
        delArr,
        addArr,
      };
    },

    // 添加，删除
    // 需要的数据，添加的数据，删除的数据
    testAddDel(arr1, arr2, arr3) {
      console.log(arr1, arr3);
      if (arr2 && arr2.length > 0) {
        // 添加数据，如果没有type重新创建一个type
        arr2.forEach((item2) => {
          const typeMatch = arr1.find(
            (item1) => item1.questionType == item2.questionType
          );
          if (typeMatch) {
            typeMatch.subQuestionIds.push(item2);
          } else {
            arr1.push({
              questionType: item2.questionType,
              subQuestionIds: [item2],
              questionTitle: this.questionList.find(
                (item) => item.value == item2.questionType
              ).label,
              input: false,
              questionScore: 1,
            });
          }
        });
      }
      if (arr3 && arr3.length > 0) {
        // 删除数据
        arr3.forEach((item3) => {
          // 在 array1 中找到匹配的 type
          let matchedArray1Item = arr1.find((item1) =>
            item1.subQuestionIds.filter((item) => item.id == item3.id)
          );
          if (matchedArray1Item) {
            // 如果找到了匹配的 type，遍历 matchedArray1Item 的 items
            let _index = matchedArray1Item.subQuestionIds.findIndex(
              (item) => item.id === item3.id
            );
            if (_index != -1) {
              matchedArray1Item.subQuestionIds.splice(_index, 1);
            }
          } else {
            return;
          }
        });
      }

      this.updateGlobalIndexes();
    },

    // 鼠标移入
    handleGroupMouseEnter(id, type) {
      if (type == "all") {
        this.selectedIndex = id;
        this.selectedItemIndex = null;
      } else {
        this.selectedItemIndex = id;
        this.selectedIndex = null;
      }
    },
    // 鼠标离开
    handleGroupMouseLeave() {
      this.selectedIndex = null;
      this.selectedItemIndex = null;
    },

    // 小标题移入
    handleItemMouseEnter(event, type) {
      this.tooltipPosition = {
        x: 50,
        y: 40,
      };

      this.isItemHovered = type;
    },
    // 小标题移除
    handleItemMouseLeave() {
      this.isItemHovered = null;
    },

    // 保存
    handleSava(type) {
      let param = {
        paperTitle: this.inputValue,
        subjectName: this.subjectName,
        sectionId: this.sectionId,
        gradeId: this.gradeId,
        questions: this.groups.filter((item) => item.subQuestionIds.length > 0),
      };
      this.$request.getWrongQuestionSave(param).then((res) => {
        if (res.status == 0) {
          this.groups = [];
          this.testData = [];
          localStorage.setItem(
            this.userId + "testlist",
            JSON.stringify(this.testData)
          );
          localStorage.setItem(
            this.userId + "question",
            JSON.stringify(this.groups)
          );
          this.$emit("setQuestions");
          this.handleClose();
          this.$message({
            message: "已保存到“即时测-组卷-我自编的",
            type: "success",
          });

          if (type == "print") {
            this.$request
              .tPaperDetail({
                paperId: res.data,
              })
              .then((detail) => {
                paperPrint(detail.data);
              });
          }
        }
      });
    },

    // 清空
    handleClear() {
      this.$confirm("确定要清空试题篮内的全部题目吗?", "提示", {
        confirmButtonText: "清空",
        cancelButtonText: "取消",
        confirmButtonClass: "el-button--danger1",
        cancelButtonClass: "el-button--primary",
        showClose: false,
        roundButton: true,
        center: false,
        type: "warning",
      })
        .then(() => {
          this.groups = [];
          this.testDataFun();
          localStorage.setItem(
            this.userId + "question",
            JSON.stringify(this.groups)
          );
          localStorage.setItem(
            this.userId + "testlist",
            JSON.stringify(this.testData)
          );

          this.$emit("setQuestions");
        })
        .catch(() => {
          console.log("取消");
        });
    },
    // 继续选题
    handleSelect() {
      this.handleClose();
    },

    // 计算总分
    sumValues() {
      return this.groups.reduce((sum, item) => {
        return sum + Number(item.questionScore) * item.subQuestionIds.length;
      }, 0);
    },

    // 当分数发生变化的时候
    handleInput() {
      localStorage.setItem(
        this.userId + "question",
        JSON.stringify(this.groups)
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.title {
  font-weight: 600;
}

.test-box {
  display: flex;
  min-height: 742px;

  .test {
    flex: 1;
    height: fit-content;
    height: 742px;
    overflow-y: auto;
    box-shadow: 0 0 10px 0 #cfcfcf;
    margin-right: 20px;
    box-sizing: border-box;
    padding: 0 20px;

    .test-title {
      font-size: 20px !important;
      font-weight: 700;
      text-align: center;
      color: #000000;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 10px;
    }

    .test-name-input {
      padding: 25px 80px 0 80px;
      display: flex;
      justify-content: space-around;
      align-items: center;
    }

    .test-group {
      .test-group-title {
        position: relative;
        height: 40px;
        line-height: 40px;
        padding: 0;
      }
    }
  }

  .edit {
    width: 400px;
    display: flex;
    flex-direction: column;

    .edit-title {
      width: 100%;
      height: 200px;
      border: 1px solid #cfcfcf;
      border-radius: 5px;

      .edit-title-info {
        height: 60px;
        width: 100%;
        text-align: center;
        font-weight: 600;
        font-size: 16px !important;
        line-height: 60px;
        color: #000000;

        span {
          color: rgb(234, 163, 73);
        }
      }

      .edit-button {
        box-sizing: border-box;
        padding: 0 20px;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-around;

        .button-width {
          width: 160px !important;
          margin: 10px 0;
        }
      }
    }

    .edit-info {
      flex: 1;
      border: 1px solid #cfcfcf;
      margin-top: 20px;
      max-height: 500px;
      padding: 10px;
      overflow: auto;
      border-radius: 5px;

      .group-item {
        margin: 10px;
        background: rgba(243, 243, 243, 0.6);
        border-radius: 5px;

        .group-title {
          display: flex;
          align-items: center;
          height: 40px;
          justify-content: space-between;
          cursor: pointer;
          padding: 0 10px;
        }
      }

      .questions {
        display: flex;
        flex-wrap: wrap;
        padding: 10px 0;
        .question-item {
          width: 35px;
          height: 35px;
          border: 1px solid rgb(172, 188, 249);
          border-radius: 4px;
          cursor: grab;
          margin: 0 10px 10px 10px;
          line-height: 35px;
          text-align: center;
          font-size: 16px !important;
        }
      }

      .question-item:active {
        cursor: grabbing;
      }
    }
  }
}

.size {
  font-size: 14px !important;
}

.color {
  color: #000000;
}

.size-16 {
  font-size: 16px !important;
  font-weight: 600;
  color: #333333;
}

::v-deep {
  .el-dialog {
    margin-top: 10vh !important;
  }
}

.border {
  border: 1px solid rgb(173, 190, 250);
  position: relative;
  border-radius: 3px;

  .border-del {
    position: absolute;
    top: -30px;
    right: -1px;
    height: 28px;
    width: fit-content;
    border: 1px solid rgb(173, 190, 250);
    padding: 0 8px;
    color: rgb(67, 141, 255);
    font-size: 14px !important;
    line-height: 28px;

    cursor: pointer;
  }
}

.outer-item,
.inner-item {
  height: fit-content;
  margin-bottom: 20px;
}

.tooltip {
  position: absolute;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 12px !important;
}

.hover {
  border: 1px solid rgb(115, 142, 246);
  background: rgb(233, 237, 253);
  width: fit-content;
}
.borderTitle {
  background: rgba(102, 127, 253, 0.1);
  padding: 0;
}

.title-bg {
  background: rgb(115, 142, 246);
  border-bottom: 1px solid rgb(115, 142, 246);
}
.font-weight {
  font-weight: 400;
}
</style>
