<template>
  <div class="comment-item" v-for="comment in comments" :key="comment.id">
      <div :class="{'comment-children': comment.cmntGrd > 0}" >
        <div class="layout">
        <h4 class="comment-user">{{ comment.rgtrNm }}</h4>
        <span class="comment-date">{{ comment.regDt }}</span>
      </div>

      <textarea v-if="'isUpdate' in comment && comment.isUpdate" class="comment-text mb10" v-model="comment.cmntCn"
        style="width: 100%; min-height: 3rem"></textarea>

      <p v-else class="comment-text">
        {{ comment.useYn == "Y" ? comment.cmntCn : "[ 삭제된 댓글입니다. ]" }}
      </p>

      <div v-if="showReplyInput[comment.cmntId]" class="layout">
          <textarea v-model="comment.replyText" style="width: 100%; min-height: 3rem" class="form-control"></textarea>
          <button class="btn md" @click="fnInsertCmnt(comment)">등록</button>
      </div>

      <div class="layout end btn-wrap pb10">
        <button  v-if="comment.useYn == 'Y' && comment.isUpdate != true"
        :class="{
          'green': !showReplyInput[comment.cmntId],
          'gray': showReplyInput[comment.cmntId],
        }" @click="toggleReplyInput(comment.cmntId)">
          {{ showReplyInput[comment.cmntId] ? "취소" : "답글 달기" }}
        </button>

        <button v-if="comment.useYn == 'Y' && mbrId == comment.rgtr && !showReplyInput[comment.cmntId]"
        :class="{
              'ml5 comment-item-btn icon-btn radius pd5': true,
              'dark-gray': pageRole == 'adm',
              'dark-gray':
                pageRole == 'portal',
            }" @click="fnUpdate(comment)">
          수정
        </button>

        <button  v-if="comment.useYn == 'Y' && (roles[0].authority == 'ROLE_ADMIN' || mbrId == comment.rgtr)"
        @click="fnDeleteCmnt(comment.cmntId)"
          class="ml5 icon-btn red radius pd5">
          삭제
        </button>
      </div>
    </div>

    <CommentItem v-if="comment.children" :comments="comment.children" :pageId="pageId" @isReply="isReply" />
  </div>
</template>

<script>
import queryParams from "../../../resources/js/queryParams.js";
import {
  saveCmnt,
  updateCmnt,
  deleteCmnt,
} from "../../../resources/api/cmnt.js";

export default {
  mixins: [queryParams],
  name: "CommentItem",
  props: {
    comments: {
      type: Array,
      required: true,
    },
    onDelete: {
      type: Function,
      required: true,
    },
    pageId: {
      type: String,
      required: true,
    },

  },
  data() {
    return {
      pageRole: this.$store.state.userType,
      roles: this.$store.state.roles,
      mbrId: this.$store.state.mbrId,

      upCmntId: null,

      showReplyInput: {},
      replyText: "",
    };
  },
  methods: {
    toggleReplyInput(commentId) {
      this.showReplyInput = {
        ...this.showReplyInput,
        [commentId]: !this.showReplyInput[commentId],
      };
      if (!this.showReplyInput[commentId]) {
        this.replyText = { ...this.replyText, [commentId]: "" };
      }
    },
    handleReply(commentId) {
      // console.log(commentId);
      // this.onReply(commentId, this.replyText);
      this.showReplyInput = { ...this.showReplyInput, [commentId]: false };
    },
    // 댓글 수정 로직
    async fnUpdate(comment) {
      if ("isUpdate" in comment && comment.isUpdate) {
        try {
          const params = {
            cmntId: comment.cmntId,
            cmntCn: comment.cmntCn,
          };
          const res = await updateCmnt(params);
          if (res.status == 200) {
            alert("수정되었습니다.");
            comment.isUpdate = false;
          }
        } catch (error) {
          const message = error.response.data.message;
          alert(message);
        }
      } else {
        comment.isUpdate = true;
      }
    },
    // 댓글 등록 로직
    async fnInsertCmnt(comment) {
      // 유효성 검사
      if (comment.replyText.trim() == "" || comment.replyText == null) {
        alert("댓글을 입력해주세요.");
        return;
      }
      try {
        const params = {
          bbsId: this.pageId,
          cmntCn: comment.replyText,
          upCmntId: comment.cmntId,
        };
        const res = await saveCmnt(params);
        if (res.status == 200) {
          alert("댓글이 등록되었습니다.");
          this.replyText = "";
          this.upCmntId = null;
          this.$emit("isReply", true);
          this.toggleReplyInput(comment.cmntId);
        }
      } catch (error) {
        const message = error.response.data.message;
        alert(message);
      }
    },

    isReply(isReply) {
      this.$emit("isReply", isReply);
    },
    // 댓글 삭제 로직
    async fnDeleteCmnt(cmntId) {
      try {
        const params = {
          cmntId: cmntId,
        };
        const res = await deleteCmnt(params);
        if (res.status == 200) {
          alert("댓글이 삭제되었습니다.");
          this.$emit("isReply", true);
        }
      } catch (error) {
        alert("에러가 발생했습니다.\n시스템관리자에게 문의하세요.");
      }
    },
  },
  watch: {},
  computed: {},
  mounted() { 
  },
};
</script>