<template>
    <div class="title-box flex justify-between mb40">
        <p class="title">평가 등록</p>
    </div>
    <!-- <label for="" class="title1">문제 리스트</label>
    <table class="mt20 mb100">
        <colgroup>
            <col style="width: 10%;">
            <col style="width: 70%;">
            <col style="width: 20%;">
        </colgroup>
        <thead>
            <td>No.</td>
            <td>문제</td>
            <td>보기</td>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>1</td>
                <td><button type="button" title="수정" class="new-btn">
                        수정
                    </button></td>
            </tr>
        </tbody>
    </table> -->
    <div class="content-t">

    <label for="" class="title1">상세 내용</label>
    <div class="board-wrap mt20">
        <div class="flex align-center mb20">
            <label for="" class="title2">단원</label>
            <select v-model="selectedUnit" class="mr10 data-wrap">
                <option v-for="(unit, index) in units" :key="index" :value="unit.unitId">
                    {{ unit.unitName }}
                </option>
            </select>
        </div>
        <div class="flex align-center mb20">
            <label for="" class="title2">평가 유형</label>
            <select v-model="selectedType" class="mr10 data-wrap">
                <option value="중간평가">중간평가</option>
                <option value="최종평가">최종평가</option>
            </select>
        </div>

        <hr>
        <button type="button" title="글쓰기" class="new-btn ml10" @click="buttonSearch">
            문제 추가
        </button>
        <hr>

        <div class="flex align-center mb20">
            <table>
                <thead>
                    <tr>
                        <td>No.</td>
                        <td>문제</td>
                        <td>유형</td>
                        <td>점수</td>
                        <td>순서</td>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(evaluation, index) in evals" :key="evaluation.prblmId">
                        <td>{{ index + 1 }}</td>
                        <td>{{ evaluation.prblmExpln }}</td>
                        <td>{{ evaluation.prblmTypeNm }}</td>
                        <td>{{ evaluation.prblmScr }}</td>
                        <td><input v-model="evaluation.seq"></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <div class="flex justify-between mt50">
        <button type="button" title="글쓰기" class="new-btn" @click="goToPage('ExamList')">
            목록
        </button>
        <div class="flex">
            <button type="button" title="글쓰기" class="new-btn" @click="submitForm">
                등록
            </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" placeholder="" v-model="searchKeyword">
                <button type="button" @click="fetchProblems">
                    <img src="../../../resources/img/look_t.png" alt="">
                </button>
            </div>
            <div class="table-wrap">
                <table>
                    <colgroup>
                        <col style="width: 10%;">
                        <col style="width: 10%;">
                        <col style="width: 30%;">
                        <col style="width: 10%;">
                        <col style="width: 10%;">
                        <col style="width: 10%;">
                        <col style="width: 20%;">
                    </colgroup>
                    <thead>
                        <tr>
                            <td></td>
                            <td>No.</td>
                            <td>문제</td>
                            <td>유형</td>
                            <td>점수</td>
                            <td>작성자</td>
                            <td>등록일</td>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(problem, index) in problems" :key="problem.prblmId">
                            <td><input type="checkbox" v-model="problem.check"></td>
                            <td>{{ index + 1 }}</td>
                            <td>{{ problem.prblmExpln }}</td>
                            <td>{{ problem.prblmTypeNm }}</td>
                            <td>{{ problem.prblmScr }}</td>
                            <td>{{ problem.userId }}</td>
                            <td>{{ problem.regDt }}</td>
                        </tr>
                    </tbody>
                </table>
                <article class="table-pagination flex justify-center align-center mb20 mt30" style="gap: 10px;">
                    <button @click="changePage(currentPage - 1)" :disabled="currentPage === 1">
                        <img src="../../../resources/img/btn27_90t_normal.png" alt="Previous">
                    </button>
                    <button v-for="page in paginationButtons" :key="page" @click="changePage(page)"
                        :class="{ 'selected-btn': currentPage === page }">
                        {{ page }}
                    </button>
                    <button @click="changePage(currentPage + 1)" :disabled="currentPage === totalPages">
                        <img src="../../../resources/img/btn28_90t_normal.png" alt="Next">
                    </button>
                </article>

            </div>
            <div class="flex justify-end ">
                <button type="button" title="" class="new-btn mr10" @click="closeBtn">
                    취소
                </button>
                <button type="button" title="" class="new-btn" @click="insertEval">
                    등록
                </button>
            </div>
        </div>
    </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,
            units: [],
            problems: [],
            selectedUnit: null,
            currentPage: 1,
            pageSize: 5,
            totalPosts: 0,
            searchOption: '',
            searchKeyword: '',
            searchOpen: false,
            evals: [],
        }
    },
    methods: {
        goToPage(page) {
            this.$router.push({ name: page, query: { unit_id: this.selectedUnit  }  });
        },

        buttonSearch() {
            this.searchOpen = true;
            this.fetchProblems();
        },
        closeBtn() {
            this.searchOpen = false;

        },

        fetchUnits() {
            axios({
                url: "/unit/findAll.json",
                method: "post",
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                },
            })
                .then(response => {
                    console.log(response.data)
                    this.units = response.data;
                    if (this.$route.query.unit_id) {
                        this.selectedUnit = this.$route.query.unit_id;
                    }
                })
                .catch(error => {
                    console.error("fetchUnits - error: ", error);
                    alert("단원 목록을 불러오는 중 오류가 발생했습니다.");
                });
        },

        // 문제 가져오기
        async fetchProblems(page = 1) {
            try {
                const response = await axios.post('/problem/problemList.json', {
                    option: this.searchOption,
                    keyword: this.searchKeyword,
                    unitId: this.selectedUnit,
                    pageSize: this.pageSize,
                    startIndex: (page - 1) * 5
                });
                this.problems = response.data.problems;
                this.totalPosts = response.data.totalProblem;

                this.currentPage = page;
            } catch (error) {
                console.error('문제 목록을 불러오는 중 오류가 발생했습니다.', error);
            }
        },
        changePage(page) {
            if (page < 1 || page > this.totalPages) return;
            this.currentPage = page;
            this.fetchProblems(page);
        },

        // 팝업 데이터 가져오기
        insertEval() {
            const selectedProblems = this.problems.filter(problem => problem.check);
            this.evals.push(...selectedProblems);
            this.closeBtn();
        },

        // 평가 데이터 등록하기
        async submitForm() {
            // 필요한 모든 필드를 검사합니다.
            if (!this.selectedUnit) {
                alert("단원을 지정해 주세요.");
                return;
            }

            if (!this.selectedType) {
                alert("평가 유형을 지정해 주세요.");
                return;
            }

            const payload = {
                evalType: this.selectedType,
                unitId: this.selectedUnit
            };

            try {
                const response = await axios.post('/evaluation/insertEvaluation.json', payload);
                console.log('성공:', response.data);
                const evalId = response.data.evalId;
                await this.submitDetailForm(evalId);
                await this.updateSequence();

                this.goToPage('ExamList');

            } catch (error) {
                console.error('오류:', error);
            }
        },

        // 평가 문제 상세 업로드
        async submitDetailForm(evalId) {
            const evalProblemVOList = this.evals.map(evaluation => ({
                evalId: evalId,
                prblmId: evaluation.prblmId,
            }));
            
            try {
                const response = await axios.post('/evalProblem/insertEvalProblem.json', evalProblemVOList);
                console.log('성공:', response.data);
            } catch (error) {
                console.error('오류:', error);
            }
        },

        // 문제 정보 수정하기 (순서 변경)
        async updateSequence(){
            const evalList = this.evals.map(evaluation => ({
                prblmId: evaluation.prblmId,
                seq: evaluation.seq,
            }));

            try {
                const response = await axios.post('/problem/updateProblemSeq.json', evalList);
                console.log('성공:', response.data);
            } catch (error) {
                console.error('오류:', error);
            }
        },
    },
    watch: {

    },
    computed: {
        totalPages() {
            return Math.ceil(this.totalPosts / this.pageSize);
        },
        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('Main2 mounted');
        this.fetchUnits();

    }
}
</script>