<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" @click="goToPage('Chapter1_3')"> @click="goToPrevPage" -->
      <div
        class="pre-btn"
        :style="{ visibility: hiddenState ? 'hidden' : 'visible' }"
        @click="goToPrevPage"
      >
        <img src="../../../../resources/img/left.png" alt="" />
      </div>
      <div class="content title-box">
        <p class="title mt25 title-bg">STEP 2 - 단어로 공부하는 영어</p>
        <div class="flex align-center mb30">
          <p class="subtitle2 mr20"></p>
        </div>

        <div class="flex justify-center">
          <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"
                    style="width: 200px"
                  />
                </div>
                <div class="flex align-start">
                  <button
                    class="listen-btn mr30"
                    data-video="1"
                    tabindex="0"
                    aria-label="음성 재생"
                  >
                    <img
                      src="../../../../resources/img/btn10_s.png"
                      data-num="1"
                      @click="playAudio('audio-family')"
                    />
                  </button>
                  <audio
                    id="audio-family"
                    src="client/resources/audio/family.wav"
                    preload="auto"
                  ></audio>
                  <div>
                    <h3>{{ word.wdNm }}</h3>
                    <div class="flex align-center mt10">
                      <p class="yellow-box">명</p>
                      <span class="title1">{{ word.wdMnng }}</span>
                    </div>
                  </div>
                </div>
              </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 {
      wdBookId: "",
      wordList: [],

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

      hiddenState: false,
      seq: this.$store.getters.seqNum,
    };
  },
  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);
        }
      }
    },

    goToPage(page) {
      this.$router.push({ name: page });
    },

    playAudio(audioId) {
      const audio = document.getElementById(audioId);
      if (audio) {
        audio.play();
      } else {
        console.error(`Audio element with ID ${audioId} not found.`);
      }
    },

    complete() {
      const { unit_id, book_id } = this.$route.query;
      this.$router.push({
        name: "Dashboard",
        query: { value: this.seq, unit_id, book_id },
      });
    },
  },
  mounted() {
    console.log("챕터2 단어장 마운트 완료");
    this.pageSetting();
  },
};
</script>

<style scoped>
.vocaGroup {
  display: flex;
  flex-wrap: wrap;
}

.word-item {
  width: 49%;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}
.completeBtn {
  margin-right: 100px;
  background-color: #ffba08;
  padding: 10px 30px;
  border-radius: 10px;
  font-size: 28px;
  font-family: "ONEMobilePOPOTF";
}
</style>
