<!--
Program: Board
Author: SDL
Brief: Post View
-->
<template>
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <div v-show="lazyLoad" class="ui--view-container">
      <h4 class="mb-3">
        <span v-if="post.classificationName">[{{ post.classificationName }}] </span>{{ post.postTitle }}
      </h4>
      <div class="ui--view-heading d-flex">
        <div>
          {{ $t('sdl.common.label.createdBy') }} :<span class="ms-1">{{ post.regrName }}</span>
        </div>
        <div class="ms-auto">
          {{ $t('sdl.common.label.createdDate') }} : <span class="ms-1">{{ $filters.dateFormat(post.regDate) }}</span>
          <span class="ui--slide ms-3 me-3">|</span>
          {{ $t('sdl.board.label.inqueryCount') }} :<span class="ms-1">{{ $filters.numberFormat(post.hitCount) }}</span>
          <span class="ui--slide ms-3 me-3">|</span>
          {{ $t('sdl.board.label.recommend') }} :<span class="ms-1">{{ $filters.numberFormat(post.recommendCount) }}</span>
        </div>
      </div>
      <article class="ui--viewer" v-html="$filters.nl2br(post.postDetail)"></article>
      <!-- Display the image in the content area if it is an image board -->
      <p v-for="file in post.imageAttachments" :key="file.fileId">
        <img :ref="file.fileId" class="img-fit" />
      </p>
      <div class="ui--article-like">
        <button class="btn btn-lg btn-outline-secondary" data-toggle="tooltip" data-placement="top" :title="post.recommendYn !== 'Y' ? $t('sdl.board.label.recommend') : $t('sdl.board.label.cancelRecommend')" @click="recommendPost">
          <!-- Branch according to recommendation -->
          <i class="bi bi-heart-fill me-2" :class="{ 'text-danger': post.recommendYn === 'Y' }"> {{ post.recommendYn === 'N' ? '' : '' }} </i>{{ post.recommendCount || 0 }}
        </button>
      </div>
      <hr class="mb-4" />
      <template v-if="boardInfo.fileAttachUsed && post.attachments && post.attachments.length > 0">
        <h5>{{ $t('sdl.common.label.attachments') }}</h5>
        <sdl-fileuploader ref="fileDownload" :fileList="post.attachments" :downloadType="boardInfo.boardId" :maxTotalSize="1073741824" :modifyFlag="false" :multiFileNm="post.postTitle"></sdl-fileuploader>
      </template>
      <!-- //upload -->
      <!--<table class="table table-bordered ui--table-form mb-4">
        <colgroup>
          <col style="width:12.5%" />          <col />
        </colgroup>
        <tbody>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.board.label.prevPost') }}</th>
            <td><a href="javascript:void(0)">Page Title</a></td>
          </tr>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.board.label.nextPost') }}</th>
            <td><a href="javascript:void(0)">Page Title</a></td>
          </tr>
        </tbody>
      </table>-->
      <!-- Sets whether to display the button according to the author / SYS-ADMIN / notice -->
      <div class="ui--button-container">
        <button class="btn btn-secondary btn-lg" type="button" @click="goBackToList">
          {{ $t('sdl.common.label.list') }}
        </button>
        <button v-if="boardInfo.answerUsed && post.noticeLabelType === 'NO'" class="btn btn-secondary btn-lg" type="button" @click="moveReplyPage" v-authorization="'execute'">
          {{ $t('sdl.common.label.reply') }}
        </button>
        <button class="btn btn-secondary btn-lg" type="button" v-if="(currentUser.systemAdminUser || post.regrId === currentUser.userId) && viewType === 'default'" @click="deletePost" v-authorization="'execute'">
          {{ $t('sdl.common.label.delete') }}
        </button>
        <button v-if="(currentUser.systemAdminUser || post.regrId === currentUser.userId) && viewType === 'default'" class="btn btn-secondary btn-lg" type="button" @click="moveEdit" v-authorization="'update'">
          {{ $t('sdl.common.label.edit') }}
        </button>
      </div>
      <div class="card ui--comment" v-if="boardInfo.commentUsed">
        <div class="card-header">
          {{ $t('sdl.board.label.comment') }} <strong>{{ $filters.numberFormat(commentCount) }}</strong>
        </div>
        <!-- commend list -->
        <template v-for="(comment, index) in commentList" :key="comment.commentId">
          <hr v-if="index > 0" :class="{ reply: comment.upperCommentId }" />
          <div class="card-body" :class="{ reply: comment.commentId === selectedReplyCommentId }">
            <div class="media d-flex">
              <i v-if="comment.upperCommentId" class="bi bi-arrow-return-right flex-shrink-0"></i>
              <div class="media-body flex-grow-1 ms-3">
                <h4>
                  <strong>{{ comment.regrName }}</strong>
                  <span v-if="post.regrId === comment.regrId" class="badge rounded-pill text-bg-secondary me-2">
                    {{ $t('sdl.common.label.createdBy') }}
                  </span>
                  <small> {{ $filters.dateFormat(comment.regDate, `${$t('data-format.date.ymd')} hh:mm`) }}</small>
                  <button class="float-end btn ui--btn-xs btn-outline-secondary" @click="openReplyInputArea(comment.commentId)">
                    {{ $t('sdl.board.label.comment') }}
                  </button>
                  <button v-if="comment.regrId === currentUser.userId" class="float-end btn ui--btn-xs btn-outline-secondary me-1" @click="deleteComment(comment.commentId)">
                    {{ $t('sdl.common.label.delete') }}
                  </button>
                </h4>
                <p>{{ comment.commentDetail }}</p>
                <div class="ui--recommand">
                  <button class="btn btn-outline-secondary ui--recomm" :class="{ on: comment.consentType === 'AGREE' }" :title="$t('sdl.board.label.empathy')" @click="recommendComment(comment, 'AGREE')">
                    <i class="bi bi-hand-thumbs-up-fill"></i>{{ $filters.numberFormat(comment.agreeCount) }}
                  </button>
                  <button class="btn btn-outline-secondary ui--unrecomm" :class="{ on: comment.consentType === 'DISAGREE' }" :title="$t('sdl.board.label.nonEmpathy')" @click="recommendComment(comment, 'DISAGREE')">
                    <i class="bi bi-hand-thumbs-down-fill"></i>{{ $filters.numberFormat(comment.disagreeCount) }}
                  </button>
                </div>
              </div>
            </div>
            <div class="card-body" v-if="selectedReplyCommentId === comment.commentId">
              <div class="input-group">
                <textarea v-model="comment.replyCommentDetail" class="form-control" rows="3"></textarea>
                <button class="btn btn-outline-secondary" type="button" @click="registComment(comment)">
                  {{ $t('sdl.common.label.register') }}
                </button>
              </div>
            </div>
          </div>
        </template>
        <hr v-if="commentList.length > 0" />
        <div class="card-body">
          <div class="input-group">
            <textarea v-model="comment.commentDetail" class="form-control" rows="3"></textarea>
            <button class="btn btn-outline-secondary" type="button" @click="registComment()">
              {{ $t('sdl.common.label.register') }}
            </button>
          </div>
        </div>
      </div>
      <!--//Contents Area -->
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import _ from 'lodash';
import SDLUtil from '@/utils/SDLUtil';
import StoreParams from '@/mixin/StoreParams';

export default {
  mixins: [StoreParams],
  data() {
    return {
      currentUser: SDLUtil.getLoginedUserInfo(),
      urlPath: _.replace(this.$route.path, `${this.$CONTEXT}/`, ''),
      roleType: '',
      boardId: '',
      boardInfo: {},
      postId: this.$route.params.postId,
      viewType: this.$route.params.viewType,
      post: {},
      tempCommentList: [],
      commentList: [],
      comment: {},
      selectedReplyCommentId: '',
      lazyLoad: false,
    };
  },
  computed: {
    // Number of comments
    commentCount() {
      return !_.isEmpty(this.commentList) ? this.commentList.length : 0;
    },
  },
  methods: {
    /**
     * param:
     * return:
     * exception:
     * description : Initialize Page
     */
    init() {
      this.boardId = this.urlPath.split('/')[1] || '';
      this.roleType = this.urlPath.split('/')[2] || '';
      this.getPostInfo();
    },
    /**
     * param:
     * return:
     * exception:
     * description : Retrieving Post Information
     */
    async getPostInfo() {
      SDLUtil.showLoadingBar(true);
      await axios
        .get(`${SDLUtil.API_URL}/boards/${this.boardId}/posts/${this.postId}`)
        .then(({ data }) => {
          this.post = data;
          this.boardInfo = this.post.boardInfo;
          // Retrieve the comment list according to whether or not to use the comment.
          if (this.boardInfo.commentUsed) {
            this.getCommentInfo();
          }
          // Image board > Load image attachment
          if (!_.isEmpty(this.post.imageAttachments)) {
            this.post.imageAttachments.map(async image => {
              SDLUtil.showLoadingBar(true);
              await this.getImageContent(image).then(blob => {
                this.$refs[image.fileId][0].src = window.URL.createObjectURL(blob);
              });
              SDLUtil.showLoadingBar(false);
            });
          }
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
      // Attach file initialization
      if (this.boardInfo.fileAttachUsed && !_.isEmpty(this.post.attachments)) this.$refs.fileDownload.init();
      SDLUtil.showLoadingBar(false);
      this.lazyLoad = true;
    },
    /**
     * param: image -> Object
     * return:
     * exception:
     * description : Image attachment load
     */
    getImageContent(image) {
      return new Promise((resolve, reject) => {
        axios({
          url: `${SDLUtil.API_URL}/resource/attachments/file-download/${image.fileId}?downloadType=${image.downloadType}`,
          responseType: 'arraybuffer',
          method: 'get',
        })
          .then(response => {
            const blob = new Blob([response.data], { type: response.headers['content-type'] });
            return resolve(blob);
          })
          .catch(error => reject(error.message));
      });
    },
    /**
     * param:
     * return:
     * exception:
     * description : Retrieving Comments List
     */
    getCommentInfo() {
      SDLUtil.showLoadingBar(true);
      axios
        .get(`${SDLUtil.API_URL}/boards/${this.boardId}/posts/${this.postId}/comments`)
        .then(({ data }) => {
          this.convertCommentList(data);
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
      // Initialize Comment Input Area
      this.comment = {
        postId: this.postId,
        commentDetail: '',
      };
      this.selectedReplyCommentId = '';
    },
    /**
     * param: list -> Array
     * return:
     * exception:
     * description : Change the list of structures to a one-dimensional array
     */
    convertCommentList(list) {
      this.tempCommentList = [];
      list.forEach(comment => {
        this.addCommentList(comment);
      });
      this.commentList = this.tempCommentList;
    },
    /**
     * param: comment -> Object
     * return:
     * exception:
     * description : Compose a comment list
     */
    addCommentList(comment) {
      const tempComment = _.omit(comment, 'replyComments');
      this.tempCommentList.push(tempComment);
      comment.replyComments.forEach(child => {
        this.addCommentList(child);
      });
    },
    /**
     * param:
     * return:
     * exception:
     * description : Post recommendation
     */
    recommendPost() {
      SDLUtil.showLoadingBar(true);
      axios
        .post(`${SDLUtil.API_URL}/boards/${this.boardId}/posts-recommend/${this.postId}`)
        .then(({ data }) => {
          // Update recommended status / number of recommendations
          this.post.recommendYn = data.recommendYn;
          this.post.recommendCount = data.totalRecommendCount;
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: upperComment -> Object
     * return:
     * exception:
     * description : Comment input
     */
    registComment(upperComment) {
      // If it is a comment about the comment, set the upper comment information
      if (upperComment) {
        this.comment.upperCommentId = upperComment.commentId;
        this.comment.commentDetail = upperComment.replyCommentDetail;
      }
      if (_.isEmpty(this.comment.commentDetail.trim())) {
        SDLUtil.alert('sdl.board.alert.valid.commentDetail');
        return;
      }
      const list = upperComment ? upperComment.replyComments : this.commentList;
      this.comment.commentSequence = !_.isEmpty(list) ? _.last(list).commentSequence + 1 : 1;
      SDLUtil.confirm({
        title: 'sdl.common.label.save',
        msg: 'sdl.common.message.doSave',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: async () => {
          SDLUtil.showLoadingBar(true);
          await axios
            .post(`${SDLUtil.API_URL}/boards/${this.boardId}/posts/${this.postId}/comments`, this.comment)
            .then(() => {
              SDLUtil.showLoadingBar(false);
            })
            .catch(err => {
              SDLUtil.showLoadingBar(false);
              SDLUtil.errorAlert(err);
            });
          this.getCommentInfo();
        },
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: comment -> Object
     * param: consentType -> String
     * return:
     * exception:
     * description : Comments empathy / non-empathy
     */
    recommendComment(comment, consentType) {
      // console.log(comment.consentType, consentType);
      const checked = !_.eq(comment.consentType, consentType);
      console.log(comment);
      const param = { consentType, checked };
      let changedType = '';
      SDLUtil.showLoadingBar(true);
      axios
        .post(`${SDLUtil.API_URL}/boards/${this.boardId}/posts/${this.postId}/comment-consent/${comment.commentId}`, param)
        .then(({ data }) => {
          _.assign(comment, data);
          if (_.eq(consentType, 'AGREE')) changedType = checked ? consentType : 'DISAGREE';
          else changedType = checked ? consentType : 'AGREE';
          comment.consentType = changedType;
          if (!checked) {
            comment.consentType = '';
          }
          // console.log(comment.consentType, consentType);
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: commentId -> String
     * return:
     * exception:
     * description : Delete Comments
     */
    deleteComment(commentId) {
      SDLUtil.confirm({
        title: 'sdl.common.label.delete',
        msg: 'sdl.common.message.doDelete',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: async () => {
          SDLUtil.showLoadingBar(true);
          await axios
            .delete(`${SDLUtil.API_URL}/boards/${this.boardId}/posts/${this.postId}/comments/${commentId}`)
            .then(() => {
              SDLUtil.showLoadingBar(false);
            })
            .catch(err => {
              SDLUtil.showLoadingBar(false);
              SDLUtil.errorAlert(err);
            });
          this.getCommentInfo();
        },
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: commentId -> String
     * return:
     * exception:
     * description : Activate the recomment input area
     */
    openReplyInputArea(commentId) {
      this.selectedReplyCommentId = _.eq(this.selectedReplyCommentId, commentId) ? '' : commentId;
    },
    /**
     * param:
     * return:
     * exception:
     * description : Move to List Page
     */
    moveListPage() {
      this.$router.push(`${this.$CONTEXT}/board/${this.boardId}/${this.roleType}/list/post`);
    },
    /**
     * param:
     * return:
     * exception:
     * description : Move to Reply Page
     */
    moveReplyPage() {
      this.$router.push(`${this.$CONTEXT}/board/${this.post.boardId}/${this.roleType}/reply/${this.postId}`);
    },
    /**
     * param:
     * return:
     * exception:
     * description : Move to Edit PAge
     */
    moveEdit() {
      this.$router.push(`${this.$CONTEXT}/board/${this.post.boardId}/${this.roleType}/edit/${this.postId}`);
    },
    /**
     * param:
     * return:
     * exception:
     * description : Delete Post
     */
    deletePost() {
      SDLUtil.confirm({
        title: 'sdl.common.label.delete',
        msg: 'sdl.common.message.doDelete',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => {
          SDLUtil.showLoadingBar(true);
          axios
            .delete(`${SDLUtil.API_URL}/boards/${this.boardId}/posts/${this.postId}`)
            .then(() => {
              SDLUtil.showLoadingBar(false);
              this.goBackToList();
            })
            .catch(err => {
              SDLUtil.showLoadingBar(false);
              SDLUtil.errorAlert(err);
            });
        },
        onCancelEvt: () => console.log('cancel'),
      });
    },
  },
  mounted() {
    this.$nextTick(() => {
      console.info('initialize Board View Page');
      this.init();
    });
  },
};
</script>
<style scoped>
.img-fit {
  max-width: 100%;
  max-height: 100%;
}
</style>
