<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="previousProblem()"
      >
        <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">step3 - 놀면서 배우는 영어</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>
          <!-- <button><img src="../../../../resources/img/btn10_s.png" alt="">
              </button> -->
        </div>

        <div class="text-ct">
          <!-- <p class="title1 mb40" style="color: #464749;">The sun rises in the east and sets in the west. It is very hot during summer.</p>
              <img src="../../../../resources/img/img65_37s.png" alt=""> -->

          <img
            class="exampleImg"
            :src="imgUrl"
            reloadable="true"
            alt="example img"
          />

          <!-- 정답 칸 -->
          <div class="dropGroup flex align-center justify-center mt30">
            <span class="mr30">{{ beforeQuestion }}</span>

            <!-- 드롭 가능한 영역 -->
            <div class="dropContainer" id="targetContainer">
              <div
                v-for="(slot, index) in answerLength"
                :key="index"
                class="dropSlot"
                @dragover.prevent
                @drop="onDrop($event, index)"
              >
                <div
                  class="dropSlot-inner"
                  draggable="true"
                  @dragstart="onDragStart($event, userAnswer[index], index)"
                >
                  <img
                    src="../../../../resources/img/img64_37s.png"
                    alt="answer slot"
                  />
                  <div v-if="userAnswer[index]" class="dropped-char">
                    {{ userAnswer[index].toUpperCase() }}
                  </div>
                </div>
              </div>
            </div>

            <span class="mr30">{{ afterQuestion }}</span>
          </div>

          <!-- 드래그 가능한 버튼 -->
          <div class="dragGroup mt40" id="sourceContainer">
            <button
              v-for="(char, index) in choiceCharacters"
              :key="index"
              draggable="true"
              @dragstart="onDragStart($event, char)"
            >
              <img
                src="../../../../resources/img/img63_37s_2.png"
                alt="drag letter"
              />
              <p>{{ char.toUpperCase() }}</p>
            </button>
          </div>
        </div>
      </div>
      <div class="next-btn" @click="nextProblem()">
        <img src="../../../../resources/img/right.png" alt="" />
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      imgSrc: "client/resources/img/jumpingRabbit.gif",
      example: "",
      beforeQuestion: "",
      afterQuestion: "",
      choice: "",
      answer: "",
      answerLength: 0, // 초기화 시 0으로 설정

      userAnswer: [], // 초기화 시 빈 배열로 설정
      draggedChar: null, // 드래그한 문자를 임시로 저장

      prblm_id: [],
      unit_id: null,
      dataList: [],

      seq: this.$store.getters.seqNum,
      hiddenState: false,

      imgUrl: null,
    };
  },
  computed: {},
  methods: {
    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 });
    },
    splitExample() {
      const parts = this.example.split("/?/");
      if (parts.length === 2) {
        this.beforeQuestion = parts[0];
        this.afterQuestion = parts[1];
      }
    },
    // 드래그 시작 시 호출
    onDragStart(event, char) {
      this.draggedChar = char;
    },
    // 드롭 시 호출
    onDrop(event, index) {
      if (this.userAnswer[index] === "") {
        this.userAnswer.splice(index, 1, this.draggedChar);
        const charIndex = this.choiceCharacters.indexOf(this.draggedChar);
        console.log(charIndex);
        if (charIndex > -1) {
          this.choiceCharacters.splice(charIndex, 1); // 드래그한 문자를 choice에서 제거
        }
        this.draggedChar = null;
        this.checkAnswer(); // 드롭 후 정답을 확인
      }
    },
    checkAnswer() {
      // userAnswer 배열이 모두 채워졌는지 확인
      if (!this.userAnswer.includes("")) {
        setTimeout(() => {
          if (this.userAnswer.join("") === this.answer) {
            alert("정답입니다!");
            this.nextProblem();
          } else {
            alert("오답입니다!");
          }
        }, 0);
      }
    },
    initializeUserAnswer() {
      this.answerLength = this.answer.length; // answer의 길이를 answerLength에 설정
      this.userAnswer = Array(this.answerLength).fill(""); // answerLength만큼 빈 배열 생성
    },
    returnPage() {
      window.location.reload();
    },
    async getProblem() {
      const prblmId = this.currentLearningId.prblm_id;

      try {
        const res = await axios.post(
          "problem/problemInfo.json",
          {
            prblmId: prblmId,
          },
          {
            headers: {
              "Content-Type": "application/json; charset=UTF-8",
            },
          }
        );

        console.log("problem - response : ", res.data);
        this.dataList = res.data.problem;
        this.problemDetail = res.data.problemDetail[0];
        this.example = this.dataList.prblmExpln;
        this.answer = this.problemDetail.prblmDtlExpln;
        this.choice = this.answer ? this.shuffleString(this.answer) : "";
        this.splitExample();
        this.initializeUserAnswer();
        this.choiceCharacters = this.choice.split("");

        const fileInfo = await this.findFile(this.dataList.fileMngId);
        if (fileInfo) {
          this.imgUrl = "http://165.229.169.113:9080/" + fileInfo.fileRpath;
          console.log(this.imgUrl);
        } else {
          console.warn("No file found for the given fileMngId.");
        }
      } catch (error) {
        console.log("problem - error : ", error);
      }
    },
    shuffleString(string) {
      const array = string.split("");
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
      }
      return array.join("");
    },
    async findFile(file_mng_id) {
      try {
        const res = await axios.post(
          "/file/find.json",
          {
            file_mng_id: file_mng_id,
          },
          {
            headers: {
              "Content-Type": "application/json; charset=UTF-8",
            },
          }
        );
        return res.data.list[0];
      } catch (error) {
        console.log("result - error : ", error);
        return null;
      }
    },
    nextProblem() {
      const problemData = {
        prblmImfo: this.currentLearningId,
        prblmNumber: this.currentProblemIndex,
        prblmAns: this.selectedButton,
      };
      this.$store.dispatch("saveProblemData", problemData);
      if (
        this.currentProblemIndex <
        this.$store.state.currentLearningIds.length - 1
      ) {
        this.$store.dispatch("goToNextProblem");
        this.handleProblemDetail(this.currentLearningId);
        this.goToPage(this.problemType);
      } else {
        // 마지막 문제면 이동
        // this.goToPage("Chapter4");
        alert("문제 학습 완료");
        this.complete();
      }
    },
    previousProblem() {
      if (this.currentProblemIndex > 0) {
        this.$store.dispatch("goToPreviousProblem");
        this.handleProblemDetail(this.currentLearningId);
        this.goToPage(this.problemType);
      }
    },

    handleProblemDetail(item) {
      if (item.prblm_type_id === "prblm_type_001") {
        this.problemType = "Chapter3";
      } else if (item.prblm_type_id === "prblm_type_002") {
        this.problemType = "Chapter3_1";
      } else if (item.prblm_type_id === "prblm_type_003") {
        this.problemType = "Chapter3_2";
      } else if (item.prblm_type_id === "prblm_type_004") {
        this.problemType = "Chapter3_3";
      } else if (item.prblm_type_id === "prblm_type_005") {
        this.problemType = "Chapter3_3_1";
      } else if (item.prblm_type_id === "prblm_type_006") {
        this.problemType = "Chapter3_4";
      } else if (item.prblm_type_id === "prblm_type_007") {
        this.problemType = "Chapter3_5";
      } else if (item.prblm_type_id === "prblm_type_008") {
        this.problemType = "Chapter3_6";
      } else if (item.prblm_type_id === "prblm_type_009") {
        this.problemType = "Chapter3_7";
      } else if (item.prblm_type_id === "prblm_type_010") {
        this.problemType = "Chapter3_8";
      } else if (item.prblm_type_id === "prblm_type_011") {
        this.problemType = "Chapter3_9";
      } else if (item.prblm_type_id === "prblm_type_012") {
        this.problemType = "Chapter3_10";
      } else if (item.prblm_type_id === "prblm_type_013") {
        this.problemType = "Chapter3_11";
      } else if (item.prblm_type_id === "prblm_type_014") {
        this.problemType = "Chapter3_12";
      } else if (item.prblm_type_id === "prblm_type_015") {
        this.problemType = "Chapter3_13";
      } else if (item.prblm_type_id === "prblm_type_016") {
        this.problemType = "Chapter3_14";
      } else if (item.prblm_type_id === "prblm_type_017") {
        this.problemType = "Chapter3_15";
      } else if (item.prblm_type_id === "prblm_type_018") {
        this.problemType = "Chapter2_8";
      } else if (item.prblm_type_id === "prblm_type_019") {
        this.problemType = "Chapter2_7";
      } else if (item.prblm_type_id === "prblm_type_020") {
        this.problemType = "Chapter2_5";
      } else if (item.prblm_type_id === "prblm_type_021") {
        this.problemType = "Chapter2_6";
      } else if (item.prblm_type_id === "prblm_type_022") {
        this.problemType = "Chapter2_10";
      } else if (item.prblm_type_id === "prblm_type_023") {
        this.problemType = "Chapter2_11";
      } else if (item.prblm_type_id === "prblm_type_024") {
        this.problemType = "Chapter2_13";
      }
    },
  },
  computed: {
    currentLearningId() {
      return this.$store.getters.currentLearningId;
    },
    currentLabel() {
      return this.$store.getters.currentLabel;
    },
    currentProblemIndex() {
      return this.$store.getters.currentProblemIndex;
    },
    isPreviousButtonDisabled() {
      return this.currentProblemIndex === 0;
    },
  },
  created() {
    console.log("Current Learning ID:", this.currentLearningId);
    console.log("Current Label:", this.currentLabel);
    console.log("Current Problem Index:", this.currentProblemIndex);

    // Fetch or process the current problem based on `currentLearningId`
  },
  mounted() {
    this.getProblem();

    if (this.currentProblemIndex == 0) {
      this.hiddenState = true;
    }
  },
};
</script>
<style scoped>
.dropContainer {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.dropGroup button {
  position: relative;
}

.dropGroup button p {
  font-size: 48px;
}

.dragGroup button p {
  font-size: 48px;
}

.dropGroup span {
  margin: 0px 10px;
}

.dropSlot {
  position: relative;
  width: 64px;
  height: 64px;
}

.dropSlot-inner {
  position: relative;
  width: 100%;
  height: 100%;
}

.dropped-char {
  font-family: "ONEMobilePOPOTF";
  position: absolute;
  top: 55%;
  left: 55%;
  transform: translate(-50%, -50%);
  font-size: 48px;
  font-weight: bold;
  color: black;
  pointer-events: none;
}

.dragGroup button p {
  font-size: 48px;
}

.exampleImg {
  width: 15%;
}

#sourceContainer {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
}

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