<template>
    <div class="title-box flex justify-between mb40">
        <p class="title">{{ bookDetails ? bookDetails.book_nm : 'Loading...' }}</p>
    </div>
    <div class="content-t">

        <label for="" class="title1">단원</label>
        <div class="unit-pagination flex mt10" style="gap: 10px;">
            <button v-for="unit in units" :key="unit.unitId" @click="selectUnit(unit.unitId)"
                :class="{ 'selected-btn': selectedUnitId === unit.unitId }">
                {{ unit.unitName }}
            </button>
            <button><svg-icon type="mdi" :path="mdiPlus" @click="buttonSearch"
                    style=" padding-top: 6px; width: 30px; height: 30px;"></svg-icon></button>
        </div>
        <div class="board-wrap mt30">
            <div class="mb20 ">
                <div class="flex justify-between mb30 align-center">
                    <label for="" class="title1">지문</label>
                    <div class="look-btn flex align-center" @click="goToPage('TextList')">
                        <p>자세히 보기 </p>
                        <svg-icon type="mdi" :path="mdilArrowRight" class=" ml10"></svg-icon>
                    </div>
                </div>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <td>No.</td>
                            <td>제목</td>
                            <td>내용</td>
                            <td>작성자</td>
                            <td>등록일</td>
                        </thead>
                        <tbody>
                            <tr v-for="(post, index) in posts" :key="index" class="post">
                                <td>{{ index }}</td>
                                <td>{{ post.textTtl.slice(0, 20) }}{{ post.textTtl.length > 20 ? '...' : '' }}</td>
                                <td>{{ post.textCnt.slice(0, 20) }}{{ post.textCnt.length > 20 ? '...' : '' }}</td>
                                <td>{{ post.userId }}</td>
                                <td>{{ post.regDt }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <hr>
            <div class="mb20">
                <div class="flex justify-between mb30 align-center">
                    <label for="" class="title1">문제</label>
                    <div class="look-btn flex align-center" @click="goToPage('QuestionList')">
                        <p>자세히 보기 </p>
                        <svg-icon type="mdi" :path="mdilArrowRight" class=" ml10"></svg-icon>
                    </div>
                </div>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <td>No.</td>
                            <td>문제</td>
                            <td>유형</td>
                            <td>점수</td>
                            <td>작성자</td>
                            <td>등록일</td>
                        </thead>
                        <tbody>
                            <tr v-for="(quiz, index) in quizs" :key="index" class="post">
                                <td>{{ index }}</td>
                                <td>{{ quiz.prblmExpln.slice(0, 20) }}{{ quiz.prblmExpln.length > 20 ? '...' : '' }}
                                </td>
                                <td>{{ quiz.prblmTypeNm }}</td>
                                <td>{{ quiz.prblmScr }}</td>
                                <td>{{ quiz.userId }}</td>
                                <td>{{ quiz.regDt }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <hr>
            <div class="mb20">
                <div class="flex justify-between mb30 align-center">
                    <label for="" class="title1">단어</label>
                    <div class="look-btn flex align-center" @click="goToPage('VocaList')">
                        <p>자세히 보기 </p>
                        <svg-icon type="mdi" :path="mdilArrowRight" class=" ml10"></svg-icon>
                    </div>
                </div>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <td>No.</td>
                            <td>지문</td>
                            <td>단어 목록</td>
                            <td>작성자</td>
                        </thead>
                        <tbody>
                            <tr v-for="(wordBook, index) in dataList" :key="wordBook.wdBookId">
                                <td>{{ index }}</td>
                                <td>{{ wordBook.textTtl }}</td>
                                <td>{{ wordBook.wordsPreview }}</td>
                                <td>{{ wordBook.userNm }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <hr>
            <div class="mb20">
                <div class="flex justify-between mb30 align-center">
                    <label for="" class="title1">중간 / 최종</label>
                    <div class="look-btn flex align-center" @click="goToPage('ExamList')">
                        <p>자세히 보기 </p>
                        <svg-icon type="mdi" :path="mdilArrowRight" class=" ml10"></svg-icon>
                    </div>
                </div>
                <div class="table-wrap">
                    <table>
                        <thead>
                    <td>No.</td>
                    <td>중간/최종</td>
                    <td>문항 갯수</td>
                </thead>
                <tbody>
                    <tr v-for="(post, index) in evals" :key="post.evalId">
                        <td>{{ index + 1 }}</td>
                        <td>{{ post.evalType }}</td>
                        <td>{{ post.problemCount }}</td>
                    </tr>
                    </tbody>
                    </table>
                </div>
            </div>
            <hr>
        </div>
        <div class="flex justify-end mt30" style="gap: 10px;">
            <button type="button" title="" class="new-btn" @click="goToPage('RoadMap')">
                로드맵
            </button>
            <button type="button" title="" class="new-btn" @click="deleteUnit()">
                삭제
            </button>
        </div>
    </div>

    <div v-show="searchOpen" class="popup-wrap">
          <div class="popup-box">
            <div class="flex justify-between mb30">
              <p class="popup-title">단원 이름</p>
              <button type="button" class="popup-close-btn" @click="closeBtn">
                <svg-icon type="mdi" :path="mdiWindowClose" class="close-btn"></svg-icon>
              </button>
            </div>
            <div class="search-wrap mb30">
              <input type="text" class="data-wrap" v-model="newUnitName" placeholder="단원 이름을 입력하세요">
            </div>
            <div class="flex justify-center">
              <button type="button" title="취소" class="new-btn mr10" @click="closeBtn">
                취소
              </button>
              <button type="button" title="생성" class="new-btn" @click="insertUnit()">
                생성
              </button>
            </div>
          </div>
        </div>

</template>

<script>
import SvgIcon from '@jamescoyle/vue-icon';
import { mdiMagnify, mdiPlus, mdiWindowClose } from '@mdi/js';
import { mdilArrowRight } from '@mdi/light-js';

import ProgressBar from '../../component/ProgressBar.vue';
import axios from 'axios';

export default {
    data() {
        return {
            mdiPlus: mdiPlus,
            mdiMagnify: mdiMagnify,
            mdilArrowRight: mdilArrowRight,
            mdiWindowClose: mdiWindowClose,

            selectedBookId: this.$route.query.book_id,
            bookDetails: null,
            units: [],
            posts: [],
            quizs: [],
            evals: [],
            dataList: [],
            totalPosts: [],
            selectedUnitId: null, // 선택된 단원 ID 저장 변수
            selectedUnitName: '', // 선택된 단원의 이름 저장 변수

            searchOpen: false,
            newUnitName: '',

        };
    },
    methods: {
        // 페이지 이동
        goToPage(page) {
            this.$router.push({ name: page, query: { unit_id: this.selectedUnitId, book_id: this.$route.query.book_id } });
        },
        // 단원 팝업
        buttonSearch() {
            this.searchOpen = true;
        },
        closeBtn() {
            this.searchOpen = false;
            this.newUnitName = '';
        },

        // 단원 추가 생성
        insertUnit() {
            if(this.newUnitName === ''){
                alert("이름을 입력해주세요!");
                return;
            }

            axios({
                url: "/unit/insertUnit.json",
                method: "post",
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                },
                data: {
                    bookId: this.$route.query.book_id,
                    unitName: this.newUnitName,
                }
            })
                .then(response => {
                    this.findUnit();
                    this.closeBtn();
                })
                .catch(error => {
                    console.error('Error creating book:', error);
                });
        },


        fetchBookDetails() {
            axios({
                url: "/book/find.json",
                method: "post",
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                },
                data: {
                    book_id: this.$route.query.book_id
                }
            })
                .then(response => {
                    console.log('Book details:', response.data);
                    this.bookDetails = response.data;
                })
                .catch(error => {
                    console.error('Error fetching book details:', error);
                });
        },

        // 책 아이디에 맞춘 단원 가져오기
        findUnit() {
            axios({
                url: "/unit/unitList.json",
                method: "post",
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                },
                data: {
                    bookId: this.$route.query.book_id
                }
            })
                .then(response => {
                    console.log('Book details:', response.data);
                    this.units = response.data;
                    this.selectedUnitId = this.units[0].unitId;
                    this.findText();
                    this.findProblem();
                    this.findWord();
                    this.fetchEvalData();
                })
                .catch(error => {
                    console.error('Error selectUnit details:', error);
                });
        },

        // 단원을 선택했을 때 호출되는 메서드
        selectUnit(unitId) {
            this.selectedUnitId = unitId;
            const selectedUnit = this.units.find(unit => unit.unitId === unitId);
            this.selectedUnitName = selectedUnit ? selectedUnit.unitName : '';
            this.findText();
            this.findProblem();
            this.findWord();
            this.fetchEvalData();
        },

        // 지문 정보 5개 정도 가져오기
        findText() {
            axios({
                url: "/text/textSearch.json",
                method: "post",
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                },
                data: {
                    "pageSize": 5,
                    "startIndex": 0,
                    "unitId": this.selectedUnitId
                },
            })
                .then(response => {
                    this.posts = response.data.list;
                })
                .catch(error => {
                    console.error("fetchData - error: ", error);
                    alert("검색 중 오류가 발생했습니다.");
                });
        },

        // 문제 정보 5개 정도 가져오기
        findProblem() {
            axios({
                url: "/problem/problemList.json",
                method: "post",
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                },
                data: {
                    "pageSize": 5,
                    "startIndex": 0,
                    "unitId": this.selectedUnitId
                },
            })
                .then(response => {

                    this.quizs = response.data.problems;
                })
                .catch(error => {
                    console.error("fetchData - error: ", error);
                    alert("검색 중 오류가 발생했습니다.");
                });
        },

        // 단어장 단어 5개 정도 조회
        findWord() {
            const vm = this;
            axios({
                url: "/wordbook/findByUnitId.json",
                method: "post",
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                },
                data: {
                    "unitId": vm.selectedUnitId,
                    "page": 1,
                    "pageSize": 5
                },
            })
                .then(function (response) {
                    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("단어장 목록 조회에 오류가 발생했습니다.");
                });
        },
        // 단어 목록 생략 String 생성 메서드
        generateWordsPreview(words) {
            const maxLength = 20; // 최대 표시 길이 설정
            const wordString = words.join(', ');

            if (wordString.length > maxLength) {
                return wordString.substring(0, maxLength) + '...';
            } else {
                return wordString;
            }
        },
        // 평가 정보 5개 정도 가져오기
        fetchEvalData() {
            axios({
                url: "/evaluation/evaluationUnitList.json",
                method: "post",
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                },
                data: {
                    "pageSize": 5,
                    "startIndex": 0,
                    "unitId": this.selectedUnitId
                },
            })
                .then(response => {
                    this.evals = response.data;
                })
                .catch(error => {
                    console.error("fetchData - error: ", error);
                    alert("검색 중 오류가 발생했습니다.");
                });
        },

        // 단원 삭제
        deleteUnit(){
            const result = confirm('해당 단원을 삭제 하시겠습니까?')
            if (result) {
            } else {
                alert("삭제를 취소했습니다")
                return;
            }

            axios({
                url: "/unit/deleteUnit.json",
                method: "post",
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                },
                data: {
                    "unitId": this.selectedUnitId
                },
            })
                .then(response => {
                    alert("삭제가 완료됐습니다");
                    this.fetchBookDetails();
                    this.findUnit();
                })
                .catch(error => {
                    console.error("fetchData - error: ", error);
                    alert("삭제 중 오류가 발생했습니다.");
                });
        }
    },
    mounted() {
        console.log('Mounted with book_id:', this.$route.query.book_id);
        this.fetchBookDetails();
        this.findUnit();
    },
    components: {
        SvgIcon,
        ProgressBar
    }
}
</script>
<style scoped></style>