<template>
    <div class=" main">
        <div class="myplan">
            <div class="title-box flex justify-between mb40">
                <p class="title">오늘 공부를 계획해봅시다.</p>
            </div>
            <div class="wrap">
                <p class="title1"> 학습 교재를 선택합시다.</p>
                <div class="search-wrap flex justify-end mb20 mt20">
                    <input class="data-wrap" type="text" placeholder="검색하세요." v-model="keyword">
                    <button type="button" title="위원회 검색" @click="searchBook">
                        <img src="../../../resources/img/look_t.png" alt="">
                    </button>
                </div>
                <div class="table-wrap">
                    <table>
                        <colgroup>
                            <col style="width: 5%;">
                            <col style="width: 10%;">
                            <col style="width: 70%;">
                            <col style="width: 15%;">
                        </colgroup>
                        <tr v-for="(book, index) in books" :key="index">
                            <td><input type="checkbox" class="ui-checkbox mr10" v-model="book.isSelected"></td>
                            <td><img src="../../../resources/img/img214_19s.png" alt=""></td>
                            <td class="text-lf">
                                <p class="title1">{{ book.bookName }}</p>
                                <p class="title2">{{ book.unitName }}</p>
                            </td>
                            <td> <button type="button" title="확인" class="new-btn"
                                    @click="buttonSearch(book.bookName, book.bookId, book.unitId)">
                                    시간입력
                                </button></td>
                        </tr>
                    </table>
                    <div class="flex justify-end">
                        <button type="button" title="선택하기" class="yellow-btn mt30" @click="checkSchedule">
                            선택하기
                        </button>
                    </div>
                </div>
            </div>

            <div class="wrap mt30">
                <p class="title1 mb20">학습일정을 확인해봅시다. </p>
                <div class="flex-column" style="gap: 20px;" v-for="(book, index) in DataArray" :key="index">
                    <div class=" flex justify-between align-center " style="gap: 70px;">
                        <div><img src="../../../resources/img/img217_22s.png" alt=""></div>
                        <div class="wrap cs-pt" :class="{ 'cs-pt-clicked': isClicked }" style="width: 100%;">
                            <div class="text-lf flex justify-between align-center ">
                                <div>
                                    <div class="flex align-center mb10" style="gap: 10px;">
                                        <p class="title2"><em class="gray-bd">{{ book.scheduleUnit }}교시</em></p>
                                        <p class="title1">{{ book.scheduleTime }}</p>
                                    </div>
                                    <div class="title-box  mb10"> <span class="title">{{ book.bookNm }}</span></div>
                                    <p class="title2">{{ book.unitNm }}</p>
                                </div>
                                <div class=""> <img src="../../../resources/img/img214_19s.png" alt=""></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="flex justify-end">
                    <button type="button" title="저장하기" class="yellow-btn mt30" @click="insertSchedule">
                        저장하기
                    </button>
                </div>
            </div>
            <div class="popup-wrap" v-show="searchOpen">
                <div class="popup-box ">
                    <div class="flex mb10  justify-between">
                        <p class="popup-title mb20">시간 선택</p>
                        <button type="button" class="popup-close-btn" @click="closeBtn">
                            <svg-icon type="mdi" :path="mdiWindowClose" class="close-btn"></svg-icon>
                        </button>
                    </div>
                    <article class="mb20 flex-column" style="gap: 20px;">
                        <div v-for="(item, index) in timeList" :key="item.value" class="flex justify-between bg-gray">
                            <div class="flex items-center">
                                <div>
                                    <input type="checkbox" class="ui-checkbox mr20" v-model="checkedItems"
                                        :value="item" />
                                </div>
                                <div class="text-lg">
                                    <p class="title1">{{ item.label }}</p>
                                </div>
                            </div>
                            <div class="flex align-center" style="gap: 10px;">
                                <img src="../../../resources/img/img215_20s.png" alt="" />
                                <p class="title1">{{ item.time }}</p>
                            </div>
                        </div>
                    </article>
                    <div class="flex justify-center mt20">
                        <button type="button" title="선택" class="new-btn" @click="timePick">
                            선택
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

</template>

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

export default {
    data() {
        return {
            isClicked: false,
            mdiMagnify: mdiMagnify,
            mdiWindowClose: mdiWindowClose,
            showModal: false,
            searchOpen: false,
            books: [],
            timeList: [
                { label: "1교시", time: "08:00 ~ 09:00", value: "1" },
                { label: "2교시", time: "09:00 ~ 10:00", value: "2" },
                { label: "3교시", time: "10:00 ~ 11:00", value: "3" },
                { label: "4교시", time: "11:00 ~ 12:00", value: "4" },
                { label: "5교시", time: "13:00 ~ 14:00", value: "5" },
                { label: "6교시", time: "14:00 ~ 15:00", value: "6" },
            ],
            checkedItems: [],
            newDataArray: [],
            DataArray: [],
            nowName: "",
            nowID: "",
            keyword: "",
            unitList: []
        }
    },
    methods: {
        toggleClicked() {
            this.isClicked = !this.isClicked;
        },
        goToPage(page) {
            this.$router.push({ name: page });
        },
        showConfirm(type) {
            let message = '';
            if (type === 'cancel') {
                message = '삭제하시겠습니까?';
            } else if (type === 'reset') {
                message = '초기화하시겠습니까?';
            } else if (type === 'save') {
                message = '등록하시겠습니까?';
            }

            if (confirm(message)) {
                this.goBack();
            }
        },
        closeModal() {
            this.showModal = false;
        },
        buttonSearch(book_nm, book_id, unit_id) {
            this.nowID = book_id
            this.nowName = book_nm
            this.nowunitID = unit_id
            this.searchOpen = true;
        },
        closeBtn() {
            this.searchOpen = false;
        },
        timePick() {
            const selectedBooks = this.books.filter(book => book.isSelected);
            if (selectedBooks.length <= 0) {
                alert('교재를 선택해 주세요.');
            } else {
                if (this.checkedItems.length === 1) {
                    if (this.unitList.find(item => item === this.checkedItems[0].value)) {
                        alert('이미 지정된 시간입니다.');
                    } else {
                        this.addToNewDataArray(this.checkedItems[0]);
                        this.searchOpen = false;
                        this.nowID = ""
                        this.nowunitID = ""
                        this.nowName = ""
                        this.unitList.push(this.checkedItems[0].value)
                        this.checkedItems = []
                    }
                } else if (this.checkedItems.length > 1) {
                    alert('시간은 하나만 선택할 수 있습니다.');
                } else if (this.checkedItems.length <= 0) {
                    alert('시간을 선택해 주세요.');
                }
            }
        },
        addToNewDataArray(selectedTime) {
            if (!this.newDataArray) {
                this.newDataArray = [];
            }
            const newEntry = {
                bookNm: this.nowName,
                scheduleTime: selectedTime.time,
                scheduleUnit: selectedTime.value,
                bookId: this.nowID,
                unitId: this.nowunitID,
                stdId: "2"
            };
            this.newDataArray.push(newEntry);
        },
        async insertSchedule() {
            this.newDataArray = this.DataArray.map(item => ({
                scheduleUnit: item.scheduleUnit,
                bookId: item.bookId,
                unitId: item.unitId,
                stdId: item.stdId
            })); 
            try {
                for (let data of this.newDataArray) {
                    await axios.post('/schedule/insertSchedule.json', data);
                }
                alert('학습 일정이 등록됐어요!');
                this.goToPage('MyPlan')
            } catch (error) {
                console.error('데이터 제출 중 오류 발생:', error);
                alert('데이터 제출 중 오류가 발생했습니다.');
            }
        }, checkSchedule() {
            const sortedArray = this.newDataArray.slice().sort((a, b) => {
                return a.scheduleUnit - b.scheduleUnit;
            });

            this.DataArray = sortedArray;
        },
        searchBook() {
            this.books = []; // books를 빈 배열로 초기화
            axios.post("/book/search.json", { book_nm: this.keyword }, {
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                }
            })
                .then(response => {
                    this.books = response.data.list;
                    this.books.forEach(book => {
                        this.searchUnits(book.book_id);
                    });
                })
                .catch(error => {
                    console.error("searchBook - error:", error);
                    alert("단원 목록을 불러오는 중 오류가 발생했습니다.");
                });
        },
        searchUnits(bookId) { 

            console.log(bookId)
            axios.post("/unit/unitList.json", { bookId: bookId }, {
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                }
            }).then(response => {
                this.books = response.data.map(book => ({
                    ...book,
                    isSelected: false
                }));
                this.searchUnit()
            })
                .catch(error => {
                    console.error("fetchUnits - error:", error);
                    alert("단원 목록을 불러오는 중 오류가 발생했습니다.");
                });
        }, fetchUnits() {
            axios.post("unit/findAll.json", {
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                }
            })
                .then(response => {
                    this.books = response.data.map(book => ({
                        ...book,
                        isSelected: false
                    }));
                    this.searchUnit()
                })
                .catch(error => {
                    console.error("fetchBooks - error: ", error);
                    alert("교재 목록을 불러오는 중 오류가 발생했습니다.");
                });
        }, searchUnit() {
            axios.post("schedule/selectSchedule.json", {stdId:"2"}, {
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                }
            })
                .then(response => { 
                    const units = response.data.map(item => item.schdl_unit); 
                    this.unitList.push(...units); 
                })
                .catch(error => {
                    console.error("searchUnit - error: ", error);
                    alert("교재 목록을 불러오는 중 오류가 발생했습니다.");
                });
        }
    },
    watch: {
        // Watchers for reactivity (if needed)
    },
    computed: {
        // Computed properties (if needed)
    },
    components: {
        SvgIcon
    },
    mounted() {
        console.log('Main2 mounted');
        this.fetchUnits();
    }
}
</script>

<style scoped>
.popup-box {
    width: 750px;
}
</style>