<template>
    <div class="container-xxl flex-grow-1 container-p-y">
        <div class="row">
            <div class="col">
                <div class="card">
                    <!-- 프로필 헤더 -->
                    <div class="card-header">
                        <BoardProfile
                            :boardId="currentBoardId"
                            :profileName="profileName"
                            :views="views"
                            :comments="comments"
                            :date="formattedBoardDate"
                            class="pb-6 border-bottom"
                        />
                    </div>
                    <!-- 게시글 내용 -->
                    <div class="card-body">

                        <div class="d-flex justify-content-between align-items-center flex-wrap mb-6 gap-2">
                            <!-- 제목 섹션 -->
                            <div class="me-1">
                                <h5 class="mb-4">{{ boardTitle }}</h5>
                            </div>

                            <!-- 첨부파일 섹션 -->
                            <div v-if="attachment" class="btn-group">
                                <button type="button" class="btn btn-label-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                                    <i class="fa-solid fa-download me-2"></i>
                                    첨부파일
                                    <!-- (<span class="attachment-num">{{ dropdownItems.length }}</span>) -->
                                </button>
                                <!-- <ul class="dropdown-menu">
                                    <li v-for="(item, index) in dropdownItems" :key="index">
                                        <a class="dropdown-item" href="javascript:void(0);">
                                            {{ item.label }}
                                        </a>
                                    </li>
                                </ul> -->
                            </div>
                        </div>

                        <!-- HTML 콘텐츠 렌더링 -->
                        <div class="board-content text-body" style="line-height: 1.6;" v-html="$common.contentToHtml(boardContent)"></div>

                        <!-- 좋아요 버튼 -->
                        <div class="row justify-content-center my-10">
                            <BoardRecommendBtn
                                :bigBtn="true"
                                :boardId="currentBoardId"
                                :commentId="null"
                                :likeCount="likes"
                                :dislikeCount="dislikes"
                                :likeClicked="likeClicked"
                                :dislikeClicked="dislikeClicked"
                                @updateReaction="handleUpdateReaction"
                            />
                        </div>

                        <!-- 첨부파일 목록 -->
                        <!-- <ul v-if="attachments.length" class="attachments mt-4 list-unstyled">
                            <li v-for="(attachment, index) in attachments" :key="index" class="mb-2">
                                <a :href="attachment.url" target="_blank" class="text-decoration-none">{{ attachment.name }}</a>
                            </li>
                        </ul> -->

                        <!-- 댓글 입력 영역 -->
                        <BoardComentArea :profileName="profileName" @submit="handleCommentSubmit"/>

                        <!-- 수정 버튼 -->
                        <!-- <button class="btn btn-primary" @click="goToEditPage">
                            글 수정
                        </button> -->
                    </div>
                    <div class="card-footer">
                        <BoardCommentList/>

                        <Pagination/>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import BoardComentArea from '@c/board/BoardComentArea.vue';
import BoardProfile from '@c/board/BoardProfile.vue';
import BoardCommentList from '@/components/board/BoardCommentList.vue';
import BoardRecommendBtn from '@/components/button/BoardRecommendBtn.vue';
import Pagination from '@/components/pagination/Pagination.vue';
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from '@api';

// 게시물 데이터 상태
const profileName = ref('');
const boardTitle = ref('제목 없음');
const boardContent = ref('');
const date = ref('');
const views = ref(0);
const likes = ref(0);
const dislikes = ref(0);
const likeClicked = ref(false);
const dislikeClicked = ref(false);
const comments = ref(0);
const attachment = ref(false);

// 라우트에서 ID 가져오기
const route = useRoute();
const currentBoardId = ref(Number(route.params.id));

// 글 수정 페이지로 이동
const goToEditPage = () => {
    router.push({ name: 'BoardEdit', params: { id: currentBoardId.value } });
};

// 게시물 상세 데이터 불러오기
const fetchBoardDetails = async () => {
    try {
        const response = await axios.get(`board/${currentBoardId.value}`);
        const data = response.data.data;

        // API 응답 데이터 반영
        // const boardDetail = data.boardDetail || {};
        
        profileName.value = data.author || '익명 사용자';
        
        // 익명확인하고 싶을때
        // profileName.value = '익명 사용자';
        
        boardTitle.value = data.title || '제목 없음';
        boardContent.value = data.content || '';
        date.value = data.date || '';
        views.value = data.cnt || 0;
        likes.value = data.likeCount || 0;
        dislikes.value = data.dislikeCount || 0;
        attachment.value = data.hasAttachment || null;
        comments.value = data.commentCount || 0;
        
    } catch (error) {
        alert('게시물 데이터를 불러오는 중 오류가 발생했습니다.');
    }
};

// 좋아요, 싫어요
const handleUpdateReaction = async ({ boardId, commentId, isLike, isDislike }) => {
    // console.log(type, boardId)
    try {

        const requestData = {
            LOCBRDSEQ: boardId,
            LOCCMTSEQ: commentId,
            MEMBERSEQ: 1, // 멤버아이디 지금은 1 나중에 수정해야함
            LOCGOBGOD: isLike ? 'T' : 'F',
            LOCGOBBAD: isDislike ? 'T' : 'F'
        };

        console.log(requestData)

        const postResponse = await axios.post(`/board/${boardId}/${commentId}/reaction`, requestData);
        // await axios.post(`board/${boardId}/${commentId}/reaction`, { type });

        const response = await axios.get(`board/${boardId}`);
        const updatedData = response.data.data;

        console.log('post요청 결과:', postResponse.data);
        console.log('get요청 결과(좋아요):', response.data.data.likeCount);

        likes.value = updatedData.likeCount;
        dislikes.value = updatedData.dislikeCount;

        likeClicked.value = isLike;
        dislikeClicked.value = isDislike;

        console.log('반응 결과:', postResponse.data);

    } catch (error) {
        alert('반응을 업데이트하는 중 오류 발생');
    }
};

function handleCommentSubmit(payload) {
    console.log('댓글 내용:', payload.comment);
    console.log('익명 여부:', payload.isAnonymous);
    console.log('비밀번호:', payload.password);

}

// 날짜
const formattedBoardDate = computed(() => {
    const dateObj = new Date(date.value);
    return `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}-${String(dateObj.getDate()).padStart(2, '0')} ${String(dateObj.getHours()).padStart(2, '0')}:${String(dateObj.getMinutes()).padStart(2, '0')}`;
});


// 컴포넌트 마운트 시 데이터 로드
onMounted(() => {
    fetchBoardDetails();
});
</script>
