<template>
    <div id="Chapter2_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">
            <BookInfo />
            <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">
                <p class="title mt25 title-bg">STEP 2 - 단어로 공부하는 영어</p>
                <div class="flex align-center mb30">
                    <p class="subtitle2 mr20">다음을 듣고 맞는 단어를 선택하세요.</p>
                    <!-- <button><img src="../../../../resources/img/btn10_s.png" alt="">
          </button> -->
                </div>

                <div class="imgGroup">
                    <div class="flex justify-center">
                        <div class="listenGroup flex" style="gap: 60px">
                            <button
                                class="popTxt"
                                v-for="(item, index) in items"
                                :key="index"
                                @click="updateContent(index)"
                                :class="{ active: selectedIndex === index }"
                            >
                                <img :src="item.imgSrc1" />
                                <img :src="item.imgSrc2" v-if="selectedIndex === index" style="display: block" />
                                <div class="textbox">
                                    <div style="height: 80%; line-height: 200px">
                                        <img :src="item.imgSrc" alt="" style="width: 120px" />
                                    </div>
                                    <p class="subtitle3" style="height: 20%">{{ item.title }}</p>
                                </div>
                            </button>
                        </div>
                    </div>
                    <div class="listen-btn mt50">
                        <img src="client/resources/img/btn10_s.png" alt="Listen" @click="playAudio" />
                    </div>

                    <audio id="audio-player" src="client/resources/audio/bank.wav" preload="auto"></audio>
                </div>
            </div>
            <div class="next-btn" @click="goToNextPage">
                <img src="../../../../resources/img/right.png" alt="" />
            </div>
        </div>
    </div>
</template>
<script>
import SvgIcon from '@jamescoyle/vue-icon';
import axios from 'axios';
import BookInfo from '../../../component/BookInfo.vue';
export default {
    data() {
        return {
            items: [],
            selectedIndex: 0,

            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);

                    // items 배열에 새로운 항목 추가
                    this.items.push({
                        imgSrc1: 'client/resources/img/img61_36s.png',
                        imgSrc2: 'client/resources/img/img62_36s.png',
                        imgSrc: 'http://165.229.169.113:9080/' + fileRpath, // 받아온 fileRpath로 이미지 설정
                        title: word.wdNm,
                    });
                });

                // 모든 요청이 완료될 때까지 대기
                await Promise.all(requests);
            } 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 });
        },
        updateContent(index) {
            this.selectedIndex = index;
            this.currentCon = this.items[index].con;
            setTimeout(() => {
                if (index == 1) {
                    alert('정답입니다!');
                    this.goToNextPage();
                } else {
                    alert('오답입니다! 다시 한번 단어를 듣고 정답을 맞춰보세요!');
                    this.playAudio();
                }
            }, 0);
        },
        playAudio() {
            const audio = document.getElementById('audio-player');
            audio.play();
            console.log('playing');
        },
    },
    components: {
        SvgIcon,
        BookInfo: BookInfo,
    },
    mounted() {
        this.pageSetting();
    },
};
</script>

<style scoped>
.listenGroup {
    height: 305px;
}

.listenGroup button {
    position: relative;
}

.listenGroup .textbox {
    width: 184px;
    height: 206px;
    left: 46%;
    top: 43%;
}

.look-text {
    bottom: 50px;
}

.btnGroup {
    width: 1060px;
    height: 340px;
}

.popTxt {
    width: 216px;
}

.popTxt > img {
    position: absolute;
    top: 0;
    left: 0;
}

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