localhost-front/src/views/board/BoardView.vue

747 lines
28 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"
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>
<!-- <p>현재 로그인한 사용자 ID: {{ currentUserId }}</p>
<p>게시글 작성자: {{ authorId }}</p>
<p>isAuthor : {{ isAuthor }}</p> -->
<!-- <p>use이미지:{{userStore.user.img}}</p> -->
<!-- <img :src="`http://localhost:10325/upload/img/profile/${userStore.user.profile}`" alt="Profile Image" class="w-px-40 h-auto rounded-circle"/> -->
<!-- 첨부파일 목록 -->
<!-- <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"
:commentAlert="commentAlert"
:passwordAlert="passwordAlert"
@submitComment="handleCommentSubmit"
/>
<!-- <BoardCommentArea :profileName="profileName" :unknown="unknown" /> -->
</div>
<!-- 댓글 목록 -->
<div class="card-footer">
<BoardCommentList
:unknown="unknown"
:comments="commentsWithAuthStatus"
:isCommentPassword="isCommentPassword"
:isEditTextarea="isEditTextarea"
:passwordCommentAlert="passwordCommentAlert"
@editClick="editComment"
@deleteClick="deleteComment"
@updateReaction="handleCommentReaction"
@submitComment="handleCommentReply"
@submitPassword="submitCommentPassword"
@commentDeleted="handleCommentDeleted"
@cancelEdit="handleCancelEdit"
@submitEdit="handleSubmitEdit"
/>
<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 { useUserInfoStore } from '@/stores/useUserInfoStore';
import axios from '@api';
import { formattedDate } from '@/common/formattedDate.js';
// 게시물 데이터 상태
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 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
}))
}));
// console.log("✅ commentsWithAuthStatus 업데이트됨:", updatedComments);
return updatedComments;
});
const password = ref('');
const passwordAlert = ref("");
const passwordCommentAlert = ref("");
const isPassword = ref(false);
const isCommentPassword = ref(false);
const lastClickedButton = ref("");
const lastCommentClickedButton = ref("");
const isEditTextarea = ref(false);
const commentAlert = 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;
// console.log(data)
// API 응답 데이터 반영
// const boardDetail = data.boardDetail || {};
profileName.value = data.author || '익명';
// 익명확인하고 싶을때
// profileName.value = '익명';
console.log("📌 게시글 작성자:", profileName.value); // 작성자 이름 출력
console.log("🔍 익명 여부 (unknown.value):", unknown.value); // 익명 여부 확인
authorId.value = data.authorId; //게시글 작성자 id
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
}
});
// console.log(response.data.data)
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: [], // 대댓글을 담을 배열
}));
for (const comment of commentsList) {
if (!comment.commentId) continue;
const replyResponse = await axios.get(`board/${currentBoardId.value}/reply`, {
params: { LOCCMTPNT: comment.commentId }
});
// console.log(`대댓글 데이터 (${comment.commentId}의 대댓글):`, replyResponse.data);
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 // 페이지네이션에서 마지막 페이지 번호
};
// console.log("📌 댓글 목록:", comments.value);
} catch (error) {
console.log('댓글 목록 불러오기 오류:', error);
}
};
// 댓글 작성
const handleCommentSubmit = async (data) => {
const { comment, password } = data;
const LOCBRDTYP = data.LOCBRDTYP || null; // undefined 방지
try {
const response = await axios.post(`board/${currentBoardId.value}/comment`, {
LOCBRDSEQ: currentBoardId.value,
LOCCMTRPY: comment,
LOCCMTPWD: password,
LOCCMTPNT: 1,
LOCBRDTYP // 익명 여부 전달
});
if (response.status === 200) {
console.log('댓글 작성 성공:', response.data.message);
await fetchComments();
} else {
console.log('댓글 작성 실패:', response.data.message);
}
} catch (error) {
console.log('댓글 작성 중 오류 발생:', error);
}
};
// 대댓글 추가 (부모 `BoardCommentList`로부터 이벤트 받아서 처리)
const handleCommentReply = async (reply) => {
try {
// 익명 여부 체크 (체크박스가 체크되었을 경우 LOCBRDTYP을 300102로 설정)
const requestBody = {
LOCBRDSEQ: currentBoardId.value,
LOCCMTRPY: reply.comment,
LOCCMTPWD: reply.password || null,
LOCCMTPNT: reply.parentId,
LOCBRDTYP: reply.isCheck ? "300102" : null
};
console.log(requestBody)
const response = await axios.post(`board/${currentBoardId.value}/comment`, requestBody);
if (response.status === 200) {
if (response.data.code === 200) {
console.log('✅ 대댓글 작성 성공:', response.data);
await fetchComments();
} else {
console.log('❌ 대댓글 작성 실패 - 서버 응답:', response.data);
alert('대댓글 작성에 실패했습니다.');
}
}
} catch (error) {
console.error('🚨 대댓글 작성 중 오류 발생:', error);
if (error.response) {
console.error('📌 서버 응답 에러:', error.response.data);
}
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) => {
console.log('대댓글 수정 버튼 클릭')
// 부모 또는 대댓글을 찾아서 가져오기
const targetComment = findCommentById(comment.commentId, comments.value);
if (!targetComment) {
console.log("대댓글을 찾을 수 없음:", comment.commentId);
return;
}
// 수정 text창 열림, 닫힘 유무 토글
targetComment.isEditTextarea = !targetComment.isEditTextarea;
// 익명일 경우 비밀번호 입력창 활성화
if (unknown.value) {
toggleCommentPassword(comment, "edit");
}
}
// 댓글 삭제 버튼 클릭
const deleteComment = async (comment) => {
console.log('🗑 댓글 삭제 시도:', comment);
// 익명 사용자인 경우
const isMyComment = comment.authorId === currentUserId.value;
if (unknown.value && !isMyComment) {
console.log('🛑 익명 사용자의 댓글 삭제 시도 (비밀번호 필요)');
if (comment.isEditTextarea) {
// 현재 수정 중이라면 수정 모드를 끄고, 삭제 비밀번호 입력창을 띄움
comment.isEditTextarea = false;
comment.isCommentPassword = true;
} else {
// 수정 중이 아니면 기존의 삭제 비밀번호 입력창을 띄우는 로직 실행
toggleCommentPassword(comment, "delete");
}
} else {
console.log('✅ 로그인 사용자 댓글 삭제 진행');
deleteReplyComment(comment);
}
};
// 익명 비밀번호 창 토글
const toggleCommentPassword = (comment, button) => {
if (lastCommentClickedButton.value === button && comment.isCommentPassword) {
comment.isCommentPassword = false;
} else {
// 모든 댓글의 비밀번호 입력창 닫기
comments.value.forEach(c => (c.isCommentPassword = false));
// 현재 선택된 댓글만 비밀번호 입력창 열기
comment.isCommentPassword = true;
}
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) {
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 submitCommentPassword = async (comment, password) => {
if (!password) {
passwordCommentAlert.value = "비밀번호를 입력해주세요.";
return;
}
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") {
comment.isEditTextarea = true;
passwordCommentAlert.value = "";
// handleSubmitEdit(comment, comment.content);
} else if (lastCommentClickedButton.value === "delete") {
passwordCommentAlert.value = "";
deleteReplyComment(comment)
}
lastCommentClickedButton.value = null;
} else {
passwordCommentAlert.value = "비밀번호가 일치하지 않습니다.";
}
} catch (error) {
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) {
alert("게시물이 삭제되었습니다.");
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;
// console.log("댓글 ID:", comment);
try {
const response = await axios.delete(`board/comment/${comment.commentId}`, {
data: { LOCCMTSEQ: comment.commentId }
});
// console.log("서버 응답:", response.data);
if (response.data.code === 200) {
// console.log("댓글 삭제 성공!");
await fetchComments();
} else {
// console.log("댓글 삭제 실패:", response.data.message);
alert("댓글 삭제에 실패했습니다.");
}
} catch (error) {
console.log("댓글 삭제 중 오류 발생:", error);
alert("댓글 삭제 중 오류가 발생했습니다.");
}
};
// 댓글 수정 확인
const handleSubmitEdit = async (comment, editedContent) => {
try {
const response = await axios.put(`board/comment/${comment.commentId}`, {
LOCCMTSEQ: comment.commentId,
LOCCMTRPY: editedContent
});
// 수정 성공 시 업데이트
// comment.content = editedContent;
// comment.isEditTextarea = false; f
if (response.status === 200) {
const targetComment = findCommentById(comment.commentId, comments.value);
if (targetComment) {
targetComment.content = editedContent; // 댓글 내용 업데이트
targetComment.isEditTextarea = false; // 수정 모드 닫기
} else {
console.warn("❌ 수정할 댓글을 찾을 수 없음");
}
} else {
console.log("❌ 댓글 수정 실패:", response.data);
}
} catch (error) {
console.error("댓글 수정 중 오류 발생:", error);
}
};
// 댓글 수정 취소 (대댓글 포함)
const handleCancelEdit = (comment) => {
const targetComment = findCommentById(comment.commentId, comments.value);
if (targetComment) {
console.log("✅ 원본 데이터 찾음, 수정 취소 처리 가능:", targetComment);
targetComment.isEditTextarea = false;
} else {
console.error("❌ 원본 데이터 찾을 수 없음, 수정 취소 실패");
}
};
// 페이지 변경
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;
}
// 2대댓글 삭제
for (let parent of comments.value) {
const childIndex = parent.children.findIndex(child => child.commentId === deletedCommentId);
if (childIndex !== -1) {
parent.children.splice(childIndex, 1);
return;
}
}
console.error("❌ 삭제할 댓글을 찾을 수 없음:", deletedCommentId);
};
const formattedBoardDate = computed(() => formattedDate(date.value));
// 컴포넌트 마운트 시 데이터 로드
onMounted(() => {
fetchBoardDetails()
fetchComments()
});
</script>