<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" @dblclick="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 class="test-group">
          <div
            class="outer-item"
            v-for="(group, index) in groups"
            :key="group.id"
            :class="{
              border: selectedIndex === group.id,
            }"
          >
            <div
              v-if="selectedIndex === group.id"
              class="border-del"
              @click="handleDel(group.id, 'all')"
            >
              删除
            </div>
            <!-- 每个组的标题 -->
            <div class="test-group-title" @click="selectItem(group.id, 'all')">
              <div class="size-16" style="font-weight: 600">
                {{ index + 1 }}、
                <span
                  class="size-16"
                  @dblclick="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"
                />
                <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; padding: 10px 0"
              v-for="(question, subIndex) in group.subQuestionIds"
              :key="question.id"
              :class="{
                border: selectedItemIndex === question.id,
              }"
              @click="selectItem(question.id, 'number')"
              class="inner-item"
            >
              <div
                v-if="selectedItemIndex === question.id"
                class="border-del"
                @click="handleDel(question.id, 'number')"
              >
                删除
              </div>
              <div class="size color">{{ question.globalIndex }}、</div>

              <iframe
                :src="question.screenshot"
                :ref="'iframe' + subIndex"
                @load="onIFrameLoad(subIndex)"
                style="width: 100%"
              ></iframe>
            </div>
          </div>
        </div>
      </div>
      <div class="edit">
        <div class="edit-title"></div>
        <div class="edit-info">
          <div class="title size color" style="padding: 15px 0 0 10px">
            题目排序
            <span class="title size" 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: 100px"
                  ></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";
export default {
  components: { draggable },
  name: "wrongQuestionDialog",
  props: {
    visible: {
      type: Boolean,
      default() {
        return false;
      },
    },
    ids: {
      // 用于请求详情接口
      type: Array,
      default() {
        return [];
      },
    },
    subjectName: {
      // 科目
      type: String,
      default() {
        return null;
      },
    },
  },
  data() {
    return {
      score: 0, // 分数
      inputValue: " 2024年11月11日数学-错题复习", // 标题
      isEditing: false, // 用于判断是否处于编辑模式
      selectedIndex: null, // 当前选中的外层对象的索引
      selectedItemIndex: null, // 当前选中的内层对象的索引
      isHovered: false, // 用于控制边框和提示文字的显示
      tooltipPosition: { x: 0, y: 0 }, // 提示文字的位置
      time: "",
      questionList: [
        { label: "全部", value: null },
        { label: "单选题", value: 2 },
        { label: "多选题", value: 3 },
        { label: "判断题", value: 4 },
        { label: "主观题", value: 5 },
      ],
      groups: [
        {
          id: 1,
          name: "单选题",
          input: false,
          items: [
            { id: 1, content: "组一题目1", globalIndex: 1 },
            { id: 2, content: "组一题目2", globalIndex: 2 },
            { id: 3, content: "组一题目3", globalIndex: 3 },
          ],
        },
        {
          id: 2,
          name: "多选题",
          input: false,
          items: [
            { id: 4, content: "组二题目1", globalIndex: 4 },
            { id: 5, content: "组二题目2", globalIndex: 5 },
            { id: 6, content: "组二题目3", globalIndex: 6 },
          ],
        },
        {
          id: 3,
          name: "填空题",
          input: false,
          items: [
            { id: 7, content: "组三题目1", globalIndex: 7 },
            { id: 8, content: "组三题目2", globalIndex: 8 },
            { id: 9, content: "组三题目3", globalIndex: 9 },
            { id: 10, content: "组三题目3", globalIndex: 10 },
            { id: 11, content: "组三题目3", globalIndex: 11 },
            { id: 12, content: "组三题目3", globalIndex: 12 },
            { id: 13, content: "组三题目3", globalIndex: 13 },
            { id: 14, content: "组三题目3", globalIndex: 14 },
            { id: 15, content: "组三题目3", globalIndex: 15 },
            { id: 16, content: "组三题目3", globalIndex: 16 },
            { id: 17, content: "组三题目3", globalIndex: 17 },
          ],
        },
        {
          id: 4,
          name: "问答题",
          input: false,
          items: [
            { id: 18, content: "组二题目1", globalIndex: 18 },
            { id: 19, content: "组二题目2", globalIndex: 19 },
            { id: 20, content: "组二题目3", globalIndex: 20 },
          ],
        },
      ],
    };
  },

  watch: {
    visible(val) {
      if (val) {
        // 初始化
        this.init();
      } else {
        // 关闭后处理
        localStorage.setItem("question", JSON.stringify(this.groups));
      }
    },
  },
  methods: {
    // 初始化
    async init() {
      let dataList = JSON.parse(localStorage.getItem("question"));
      if (dataList && dataList.length > 0) {
        this.groups = dataList;
        return;
      }
      console.log("初始化成功");
      this.time = this.getFormattedDate();
      this.inputValue = this.time + this.subjectName + "--错题复习";
      this.$request
        .getWrongQuestionList({ ids: this.ids, page: 1, size: 99999 })
        .then((res) => {
          this.groups = this.classifyByType(
            res.data.records.map((item, index) => {
              return { ...item, globalIndex: index };
            })
          );
          console.log(this.groups, "=-=-=");
        });
    },
    /** 按钮 - 取消 */
    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;
      });
    },
    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) => ({
        type: type,
        questionTitle: this.questionList.find((item) => item.value == type)
          .label,
        questionScore: 1,
        subQuestionIds: result[type],
      }));
    },
    onIFrameLoad(index) {
      const iframeRef = this.$refs["iframe" + index][0]; // 获取对应的 iframe
      console.log(iframeRef, "ref");
      console.log(iframeRef.contentWindow.document, "document");
    },

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

    // 保存修改后的内容，回车或失去焦点时触发
    save() {
      console.log("回车事件");

      this.isEditing = false;
      console.log("保存的内容:", this.inputValue); // 可根据需要将内容保存到其他地方
    },

    // 单题title修改
    groupEditing(index) {
      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);
    },
    // 高亮
    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") {
        console.log("删除整个大题");
      } else {
        console.log("删除整个小题");
      }
    },
    handleMouseEnter(event) {
      console.log(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}日`;
    },
  },
};
</script>
<style lang="scss" scoped>
.title {
  font-weight: 600;
}
.test-box {
  display: flex;
  .test {
    flex: 1;
    height: fit-content;
    max-height: 642px;
    overflow-y: auto;
    box-shadow: 0 0 10px 0 #999999;
    margin-right: 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 {
        padding: 10px 0;
      }
    }
  }
  .edit {
    width: 400px;
    display: flex;
    flex-direction: column;
    .edit-title {
      width: 100%;
      height: 200px;
      border: 1px solid #999999;
    }
    .edit-info {
      flex: 1;
      border: 1px solid #999999;
      margin-top: 20px;
      max-height: 400px;
      padding: 10px;
      overflow: auto;
      .group-item {
        padding: 10px;
        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;
        }
      }
      .questions {
        display: flex;
        flex-wrap: wrap;
        .question-item {
          width: 35px;
          height: 35px;
          border: 1px solid rgb(172, 188, 249);
          border-radius: 4px;
          cursor: grab;
          margin: 5px 8px;
          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-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;
    font-weight: 600;
    cursor: pointer;
  }
}
.outer-item,
.inner-item {
  height: fit-content;
  padding: 0 20px;
  margin: 5px;
}
.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);
}
</style>