localhost-front/src/views/board/BoardView.vue
2025-03-11 10:34:10 +09:00

782 lines
31 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"
:views="views"
:commentNum="commentNum"
:date="formattedBoardDate"
:isLike="false"
:isAuthor="isAuthor"
@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"
autocomplete="off"
v-model="password"
placeholder="비밀번호 입력"
@input="
password = password.replace(/\s/g, '');
inputCheck();
"
/>
<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="attachments.length" 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>
첨부파일 ({{ attachments.length }}개)
</button>
<ul class="dropdown-menu">
<li v-for="(attachment, index) in attachments" :key="index">
<a class="dropdown-item" href="#" @click.prevent="downloadFile(attachment)">
{{ attachment.originalName }}.{{ attachment.extension }}
</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>
<!-- 댓글 입력 영역 -->
<BoardCommentArea
:profileName="profileName"
:unknown="unknown"
:commentAlert="commentAlert"
:passwordAlert="passwordAlert"
:maxLength="500"
@submitComment="handleCommentSubmit"
/>
</div>
<!-- 댓글 목록 -->
<div class="card-footer">
<BoardCommentList
:unknown="unknown"
:comments="commentsWithAuthStatus"
:isCommentPassword="isCommentPassword"
:isEditTextarea="isEditTextarea"
:isDeleted="isDeleted"
:passwordCommentAlert="passwordCommentAlert"
:currentPasswordCommentId="currentPasswordCommentId"
:password="password"
@editClick="editComment"
@deleteClick="deleteComment"
@updateReaction="handleCommentReaction"
@submitComment="handleCommentReply"
@submitPassword="submitCommentPassword"
@commentDeleted="handleCommentDeleted"
@cancelEdit="handleCancelEdit"
@submitEdit="handleSubmitEdit"
@update:password="updatePassword"
/>
<Pagination v-if="pagination.pages" v-bind="pagination" @update:currentPage="handlePageChange" />
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import BoardCommentArea from '@c/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 { useUserInfoStore } from '@/stores/useUserInfoStore';
import { useToastStore } from '@s/toastStore';
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 userStore = useUserInfoStore();
const toastStore = useToastStore();
const currentBoardId = ref(Number(route.params.id));
const unknown = computed(() => profileName.value === '익명');
const currentUserId = computed(() => userStore.user.id); // 현재 로그인한 사용자 id
const authorId = ref(''); // 작성자 id
const isAuthor = computed(() => currentUserId.value === authorId.value);
const commentsWithAuthStatus = computed(() => {
const updatedComments = comments.value.map(comment => ({
...comment,
isCommentAuthor: comment.authorId === currentUserId.value,
children: comment.children.map(reply => ({
...reply,
isCommentAuthor: reply.authorId === currentUserId.value,
})),
}));
return updatedComments;
});
const attachments = ref([]);
// 첨부파일 다운로드 URL 생성
const downloadFile = async attachment => {
try {
const response = await axios.get(`board/download`, {
params: { path: attachment.path },
responseType: 'blob',
});
// Blob에서 파일 다운로드 링크 생성
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', attachment.originalName + '.' + attachment.extension);
document.body.appendChild(link);
link.click();
link.remove();
window.URL.revokeObjectURL(url);
} catch (error) {
console.error('파일 다운로드 오류:', error);
alert('파일 다운로드 중 오류가 발생했습니다.');
}
};
const password = ref('');
const passwordAlert = ref('');
const passwordCommentAlert = ref('');
const isPassword = ref(false);
const isCommentPassword = ref(false);
const currentPasswordCommentId = ref(null);
const lastClickedButton = ref('');
const lastCommentClickedButton = ref('');
const isEditTextarea = ref(false);
const isDeleted = ref(true);
const commentAlert = ref('');
const updatePassword = newPassword => {
password.value = newPassword;
};
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 inputCheck = () => {
passwordAlert.value = '';
};
// 게시물 상세 데이터 불러오기
const fetchBoardDetails = async () => {
try {
const response = await axios.get(`board/${currentBoardId.value}`);
const data = response.data.data;
profileName.value = data.author || '익명';
authorId.value = data.authorId;
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;
attachments.value = data.attachments || [];
} catch (error) {
alert('게시물 데이터를 불러오는 중 오류가 발생했습니다.');
}
};
// 좋아요, 싫어요
const handleUpdateReaction = async ({ boardId, commentId, isLike, isDislike }) => {
try {
await axios.post(`/board/${boardId}/${commentId}/reaction`, {
LOCBRDSEQ: boardId, // 게시글 id
LOCCMTSEQ: commentId, //댓글 id
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;
} 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',
});
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 commentsList = response.data.data.list.map(comment => ({
commentId: comment.LOCCMTSEQ, // 댓글 ID
boardId: comment.LOCBRDSEQ,
parentId: comment.LOCCMTPNT, // 부모 ID
author: comment.author || '익명',
authorId: comment.authorId,
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: [], // 대댓글을 담을 배열
updateAtRaw: comment.LOCCMTUDT,
}));
commentsList.sort((a, b) => b.createdAtRaw - a.createdAtRaw);
for (const comment of commentsList) {
if (!comment.commentId) continue;
const replyResponse = await axios.get(`board/${currentBoardId.value}/reply`, {
params: { LOCCMTPNT: comment.commentId },
});
if (replyResponse.data.data) {
comment.children = replyResponse.data.data.map(reply => ({
author: reply.author || '익명',
authorId: reply.authorId,
commentId: reply.LOCCMTSEQ,
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,
}));
} else {
comment.children = []; // 대댓글이 없으면 빈 배열로 초기화
}
}
// 최종적으로 댓글 목록 업데이트
comments.value = commentsList;
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) {
alert('오류가 발생했습니다.');
}
};
// 댓글 작성
const handleCommentSubmit = async data => {
if (!data) {
return;
}
const { comment, password, isCheck } = data;
if (!comment || comment.trim() === '') {
commentAlert.value = '댓글을 입력해주세요.';
return;
} else {
commentAlert.value = '';
}
if (unknown.value && isCheck && (!password || password.trim() === '')) {
passwordAlert.value = '비밀번호를 입력해야 합니다.';
return;
}
try {
const response = await axios.post(`board/${currentBoardId.value}/comment`, {
LOCBRDSEQ: currentBoardId.value,
LOCCMTRPY: comment,
LOCCMTPWD: isCheck ? password : '',
LOCCMTPNT: 1,
LOCBRDTYP: isCheck ? '300102' : null,
});
if (response.status === 200) {
passwordAlert.value = '';
commentAlert.value = '';
await fetchComments();
} else {
alert('댓글 작성을 실패했습니다.');
}
} catch (error) {
alert('오류가 발생했습니다.');
}
};
// 대댓글 추가
const handleCommentReply = async reply => {
try {
const response = await axios.post(`board/${currentBoardId.value}/comment`, {
LOCBRDSEQ: currentBoardId.value,
LOCCMTRPY: reply.comment,
LOCCMTPWD: reply.password || null,
LOCCMTPNT: reply.parentId,
LOCBRDTYP: reply.isCheck ? '300102' : null,
});
if (response.status === 200) {
if (response.data.code === 200) {
await fetchComments();
} else {
alert('대댓글 작성을 실패했습니다.');
}
}
} catch (error) {
if (error.response) {
alert('오류가 발생했습니다.');
}
alert('오류가 발생했습니다.');
}
};
// 게시글 수정 버튼 클릭
const editClick = unknown => {
const isUnknown = unknown?.unknown ?? false;
if (isUnknown) {
togglePassword('edit');
} else {
router.push({ name: 'BoardEdit', params: { id: currentBoardId.value } });
}
};
// 게시글 삭제 버튼 클릭
const deleteClick = unknown => {
if (unknown) {
togglePassword('delete');
} else {
deletePost();
}
};
const findCommentById = (commentId, commentsList) => {
for (const comment of commentsList) {
if (comment.commentId === commentId) {
return comment; // 부모 댓글일 경우
}
if (comment.children && comment.children.length) {
const found = findCommentById(commentId, comment.children);
if (found) return found; // 대댓글일 경우
}
}
return null;
};
// 댓글 수정(대댓글 포함)
const editComment = comment => {
password.value = '';
passwordCommentAlert.value = '';
currentPasswordCommentId.value = null;
const targetComment = findCommentById(comment.commentId, comments.value);
if (!targetComment) {
return;
}
const isMyComment = comment.authorId === currentUserId.value;
const isAnonymous = comment.author === '익명';
if (isMyComment) {
if (targetComment.isEditTextarea) {
// 수정창이 열려 있는 상태에서 다시 수정 버튼을 누르면 초기화
targetComment.isEditTextarea = false;
currentPasswordCommentId.value = comment.commentId;
} else {
// 다른 모든 댓글의 수정창 닫기
closeAllEditTextareas();
// 현재 댓글만 수정 모드 활성화
targetComment.isEditTextarea = true;
}
} else if (isAnonymous) {
if (currentPasswordCommentId.value === comment.commentId) {
// 이미 비밀번호 입력 중이면 유지
return;
} else {
// 다른 모든 댓글의 수정창 닫기
closeAllEditTextareas();
// 비밀번호 입력
targetComment.isEditTextarea = false;
toggleCommentPassword(comment, 'edit');
}
} else {
alert('수정이 불가능합니다');
}
};
// 모든 댓글의 수정 창 닫기
const closeAllEditTextareas = () => {
comments.value.forEach(comment => {
comment.isEditTextarea = false;
comment.children.forEach(reply => {
reply.isEditTextarea = false;
});
});
};
// 댓글 삭제 버튼 클릭
const deleteComment = async comment => {
const isMyComment = comment.authorId === currentUserId.value;
if (unknown.value && !isMyComment) {
if (comment.isEditTextarea) {
comment.isEditTextarea = false;
comment.isCommentPassword = true;
} else {
toggleCommentPassword(comment, 'delete');
}
} else {
deleteReplyComment(comment);
}
};
// 익명 댓글 비밀번호 창 토글
const toggleCommentPassword = (comment, button) => {
if (lastCommentClickedButton.value === button && currentPasswordCommentId.value === comment.commentId) {
currentPasswordCommentId.value = null; // 비밀번호 창 닫기
password.value = '';
passwordCommentAlert.value = '';
} else {
currentPasswordCommentId.value = comment.commentId; // 비밀번호 창 열기
password.value = '';
passwordCommentAlert.value = '';
}
lastCommentClickedButton.value = button;
};
const togglePassword = button => {
if (lastClickedButton.value === button) {
isPassword.value = !isPassword.value;
} else {
isPassword.value = true;
}
lastClickedButton.value = button;
};
// 게시글 비밀번호 제출
const submitPassword = async () => {
if (!password.value.trim()) {
passwordAlert.value = '비밀번호를 입력해주세요.';
return;
}
try {
const response = await axios.post(`board/${currentBoardId.value}/password`, {
LOCBRDPWD: password.value,
LOCBRDSEQ: currentBoardId.value,
});
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) {
if (error.response && error.response.status === 401) passwordAlert.value = '비밀번호가 일치하지 않습니다.';
}
};
// 댓글 (비밀번호 확인 후)
const submitCommentPassword = async (comment, password) => {
if (!password) {
passwordCommentAlert.value = '비밀번호를 입력해주세요.';
return;
}
const targetComment = findCommentById(comment.commentId, comments.value);
try {
const response = await axios.post(`board/comment/${comment.commentId}/password`, {
LOCCMTPWD: password,
LOCCMTSEQ: comment.commentId,
});
if (response.data.code === 200 && response.data.data === true) {
passwordCommentAlert.value = '';
comment.isCommentPassword = false;
// 수정
if (lastCommentClickedButton.value === 'edit') {
if (targetComment) {
// 다른 모든 댓글의 수정 창 닫기
closeAllEditTextareas();
targetComment.isEditTextarea = true;
passwordCommentAlert.value = '';
currentPasswordCommentId.value = null;
} else {
alert('수정 취소를 실패했습니다.');
}
//삭제
} else if (lastCommentClickedButton.value === 'delete') {
passwordCommentAlert.value = '';
deleteReplyComment(comment);
}
lastCommentClickedButton.value = null;
} else {
passwordCommentAlert.value = '비밀번호가 일치하지 않습니다.';
}
} catch (error) {
if (error.response?.status === 401) {
passwordCommentAlert.value = '비밀번호가 일치하지 않습니다';
}
passwordCommentAlert.value = '비밀번호가 일치하지 않습니다';
}
};
// 게시글 삭제
const deletePost = async () => {
if (confirm('정말 삭제하시겠습니까?')) {
try {
const response = await axios.delete(`board/${currentBoardId.value}`, {
data: { LOCBRDSEQ: currentBoardId.value },
});
if (response.data.code === 200) {
toastStore.onToast('게시물이 삭제되었습니다.');
router.push({ name: 'BoardList' });
} else {
alert('삭제 실패: ' + response.data.message);
}
} catch (error) {
if (error.response) {
alert(`삭제 실패: ${error.response.data.message || '서버 오류'}`);
} else {
alert('네트워크 오류가 발생했습니다. 다시 시도해주세요.');
}
}
}
};
// 댓글 삭제 (대댓글 포함)
const deleteReplyComment = async comment => {
if (!confirm('정말 이 댓글을 삭제하시겠습니까?')) return;
const targetComment = findCommentById(comment.commentId, comments.value);
console.log(comment.parentId, comment.commentId)
try {
const response = await axios.delete(`board/comment/${comment.commentId}`, {
params: { LOCCMTSEQ: comment.commentId, LOCCMTPNT: comment.parentId },
});
if (response.data.code === 200) {
await fetchComments();
if (targetComment) {
// console.log('타겟',targetComment)
// ✅ 댓글 내용만 "삭제된 댓글입니다."로 변경하고, 구조는 유지
targetComment.content = '댓글이 삭제되었습니다.';
targetComment.author = '알 수 없음'; // 익명 처리
targetComment.isDeleted = true; // ✅ 삭제 상태를 추가
}
} else {
alert('댓글 삭제에 실패했습니다.');
}
} catch (error) {
alert('댓글 삭제 중 오류가 발생했습니다.');
}
};
// 댓글 수정 확인
const handleSubmitEdit = async (comment, editedContent) => {
try {
const response = await axios.put(`board/comment/${comment.commentId}`, {
LOCCMTSEQ: comment.commentId,
LOCCMTRPY: editedContent,
});
if (response.status === 200) {
const targetComment = findCommentById(comment.commentId, comments.value);
if (targetComment) {
targetComment.content = editedContent; // 댓글 내용 업데이트
targetComment.isEditTextarea = false; // 수정 모드 닫기
} else {
alert('수정할 댓글을 찾을 수 없습니다.');
}
} else {
alert('댓글 수정 실패했습니다.');
}
} catch (error) {
alert('댓글 수정 중 오류 발생했습니다.');
}
};
// 댓글 수정 취소 (대댓글 포함)
const handleCancelEdit = comment => {
const targetComment = findCommentById(comment.commentId, comments.value);
if (targetComment) {
targetComment.isEditTextarea = false;
} else {
alert('수정 취소를 실패했습니다.');
}
};
// 페이지 변경
const handlePageChange = page => {
if (page !== pagination.value.currentPage) {
pagination.value.currentPage = page;
fetchComments(page);
}
};
// 댓글 삭제 (대댓글 포함)
const handleCommentDeleted = deletedCommentId => {
// 댓글 삭제
const parentIndex = comments.value.findIndex(comment => comment.commentId === deletedCommentId);
if (parentIndex !== -1) {
comments.value.splice(parentIndex, 1);
return;
}
// 대댓글 삭제
for (let parent of comments.value) {
const childIndex = parent.children.findIndex(child => child.commentId === deletedCommentId);
if (childIndex !== -1) {
parent.children.splice(childIndex, 1);
return;
}
}
};
// 날짜
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>