<template>
  <div id="Chapter1_1" class="content-wrap">
    <div style="margin: 30px 0px 50px; width: 20%">
      <router-link to="/MyPlan.page">
        <div class="logo mb25">
          <img src="../../../../resources/img/logo2.png" alt="" />
        </div>
      </router-link>
    </div>
    <div
      class="title-box mb25 flex align-center mt40"
      style="justify-content: space-between"
    >
      <div>
        <span class="title mr40">1. Hello WORLD</span>
        <span class="subtitle">my name is dd</span>
      </div>
      <button class="completeBtn" @click="complete">학습 종료</button>
    </div>
    <div class="flex justify-between align-center">
      <div
        class="pre-btn"
        :style="{ visibility: hiddenState ? 'hidden' : 'visible' }"
        @click="goToPrevPage"
      >
        <img src="../../../../resources/img/left.png" alt="" />
      </div>
      <div class="content title-box">
        <div style="display: flex; justify-content: space-between">
          <p class="title mt25 title-bg">STEP 2 - 단어로 공부하는 영어</p>
          <button id="returnButton" @click="returnPage" style="margin: 4rem">
            <img src="../../../../resources/img/btn_return_50x50.png" alt="" />
            <p>되돌리기</p>
          </button>
        </div>
        <div class="flex align-center mb30">
          <p class="subtitle2 mr20">
            앗! 잉크가 쏟아졌어! 지우개로 잉크를 지워줘!
          </p>
        </div>

        <div class="text-ct">
          <div class="dropGroup flex align-center justify-center">
            <div style="position: relative">
              <img
                src="../../../../resources/img/img72_41s.png"
                alt=""
                style="width: 93%"
              />
              <div class="vocaGroup">
                <div
                  v-for="word in wordList"
                  :key="word.wdId"
                  class="flex justify-between mb80 word-item"
                >
                  <article class="flex align-center">
                    <div class="imgGroup mr30">
                      <img
                        :src="word.fileRpath"
                        data-num="1"
                        class="ink"
                        style="width: 150px"
                      />
                    </div>
                    <div class="flex align-start">
                      <div>
                        <h3>{{ word.wdNm }}</h3>
                        <div class="flex align-center mt10">
                          <span class="title1">{{ word.wdMnng }}</span>
                        </div>
                      </div>
                    </div>
                  </article>
                </div>
              </div>
              <div class="textbox">
                <button
                  id="eraser1"
                  class="dropzone"
                  style="left: 141px; top: 44px"
                >
                  <img src="../../../../resources/img/img78_41s.png" alt="" />
                </button>
                <button
                  id="eraser2"
                  class="dropzone"
                  style="left: 200px; bottom: 46px"
                >
                  <img src="../../../../resources/img/img79_41s.png" alt="" />
                </button>
                <button
                  id="eraser3"
                  class="dropzone"
                  style="right: 237px; top: 114px"
                >
                  <img src="../../../../resources/img/img80_41s.png" alt="" />
                </button>
                <button
                  id="eraser4"
                  class="dropzone"
                  style="right: 159px; bottom: 5px"
                >
                  <img src="../../../../resources/img/img81_41s.png" alt="" />
                </button>
              </div>
            </div>
          </div>
          <div class="dragGroup">
            <div>
              <article style="left: 83px; top: 69%">
                <button
                  id="eraser"
                  draggable="true"
                  @dragstart="handleDragStart"
                >
                  <img src="../../../../resources/img/img73_41s.png" alt="" />
                </button>
              </article>
            </div>
          </div>
        </div>
      </div>
      <div class="next-btn" @click="goToNextPage">
        <img src="../../../../resources/img/right.png" alt="" />
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      draggedElementId: null, // 드래그한 요소의 ID를 저장
      wordList: [],

      wdBookIdList: [], // 단어 컨텐츠의 단어장 id 리스트
      wdBookId: "", // 현재 단어장 id
      currentWdBkIndex: 0, // 현재 단어장 인덱스
      wdBookTypeIdState: "", // 이동할 페이지 타입 id
      wordBookType: "", // 이동할 페이지

      seq: this.$store.getters.seqNum,

      hiddenState: false,
    };
  },
  methods: {
    pageSetting() {
      this.currentWdBkIndex = this.$store.getters.getCurrentWdBkIndex; // 현재 단어장 인덱스
      this.wdBookIdList = this.$store.getters.getWdBookIdList; // 단어컨텐츠의 단어장 id 리스트
      this.wdBookId =
        this.$store.getters.getWdBookIdList[this.currentWdBkIndex]; // 현재 단어장 콘텐츠 인덱스에 대한 단어장 id

      if (this.currentWdBkIndex - 1 < 0) {
        this.hiddenState = true;
      }

      this.fetchWordList();
    },

    async fetchWordList() {
      try {
        const response = await axios.post("/word/getWordsByBookId.json", {
          wdBookId: this.wdBookId,
        });

        const wordList = response.data;

        // 각 word 객체에 대해 fileRpath를 받아오는 요청 처리
        const requests = wordList.map(async (word) => {
          const fileResponse = await axios.post("/file/find.json", {
            file_mng_id: word.fileMngId,
          });

          const fileRpath =
            fileResponse.data.list.length > 0
              ? fileResponse.data.list[0].fileRpath
              : null;
          console.log("각 단어의 fileRpath: ", fileRpath);

          word.fileRpath = "http://165.229.169.113:9080/" + fileRpath; // fileRpath 값을 해당 객체에 추가
        });

        // 모든 요청이 완료될 때까지 대기
        await Promise.all(requests);

        // 최종적으로 wordList를 설정
        this.wordList = wordList;
        console.log("단어 리스트 -> ", this.wordList);
      } catch (error) {
        console.error("단어 목록을 불러오는 중 오류 발생:", error);
      }
    },

    async goToPrevPage() {
      if (this.currentWdBkIndex - 1 < 0) {
        alert("단어장 첫번째 페이지 입니다");
      } else {
        this.currentWdBkIndex--;
        this.$store.dispatch("updateCurrentWdBkIndex", this.currentWdBkIndex);

        try {
          const response = await axios.post("/wordbook/find.json", {
            wdBookId:
              this.$store.getters.getWdBookIdList[this.currentWdBkIndex],
          });
          this.wdBookTypeIdState = response.data.wdBookTypeId;
          console.log("이전 단어장 타입 id: ", this.wdBookTypeIdState);

          switch (this.wdBookTypeIdState) {
            case "1":
              this.wordBookType = "Chapter2";
              break;
            case "2":
              this.wordBookType = "Chapter2_3";
              break;
            case "3":
              this.wordBookType = "Chapter2_2";
              break;
            case "4":
              this.wordBookType = "Chapter2_9";
              break;
            case "5":
              this.wordBookType = "Chapter2_4";
              break;
            default:
              this.wordBookType = null;
          }

          this.goToPage(this.wordBookType);
        } catch (error) {
          console.error("단어장 정보 불러오는 중 오류 발생:", error);
        }
      }
    },

    async goToNextPage() {
      if (this.currentWdBkIndex + 1 >= this.wdBookIdList.length) {
        alert("단어장 마지막 페이지 입니다");
        this.complete();
      } else {
        this.currentWdBkIndex++;
        this.$store.dispatch("updateCurrentWdBkIndex", this.currentWdBkIndex);

        try {
          const response = await axios.post("/wordbook/find.json", {
            wdBookId:
              this.$store.getters.getWdBookIdList[this.currentWdBkIndex],
          });
          this.wdBookTypeIdState = response.data.wdBookTypeId;
          console.log("다음 단어장 타입 id: ", this.wdBookTypeIdState);

          switch (this.wdBookTypeIdState) {
            case "1":
              this.wordBookType = "Chapter2";
              break;
            case "2":
              this.wordBookType = "Chapter2_3";
              break;
            case "3":
              this.wordBookType = "Chapter2_2";
              break;
            case "4":
              this.wordBookType = "Chapter2_9";
              break;
            case "5":
              this.wordBookType = "Chapter2_4";
              break;
            default:
              this.wordBookType = null;
          }

          this.goToPage(this.wordBookType);
        } catch (error) {
          console.error("단어장 정보 불러오는 중 오류 발생:", error);
        }
      }
    },

    complete() {
      const { unit_id, book_id } = this.$route.query;
      this.$router.push({
        name: "Dashboard",
        query: { value: this.seq, unit_id, book_id },
      });
    },
    goToPage(page) {
      this.$router.push({ name: page });
    },
    handleDragStart(event) {
      this.draggedElementId = event.target.id; // 드래그한 요소의 ID를 저장
      event.dataTransfer.setData("text/plain", this.draggedElementId);
    },
    handleDragOver(event) {
      event.preventDefault(); // 드롭을 허용
    },
    handleDrop(event) {
      event.preventDefault();

      // 드롭된 영역이 버튼인지 확인
      const dropZone = event.target.closest("button.dropzone");

      if (dropZone) {
        // 드롭이 이루어진 영역이 버튼일 때만 처리
        dropZone.querySelector("img").style.display = "none"; // 잉크를 숨깁니다
      }

      // 드래그한 요소를 원래 위치로 복원
      const draggedElement = document.getElementById(this.draggedElementId);
      if (draggedElement) {
        draggedElement.style.visibility = "visible";
        draggedElement.style.position = "";
        draggedElement.style.top = "";
        draggedElement.style.left = "";
      }

      this.draggedElementId = null; // 드래그 상태 초기화
    },
    returnPage() {
      window.location.reload();
    },
  },
  mounted() {
    this.pageSetting();
    // 드래그 가능한 영역에 드래그 오버 및 드롭 이벤트를 추가합니다
    document.querySelectorAll(".dropzone").forEach((button) => {
      button.addEventListener("dragover", this.handleDragOver);
      button.addEventListener("drop", this.handleDrop);
    });
  },
};
</script>

<style scoped>
.vocaGroup {
  width: 79%;
  position: absolute;
  top: 90px;
  left: 120px;
  display: flex;
  flex-wrap: wrap;
}

.word-item {
  width: 49%;
}

.ink {
  cursor: pointer;
}

.completeBtn {
  margin-right: 100px;
  background-color: #ffba08;
  padding: 10px 30px;
  border-radius: 10px;
  font-size: 28px;
  font-family: "ONEMobilePOPOTF";
}
</style>
