localhost-front/src/views/board/BoardView.vue
2025-02-20 16:54:37 +09:00

496 lines
19 KiB
Vue

<template>
<div class="container-xxl flex-grow-1 container-p-y">
<div class="row">
<div class="col">
<div class="card">
<!-- 프로필 헤더 -->
<div class="card-header">
<div class="pb-5 border-bottom">
<BoardProfile
:boardId="currentBoardId"
:profileName="profileName"
:unknown="unknown"
:author="isAuthor"
:views="views"
:commentNum="commentNum"
:date="formattedBoardDate"
:isLike="false"
@editClick="editClick"
@deleteClick="deleteClick"
/>
<!-- 비밀번호 입력창 (익명일 경우) -->
<div v-if="isPassword && unknown" class="mt-3 w-25 ms-auto">
<div class="input-group">
<input
type="password"
class="form-control"
v-model="password"
placeholder="비밀번호 입력"
/>
<button class="btn btn-primary" @click="submitPassword">확인</button>
</div>
<span v-if="passwordAlert" class="invalid-feedback d-block text-start">{{ passwordAlert }}</span>
</div>
</div>
</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> -->
<!-- 댓글 입력 영역 -->
<BoardCommentArea
:profileName="profileName"
:unknown="unknown"
@submitComment="handleCommentSubmit"
/>
<!-- <BoardCommentArea :profileName="profileName" :unknown="unknown" /> -->
</div>
<!-- 댓글 목록 -->
<div class="card-footer">
<BoardCommentList
:unknown="unknown"
:comments="comments"
:isEditTextarea="isEditTextarea"
@editClick="editClick"
@deleteClick="deleteClick"
@updateReaction="handleCommentReaction"
@submitComment="handleCommentReply"
/>
<Pagination
v-if="pagination.pages"
v-bind="pagination"
@update:currentPage="handlePageChange"
/>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import BoardCommentArea from '@/components/board/BoardCommentArea.vue';
import BoardProfile from '@c/board/BoardProfile.vue';
import BoardCommentList from '@c/board/BoardCommentList.vue';
import BoardRecommendBtn from '@c/button/BoardRecommendBtn.vue';
import Pagination from '@c/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 commentNum = ref(0);
const attachment = ref(false);
const comments = ref([]);
const route = useRoute();
const router = useRouter();
const currentBoardId = ref(Number(route.params.id));
const unknown = computed(() => profileName.value === '익명 사용자');
const currentUserId = ref('김자바'); // 현재 로그인한 사용자 id
const authorId = ref(null); // 작성자 id
const isAuthor = computed(() => currentUserId.value === authorId.value);
const isEditTextarea = ref(false);
const password = ref('');
const passwordAlert = ref("");
const isPassword = ref(false);
const lastClickedButton = ref("");
const pagination = ref({
currentPage: 1,
pages: 1,
prePage: 0,
nextPage: 1,
isFirstPage: true,
isLastPage: false,
hasPreviousPage: false,
hasNextPage: false,
navigatePages: 10,
navigatepageNums: [1],
navigateFirstPage: 1,
navigateLastPage: 1
});
// 게시물 상세 데이터 불러오기
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 = '익명 사용자';
// 게시글의 작성자 여부를 확인 : 현재 로그인한 사용자가 이 게시글의 작성자인지 여부
authorId.value = data.author;
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;
commentNum.value = data.commentCount || 0;
} catch (error) {
alert('게시물 데이터를 불러오는 중 오류가 발생했습니다.');
}
};
// 좋아요, 싫어요
const handleUpdateReaction = async ({ boardId, commentId, isLike, isDislike }) => {
try {
await axios.post(`/board/${boardId}/${commentId}/reaction`, {
LOCBRDSEQ: boardId, // 게시글 id
LOCCMTSEQ: commentId, //댓글 id
// MEMBERSEQ: 1, // 멤버아이디 지금은 1 나중에 수정해야함
LOCGOBGOD: isLike ? 'T' : 'F',
LOCGOBBAD: isDislike ? 'T' : 'F'
});
const response = await axios.get(`board/${boardId}`);
const updatedData = response.data.data;
likes.value = updatedData.likeCount;
dislikes.value = updatedData.dislikeCount;
likeClicked.value = isLike;
dislikeClicked.value = isDislike;
// console.log(updatedData)
// console.log("갱신된 데이터:", updatedData);
} catch (error) {
alert('반응을 업데이트하는 중 오류 발생');
}
};
// 대댓글 좋아요
const handleCommentReaction = async ({ boardId, commentId, isLike, isDislike }) => {
if (!commentId) return; // 댓글 ID가 없으면 실행 안 함
try {
const response = await axios.post(`/board/${boardId}/${commentId}/reaction`, {
LOCBRDSEQ: boardId, // 게시글 ID
LOCCMTSEQ: commentId, // 댓글 ID
LOCGOBGOD: isLike ? 'T' : 'F',
LOCGOBBAD: isDislike ? 'T' : 'F'
});
console.log("댓글 좋아요 API 응답 데이터:", response.data);
// 좋아요/싫어요 상태 업데이트를 위해 새로 불러오기
await fetchComments();
} catch (error) {
alert('댓글 반응을 업데이트하는 중 오류 발생');
}
};
// 댓글 목록 조회
const fetchComments = async (page = 1) => {
try {
// 댓글
const response = await axios.get(`board/${currentBoardId.value}/comments`, {
params: {
LOCBRDSEQ: currentBoardId.value,
page
}
});
// 대댓글
const replyResponse = await axios.get(`board/${currentBoardId.value}/reply`, {
params: {
LOCCMTPNT: 120
}
});
console.log(replyResponse.data)
comments.value = response.data.data.list.map(comment => ({
commentId: comment.LOCCMTSEQ, // 댓글 ID
boardId: comment.LOCBRDSEQ,
parentId: comment.LOCCMTPNT, // 부모 ID
author: comment.author || "익명 사용자",
content: comment.LOCCMTRPY,
likeCount: comment.likeCount || 0,
dislikeCount: comment.dislikeCount || 0,
likeClicked: comment.likeClicked || false,
dislikeClicked: comment.dislikeClicked || false,
createdAtRaw: new Date(comment.LOCCMTRDT), // 정렬용
createdAt: formattedDate(comment.LOCCMTRDT), // 표시용
children: [] // 대댓글을 담을 배열
}));
pagination.value = {
...pagination.value,
currentPage: response.data.data.pageNum, // 현재 페이지 번호
pages: response.data.data.pages, // 전체 페이지 수
prePage: response.data.data.prePage, // 이전 페이지
nextPage: response.data.data.nextPage, // 다음 페이지
isFirstPage: response.data.data.isFirstPage, // 첫 페이지 여부
isLastPage: response.data.data.isLastPage, // 마지막 페이지 여부
hasPreviousPage: response.data.data.hasPreviousPage, // 이전 페이지 존재 여부
hasNextPage: response.data.data.hasNextPage, // 다음 페이지 존재 여부
navigatePages: response.data.data.navigatePages, // 몇 개의 페이지 버튼을 보여줄 것인지
navigatepageNums: response.data.data.navigatepageNums, // 실제 페이지 번호 목록
navigateFirstPage: response.data.data.navigateFirstPage, // 페이지네이션에서 첫 페이지 번호
navigateLastPage: response.data.data.navigateLastPage // 페이지네이션에서 마지막 페이지 번호
};
} catch (error) {
console.log('댓글 목록 불러오기 오류:', error);
}
};
// 대댓글 목록 조회
// const fetchReplies = async () => {
// try {
// const response = await axios.get(`board/${currentBoardId.value}/reply`);
// const replyData = response.data.data || [];
// return replyData.map(reply => ({
// commentId: reply.LOCCMTSEQ, // 대댓글 ID
// boardId: reply.LOCBRDSEQ,
// parentId: reply.LOCCMTPNT, // 부모 댓글 ID
// content: reply.LOCCMTRPY,
// createdAtRaw: new Date(reply.LOCCMTRDT), // 정렬용
// createdAt: formattedDate(reply.LOCCMTRDT), // 표시용
// likeCount: reply.likeCount || 0,
// dislikeCount: reply.dislikeCount || 0,
// likeClicked: false,
// dislikeClicked: false
// }));
// } catch (error) {
// console.error("대댓글 불러오기 오류:", error);
// return [];
// }
// };
// 댓글 작성
const handleCommentSubmit = async ({ comment, password }) => {
try {
const response = await axios.post(`board/${currentBoardId.value}/comment`, {
LOCBRDSEQ: currentBoardId.value,
LOCCMTRPY: comment,
LOCCMTPWD: password || null,
LOCCMTPNT: 1
});
// console.log('서버 응답 전체:', response.data);
if (response.status === 200) {
console.log('댓글 작성 성공:', response.data.message);
await fetchComments();
} else {
console.log('댓글 작성 실패:', response.data.message);
}
} catch (error) {
console.log('댓글 작성 중 오류 발생:', error);
}
};
// 대댓글 작성
const handleCommentReply = async (reply) => {
const response = await axios.post(`board/${currentBoardId.value}/comment`, {
LOCBRDSEQ: currentBoardId.value,
LOCCMTRPY: reply.comment,
LOCCMTPWD: reply.password || null,
LOCCMTPNT: reply.parentId
});
if (response.status === 200) {
console.log('대댓글 작성 성공:', response.data.message);
await fetchComments();
} else {
console.log('대댓글 작성 실패:', response.data.message);
}
}
const editClick = (unknown) => {
if (unknown) {
togglePassword("edit");
} else {
router.push({ name: "BoardEdit", params: { id: currentBoardId.value } });
}
};
const deleteClick = (unknown) => {
if (unknown) {
togglePassword("delete");
} else {
deletePost();
}
};
const togglePassword = (button) => {
if (lastClickedButton.value === button) {
isPassword.value = !isPassword.value;
} else {
isPassword.value = true;
}
lastClickedButton.value = button;
};
const submitPassword = async () => {
if (!password.value) {
passwordAlert.value = "비밀번호를 입력해주세요.";
return;
}
// console.log("📌 요청 시작: submitPassword 실행됨");
try {
const response = await axios.post(`board/${currentBoardId.value}/password`, {
LOCBRDPWD: password.value,
LOCBRDSEQ: 288, // 나중에 현재 게시글 ID 사용해야함
});
if (response.data.code === 200 && response.data.data === true) {
password.value = '';
isPassword.value = false;
if (lastClickedButton.value === "edit") {
router.push({ name: "BoardEdit", params: { id: currentBoardId.value } });
} else if (lastClickedButton.value === "delete") {
await deletePost();
}
lastClickedButton.value = null;
} else {
passwordAlert.value = "비밀번호가 일치하지 않습니다.????";
}
} catch (error) {
// console.log("📌 전체 오류:", error);
if (error.response) {
if (error.response.status === 401) {
passwordAlert.value = "비밀번호가 일치하지 않습니다.";
} else {
passwordAlert.value = error.response.data?.message || "서버 오류가 발생했습니다.";
}
} else if (error.request) {
passwordAlert.value = "네트워크 오류가 발생했습니다. 다시 시도해주세요.";
} else {
passwordAlert.value = "요청 중 알 수 없는 오류가 발생했습니다.";
}
}
};
const deletePost = async () => {
if (confirm("정말 삭제하시겠습니까?")) {
try {
const response = await axios.delete(`board/${currentBoardId.value}`, {
data: { LOCBRDSEQ: currentBoardId.value }
});
if (response.data.code === 200) {
alert("게시물이 삭제되었습니다.");
router.push({ name: "BoardList" });
} else {
alert("삭제 실패: " + response.data.message);
}
} catch (error) {
if (error.response) {
alert(`삭제 실패: ${error.response.data.message || "서버 오류"}`);
} else {
alert("네트워크 오류가 발생했습니다. 다시 시도해주세요.");
}
}
}
};
// 페이지 변경
const handlePageChange = (page) => {
if (page !== pagination.value.currentPage) {
pagination.value.currentPage = page;
fetchComments(page);
}
};
// 날짜
const formattedDate = (dateString) => {
if (!dateString) return "날짜 없음";
const dateObj = new Date(dateString);
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')}`;
};
const formattedBoardDate = computed(() => formattedDate(date.value));
// 컴포넌트 마운트 시 데이터 로드
onMounted(() => {
fetchBoardDetails()
fetchComments()
});
</script>