<template>
  <div id="Chapter1_2" class="content-wrap">
    <div style="margin: 30px 0px 50px; width: 20%">
      <router-link to="/MyPlan.page">
        <div class="logo mb25">
          <img src="../../../../resources/img/new_img/logo_v2.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>
      <div class="flex">
        <TextToImage />
        <button class="completeBtn" @click="complete">학습 종료</button>
      </div>
    </div>
    <div class="flex justify-between align-center">
      <div
        class="pre-btn"
        style="visibility: hidden"
        @click="goToPage('Chapter1_1')"
      >
        <img src="../../../../resources/img/left.png" alt="" />
      </div>
      <div class="content title-box">
        <p class="title mt25 title-bg">step1. Hello WORLD</p>
        <div
          class="flex align-center ml50 mb15"
          style="margin-top: -30px; gap: 10px"
        >
          <h4>
            각 인물들의 대화를 듣고 읽어봅시다. 아래의 플레이버튼을 눌러 영어
            발음을 들어보세요!
          </h4>
          <div class="listen-btn">
            <img
              src="../../../../resources/img/btn10_s.png"
              alt=""
              @click="playAudio"
            />
            <audio
              id="audio-player"
              src="client/resources/audio/passage/passage_intoduce.mp3"
              preload="auto"
            ></audio>
          </div>
        </div>
        <div class="flex justify-center">
          <div class="readGroup">
            <div>
              <div class="textbox">
                <article
                  v-for="(line, index) in combinedLines"
                  :key="index"
                  :class="[
                    'flex',
                    'align-center',
                    'mb10',
                    { 'justify-end': index % 2 !== 0 },
                  ]"
                >
                  <div v-if="index % 2 === 0" class="icon mr40">
                    <img src="../../../../resources/img/img37_s.png" alt="" />
                    <p class="name">{{ speakerA_name }}</p>
                  </div>
                  <p v-if="index % 2 === 0" class="read">{{ line }}</p>
                  <div class="listen-btn ml10" v-if="index % 2 === 0">
                    <img
                      src="../../../../resources/img/new_img/icon/play_icon.png"
                      alt=""
                      @click="generateTts('male', line)"
                    />
                    <audio id="tts-audio-player" preload="auto"></audio>
                  </div>

                  <div class="listen-btn mr10" v-if="index % 2 !== 0">
                    <img
                      src="../../../../resources/img/new_img/icon/play_icon.png"
                      alt=""
                      @click="generateTts('femail', line)"
                    />
                    <audio id="tts-audio-player" preload="auto"></audio>
                  </div>
                  <p v-if="index % 2 !== 0" class="read mr40">{{ line }}</p>
                  <div v-if="index % 2 !== 0" class="icon">
                    <img src="../../../../resources/img/img37_s.png" alt="" />
                    <p class="name">{{ speakerB_name }}</p>
                  </div>
                </article>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="next-btn" @click="goToNextPage">
        <img src="../../../../resources/img/right.png" alt="" />
      </div>
    </div>
  </div>
</template>

<script>
import TextToImage from "../../../component/TextToImage.vue";
import axios from "axios";
export default {
  data() {
    return {
      text_data: null, // 받아온 지문 정보
      speakerA_name: null,
      speakerB_name: null,
      speakerA: [],
      speakerB: [],

      seq: this.$store.getters.seqNum,
    };
  },
  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 });
    },
    goToNextPage() {
      // alert('지문 학습 완료!');
      this.complete();
      this.goToPage("Chapter1_1");
    },
    // 대화 지문 API
    async fetchText() {
      axios({
        url: "/text/selectOneText.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: {
          textId: this.textId,
        },
      })
        .then((response) => {
          this.text_data = response.data[0].text_cnt;
          this.splitConversation();
        })
        .catch((err) => {
          console.log("지문 에러 : ", err);
        });
    },
    // 대화 지문 split
    splitConversation() {
      const lines = this.text_data.split("/");
      const speakers = {};

      lines.forEach((line) => {
        const [speaker, message] = line.trim().split(":");

        if (!speakers.speakerA_name && !speakers.speakerB_name) {
          // 첫 번째 발화자를 speakerA_name으로 설정
          speakers.speakerA_name = speaker.trim();
          this.speakerA.push(message.trim());
        } else if (
          speakers.speakerA_name &&
          !speakers.speakerB_name &&
          speakers.speakerA_name !== speaker.trim()
        ) {
          // 두 번째 발화자를 speakerB_name으로 설정
          speakers.speakerB_name = speaker.trim();
          this.speakerB.push(message.trim());
        } else if (speaker.trim() === speakers.speakerA_name) {
          // speakerA_name에 내용 추가
          this.speakerA.push(message.trim());
        } else if (speaker.trim() === speakers.speakerB_name) {
          // speakerB_name에 내용 추가
          this.speakerB.push(message.trim());
        }
      });

      this.speakerA_name = speakers.speakerA_name;
      this.speakerB_name = speakers.speakerB_name;
    },

    playAudio() {
      const audio = document.getElementById("audio-player");
      audio.play();
      console.log("playing");
    },

    // 대화 지문 재생
    generateTts(gender, line) {
      console.log("line : ", line);
      axios({
        url: "http://165.229.169.32:35716/generate_tts",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        responseType: "blob",
        data: {
          gender: gender,
          input_text: line,
        },
      })
        .then((response) => {
          console.log("tts 응답 : ", response);
          const audioBlob = new Blob([response.data], { type: "audio/mpeg" });
          const audioUrl = URL.createObjectURL(audioBlob); // 오디오 url 생성
          const audioPlayer = document.getElementById("tts-audio-player");
          audioPlayer.src = audioUrl;
          audioPlayer.play();
        })
        .catch((err) => {
          console.log("tts 에러 : ", err);
        });
    },
  },
  watch: {},
  computed: {
    textId() {
      //console.log("지문 화면 아이디 : ", this.$store.getters.getTextId);
      return this.$store.getters.getTextId;
    },
    combinedLines() {
      const maxLength = Math.max(this.speakerA.length, this.speakerB.length);
      const lines = [];

      for (let i = 0; i < maxLength; i++) {
        if (i < this.speakerA.length) {
          lines.push(this.speakerA[i]);
        }
        if (i < this.speakerB.length) {
          lines.push(this.speakerB[i]);
        }
      }
      return lines;
    },
  },
  components: {
    TextToImage: TextToImage,
  },
  mounted() {
    this.fetchText();
  },
};
</script>

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