<template>
    <div class="title-box flex justify-between mb40">
        <p class="title">단어장</p>
        <select name="" id="">
            <option value="UNIT_000000000000001">1단원</option>
        </select>
    </div>
    <div class="search-wrap flex justify-between mb20 align-center">
        <div class="title2 gray">?단원 전체 목록</div>
        <div>
            <select name="" id="" class="mr10 data-wrap">
                <option value="">지문</option>
                <option value="">단어</option>
            </select>
            <input  type="text" placeholder="검색하세요.">
            <button type="button" title="단어장 검색">
                <img src="../../../resources/img/look_t.png" alt="">
            </button>
        </div>
    </div>
    <div class="table-wrap">
        <table>
            <thead>
                <td>No.</td>
                <td>지문</td>
                <td>단어 목록</td>
                <td>작성자</td>
                <td>등록일</td>
            </thead>
            <tbody>
                <tr v-for="(wordBook, index) in dataList" :key="wordBook.wdBookId" @click="goToViewPage('VocaDetail')">
                    <td>{{ createNo(index) }}</td>
                    <td>{{ wordBook.textTtl }}</td>
                    <td>{{ wordBook.wordsPreview }}</td>
                    <td>{{ wordBook.userId }}</td>
                    <td>{{ '' }}</td>
                </tr>
            </tbody>
        </table>
        <article class="table-pagination flex justify-center align-center mb20 mt30" style="gap: 10px;">
            <button @click="goToPage(currentPage - 1)">
                <img src="../../../resources/img/btn27_90t_normal.png" alt="">
            </button>
            <button v-for="page in paginationButtons" :key="page" @click="goToPage(page - 1)" :class="{ 'selected-btn': currentPage === page - 1 }">
                {{ page }}
            </button>
            <button @click="goToPage(currentPage + 1)">
                <img src="../../../resources/img/btn28_90t_normal.png" alt="">
            </button>
        </article>
        <div class="flex justify-end ">
            <button type="button" title="등록" class="new-btn" @click="goToPage('VocaInsert')">
                등록
            </button>
        </div>
    </div>
</template>

<script>
import SvgIcon from '@jamescoyle/vue-icon';
import { mdiMagnify } from '@mdi/js';
import axios from "axios";


export default {
    data () {
        return {
            mdiMagnify: mdiMagnify,
            dataList: [],
            currentPage: 0,
            itemsPerPage: 2,
            totalPosts: 0,
            unitId: "UNIT_000000000000001"
        }
    },
    methods: {

        dataSelectList() {
            const vm = this;
            axios({
                url: "/wordbook/findByUnitId.json",
                method: "post",
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                },
                data: {
                    unitId: vm.unitId,
                    page: vm.currentPage + 1,
                    pageSize: vm.itemsPerPage
                },
            })
            .then(function (response) {
                console.log("dataList - response: ", response.data);
                const wordBooks = response.data.wordBooks;
                vm.totalPosts = response.data.totalWordBooks;
                
                // 지문 제목 및 단어 목록 가져오기
                const fetchDataPromises = wordBooks.map(wordBook => {
                    const textTitlePromise = axios.post("/text/selectOneText.json", {
                        textId: wordBook.textId
                    }).then(textResponse => {
                        wordBook.textTtl = textResponse.data[0].text_ttl;
                    }).catch(error => {
                        console.error(`${wordBook.textId}으로 지문 제목 가져오기 실패: `, error);
                        wordBook.textTtl = '제목값없음'; // 오류 시 기본값 설정
                    });

                    const wordsPromise = axios.post("/word/getWordsByBookId.json", {
                        wdBookId: wordBook.wdBookId
                    }).then(wordsResponse => {
                        const words = wordsResponse.data.map(word => word.wdNm);
                        wordBook.wordsPreview = vm.generateWordsPreview(words);
                    }).catch(error => {
                        console.error(`${wordBook.wdBookId}으로 단어 목록 가져오기 실패: `, error);
                        wordBook.wordsPreview = '단어값없음'; // 오류 시 기본값 설정
                    });

                    return Promise.all([textTitlePromise, wordsPromise]);
                });

                // 모든 데이터 가져오기 작업이 완료되면 dataList에 데이터 설정
                Promise.all(fetchDataPromises).then(() => {
                    vm.dataList = wordBooks;
                });
            })
            .catch(function (error) {
                console.log("dataList - error: ", error);
                alert("단어장 목록 조회에 오류가 발생했습니다.");
            });
        },
        generateWordsPreview(words) {
            const maxLength = 20; // 최대 표시 길이 설정
            const wordString = words.join(', ');

            if (wordString.length > maxLength) {
                return wordString.substring(0, maxLength) + '...';
            } else {
                return wordString;
            }
        },
        createNo(index) {
            return this.totalPosts - (this.currentPage * this.itemsPerPage + index);
        },
        goToPage(page) {
            if (page < 0 || page >= this.totalPages) {
                return;
            }
            this.currentPage = page;
            this.dataSelectList();
        },
        goToViewPage(page) {
            this.$router.push({ name: page });
        },
    },
    watch: {

    },
    computed: {
        totalPages() {
            return Math.ceil(this.totalPosts / this.itemsPerPage);
        },
        paginationButtons() {
            let start = Math.max(0, this.currentPage - 2);
            let end = Math.min(start + 5, this.totalPages);

            if (end - start < 5) {
                start = Math.max(0, end - 5);
            }

            return Array.from({ length: end - start }, (_, i) => start + i + 1);
        },
        startIndex() {
            return this.currentPage * this.itemsPerPage;
        }
    },
    components:{
        SvgIcon
    },
    mounted() {
        console.log('Voca Book List Component mounted');
        this.dataSelectList();
    }
}
</script>