<template>
    <div id="Chapter1_1" 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">
            <BookInfo />
        </div>
        <div class="flex justify-between align-center">
            <div class="pre-btn" @click="previousProblem()">
                <img src="../../../../resources/img/left.png" alt="" :class="{ active: currentIndex === 0 }" />
            </div>
            <div class="content title-box">
                <p class="title mt25 title-bg">step3</p>
                <div class="flex align-center mb30">
                    <p class="subtitle2 mr20">{{ currentProblemIndex + 1 }}. {{ dataList.prblmExpln }}</p>
                    <!-- <button><img src="../../../../resources/img/btn10_s.png" alt="">
               </button> -->
                </div>

                <div class="text-ct">
                    <div class="time-hint">
                        <button class="hint-btn">HINT</button>
                        <div class="time-bg mt20">
                            <div>
                                <div class="time">
                                    <p class="second">{{ timer }}</p>
                                    <p class="text">sec</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="dragGroup mt40">
                        <div class="flex justify-center" style="gap: 20px">
                            <div class="dropContainer" id="sourceContainer">
                                <button
                                    v-for="(word, index) in question"
                                    :key="index"
                                    draggable="true"
                                    @dragstart="onDragStart($event, word, index)"
                                >
                                    <p>{{ word }}</p>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="dropContainer flex align-center justify-center mt30" id="targetContainer">
                        <div
                            class="dropSlot"
                            v-for="(slot, index) in questionLength"
                            :key="index"
                            @dragover.prevent
                            @drop="onDrop($event, index)"
                        >
                            <div
                                class="dropSlot-inner"
                                draggable="true"
                                @dragstart="onDragStart($event, userAnswer[index], index)"
                            >
                                <div class="dropSlot-inner">
                                    <div v-if="userAnswer[index]" class="dropped-char">
                                        {{ userAnswer[index] }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <button class="submit-button" @click="handleSubmit()" v-if="currentIndex === learningIdsLength - 1">
                    제출하기
                </button>
                <button class="submit-button" @click="nextProblem()" v-else>다음 문제로</button>
            </div>
            <div class="next-btn" @click="nextProblem()">
                <img src="../../../../resources/img/right.png" alt="" />
            </div>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import BookInfo from '../../../component/BookInfo.vue';
export default {
    data() {
        return {
            timer: '00',
            question: [`don't`, 'banana', 'i', 'like'],
            questionLength: null,
            answer: null,

            userAnswer: [], // 초기화 시 빈 배열로 설정
            draggedChar: null, // 드래그한 문자를 임시로 저장
            draggedCharIndex: null, // 드래그한 문자의 인덱스 저장
            dataList: [],
            problemDetail: [],
            currentIndex: null,
            learningIdsLength: null,
        };
    },
    methods: {
        goToPage(page) {
            this.$router.push({ name: page });
        },
        startTimer() {
            if (this.intervalId) {
                clearInterval(this.intervalId);
            }
            this.timer = 5;
            this.intervalId = setInterval(() => {
                if (this.timer > 0) {
                    this.timer--;
                } else {
                    clearInterval(this.intervalId);
                }
            }, 1000);
        },
        initializeAnswer() {
            this.questionLength = this.question.length;
            this.userAnswer = new Array(this.questionLength).fill(null); // userAnswer 배열을 question 길이만큼 초기화
        },
        // 드래그 시작 시 호출
        onDragStart(event, char, index) {
            this.draggedChar = char;
            this.draggedCharIndex = index;
        },
        // 드롭 시 호출
        onDrop(event, index) {
            if (!this.userAnswer[index]) {
                // 해당 슬롯이 비어있는 경우에만 드롭
                this.userAnswer.splice(index, 1, this.draggedChar); // userAnswer에 드래그한 문자 추가
                this.draggedChar = null;
                this.draggedCharIndex = null;
            }
        },
        handleSubmit() {
            const userConfirmed = window.confirm('제출 하시겠습니까?');
            if (userConfirmed) {
                const problemData = {
                    prblmInfo: this.currentLearningId,
                    prblmNumber: this.currentProblemIndex,
                    prblmAns: this.selectedButton,
                };

                const answerData = {
                    prblmId: this.currentLearningId.prblm_id,
                    prblmAns: this.selectedButton,
                    stdId: this.$store.getters.getStdId,
                    prblmLogAnsCnt: 1,
                };

                this.$store.dispatch('saveProblemData', problemData);
                this.$store.dispatch('saveProblemAttempt', answerData);

                console.log(this.$store.getters.getAllProblems);
                console.log(this.$store.getters.getAllAnswers);

                axios({
                    url: 'problemLog/insertProblemLog.json',
                    method: 'post',
                    headers: {
                        'Content-Type': 'application/json; charset=UTF-8',
                    },
                    data: this.$store.getters.getAllAnswers,
                })
                    .then(function (res) {
                        console.log('problem - response : ', res.data);
                        this.goToPage('Chapter4');
                    })
                    .catch(function (error) {
                        console.log('problem - error : ', error);
                    });
            } else {
                console.log('Submission canceled by the user.');
            }
        },
        getProblem() {
            const vm = this;
            const prblmId = this.currentLearningId.prblm_id;
            axios({
                url: 'problem/problemInfo.json',
                method: 'post',
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8',
                },
                data: {
                    prblmId: prblmId,
                },
            })
                .then(function (res) {
                    console.log('problem - response : ', res.data);
                    vm.dataList = res.data.problem;
                    vm.problemDetail = res.data.problemDetail;
                })
                .catch(function (error) {
                    console.log('problem - error : ', error);
                });
        },
        nextProblem() {
            const problemData = {
                prblmInfo: this.currentLearningId,
                prblmNumber: this.currentProblemIndex,
                prblmAns: this.selectedButton,
            };
            const answerData = {
                prblmId: this.currentLearningId.prblm_id,
                prblmAns: this.selectedButton,
                stdId: this.$store.getters.getStdId,
                prblmLogAnsCnt: 1,
            };
            this.$store.dispatch('saveProblemData', problemData);
            this.$store.dispatch('saveProblemAttempt', answerData);
            console.log(this.$store.getters.getAllProblems);
            console.log(this.$store.getters.getAllAnswers);
            if (this.currentProblemIndex < this.$store.state.currentLearningIds.length - 1) {
                this.$store.dispatch('goToNextProblem');
                this.handleProblemDetail(this.currentLearningId);
                this.goToPage(this.problemType);
            }
        },
        previousProblem() {
            if (this.currentProblemIndex > 0) {
                this.$store.dispatch('goToPreviousProblem');
                this.handleProblemDetail(this.currentLearningId);
                this.goToPage(this.problemType);
            }
        },

        handleProblemDetail(item) {
            if (item.prblm_type_id === 'prblm_type_001') {
                this.problemType = 'Chapter3';
            } else if (item.prblm_type_id === 'prblm_type_002') {
                this.problemType = 'Chapter3_1';
            } else if (item.prblm_type_id === 'prblm_type_003') {
                this.problemType = 'Chapter3_2';
            } else if (item.prblm_type_id === 'prblm_type_004') {
                this.problemType = 'Chapter3_3';
            } else if (item.prblm_type_id === 'prblm_type_005') {
                this.problemType = 'Chapter3_3_1';
            } else if (item.prblm_type_id === 'prblm_type_006') {
                this.problemType = 'Chapter3_4';
            } else if (item.prblm_type_id === 'prblm_type_007') {
                this.problemType = 'Chapter3_5';
            } else if (item.prblm_type_id === 'prblm_type_008') {
                this.problemType = 'Chapter3_6';
            } else if (item.prblm_type_id === 'prblm_type_009') {
                this.problemType = 'Chapter3_7';
            } else if (item.prblm_type_id === 'prblm_type_010') {
                this.problemType = 'Chapter3_8';
            } else if (item.prblm_type_id === 'prblm_type_011') {
                this.problemType = 'Chapter3_9';
            } else if (item.prblm_type_id === 'prblm_type_012') {
                this.problemType = 'Chapter3_10';
            } else if (item.prblm_type_id === 'prblm_type_013') {
                this.problemType = 'Chapter3_11';
            } else if (item.prblm_type_id === 'prblm_type_014') {
                this.problemType = 'Chapter3_12';
            } else if (item.prblm_type_id === 'prblm_type_015') {
                this.problemType = 'Chapter3_13';
            } else if (item.prblm_type_id === 'prblm_type_016') {
                this.problemType = 'Chapter3_14';
            } else if (item.prblm_type_id === 'prblm_type_017') {
                this.problemType = 'Chapter3_15';
            } else if (item.prblm_type_id === 'prblm_type_018') {
                this.problemType = 'Chapter2_8';
            } else if (item.prblm_type_id === 'prblm_type_019') {
                this.problemType = 'Chapter2_7';
            } else if (item.prblm_type_id === 'prblm_type_020') {
                this.problemType = 'Chapter2_5';
            } else if (item.prblm_type_id === 'prblm_type_021') {
                this.problemType = 'Chapter2_6';
            } else if (item.prblm_type_id === 'prblm_type_022') {
                this.problemType = 'Chapter2_10';
            } else if (item.prblm_type_id === 'prblm_type_023') {
                this.problemType = 'Chapter2_11';
            } else if (item.prblm_type_id === 'prblm_type_024') {
                this.problemType = 'Chapter2_13';
            }
        },
    },
    watch: {},
    computed: {
        currentLearningId() {
            return this.$store.getters.currentLearningId;
        },
        currentLabel() {
            return this.$store.getters.currentLabel;
        },
        currentProblemIndex() {
            return this.$store.getters.currentProblemIndex;
        },
        isPreviousButtonDisabled() {
            return this.currentProblemIndex === 0;
        },
    },
    created() {
        console.log('Current Learning ID:', this.currentLearningId);
        console.log('Current Label:', this.currentLabel);
        console.log('Current Problem Index:', this.currentProblemIndex);
        this.currentIndex = this.currentProblemIndex;
        this.learningIdsLength = this.$store.state.currentLearningIds.length;

        // Fetch or process the current problem based on `currentLearningId`
    },
    components: {
        BookInfo: BookInfo,
    },
    mounted() {
        this.getProblem();
        this.initializeAnswer();
    },
};
</script>
<style scoped>
.textbox {
    height: 60px;
}

.textbox p {
    font-size: 28px;
    font-weight: bold;
    line-height: 65px;
}

.dropGroup button {
    position: relative;
}

.dropGroup button p {
    font-size: 48px;
}

.dragGroup button p {
    font-size: 48px;
}

#sourceContainer {
    margin-top: 100px;
    display: flex;
    flex-direction: row;
    gap: 230px;
}

#targetContainer {
    margin-top: 15rem;
    height: 100px;
    display: flex;
    flex-direction: row;
    gap: 80px;
}

#targetContainer .dropSlot {
    width: 250px;
    height: 70px;
    padding: 10px;
    border-bottom: 8px solid #ffba08;
}

#targetContainer .dropSlot .dropped-char {
    font-size: 48px;
    font-family: 'ONEMobilePOPOTF';
}

.pre-btn img.active {
    visibility: hidden;
}

.pre-btn img.active {
    visibility: hidden;
}

.submit-button {
    position: absolute;
    background-color: #ffba08;
    padding: 10px 30px;
    border-radius: 10px;
    font-size: 28px;
    font-family: 'ONEMobilePOPOTF';
    right: 5rem;
    bottom: 3rem;
}
</style>
