<!--
Program: Board
Author: SDL
Brief: Post Edit
-->
<template>
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <!-- Form Area -->
    <div class="ui--form-container">
      <h4 class="mb-3">{{ $t('sdl.board.label.basicInfo') }}</h4>
      <form class="needs-validation" novalidate="">
        <div class="mb-2">
          <label>{{ $t('sdl.common.label.title') }} <span class="ui--text-required">&#42;</span></label>
          <input
            v-model="post.postTitle"
            type="text"
            class="form-control"
            v-validation="{
              groupId: '',
              valids: [
                {
                  validFuncs: () => {
                    return checkTitleLength(post.postTitle);
                  },
                  errorMessage: 'sdl.board.message.description1000Characters',
                },
              ],
            }"
            :errorMessage="$t('sdl.department.message.requiredValue')"
          />
        </div>
        <div class="row">
          <div v-if="boardInfo.classificationUsed" class="col-6 mb-3">
            <label>{{ $t('sdl.board.label.groupWord') }}</label>
            <select v-model="post.classificationId" class="form-select d-block w-100" :disabled="post.postId && post.upperPostId !== ''">
              <option value="">{{ $t('sdl.common.label.none') }}</option>
              <option v-for="item in boardInfo.classifications" :value="item.classificationId" :key="item.classificationId">
                {{ item.classificationName }}
              </option>
            </select>
          </div>
          <div v-if="isAdminBoard && boardInfo.noticeLabelUsed && post.upperPostId === ''" class="col-6 mb-3">
            <label>{{ $t('sdl.board.label.noticeLabel.display') }}</label>
            <select v-model="post.noticeLabelType" class="form-select d-block w-100">
              <option value="NO">{{ $t('sdl.common.label.nonUse') }}</option>
              <option value="THIS">{{ $t('sdl.board.label.currentBoard') }}</option>
              <option value="ALL">{{ $t('sdl.board.label.allBoard') }}</option>
            </select>
            <div class="mt-1 bg-light rounded p-3" v-show="post.noticeLabelType !== 'NO'" :class="{ fade: post.noticeLabelType === 'NO' }">
              <label>{{ $t('sdl.board.label.noticeLabel.period') }}</label>
              <div class="d-block w-100">
                <sdl-datepicker v-model="noticePeriod" ref="noticePeriod" :period="noticePeriod" :wrap-class="'input-group input-date-in'" :default="false"></sdl-datepicker>
              </div>
            </div>
          </div>
          <div v-if="(!boardInfo.classificationUsed || !boardInfo.noticeLabelUsed) && post.upperPostId === ''" class="col-6 mb-3"></div>
          <div v-if="!boardInfo.classificationUsed && !boardInfo.noticeLabelUsed && post.upperPostId === ''" class="col-6 mb-3"></div>
          <div v-show="isAdminBoard && boardInfo.noticePopupUsed && post.upperPostId === ''" class="col-6 mb-3">
            <label>{{ $t('sdl.board.label.noticePopup') }}</label>
            <div class="d-block w-100">
              <div class="form-check form-check-inline">
                <input v-model="post.noticePopupUsed" id="noticePopupUsed_Y" class="form-check-input" type="radio" :value="true" />
                <label class="form-check-label" for="noticePopupUsed_Y">{{ $t('sdl.common.label.use') }}</label>
              </div>
              <div class="form-check form-check-inline">
                <input v-model="post.noticePopupUsed" id="noticePopupUsed_N" class="form-check-input" type="radio" :value="false" />
                <label class="form-check-label" for="noticePopupUsed_N">{{ $t('sdl.common.label.nonUse') }}</label>
              </div>
              <div class="text-danger" v-if="boardInfo.noticePopupUnfoldUsed">
                {{ $t('sdl.board.label.noticePopup.restrictionGuide') }}
              </div>
            </div>
            <div class="mt-1 bg-light rounded p-3" v-show="post.noticePopupUsed && !boardInfo.noticePopupUnfoldUsed" :class="{ fade: !post.noticePopupUsed && !boardInfo.noticePopupUnfoldUsed }">
              <label>{{ $t('sdl.board.label.noticePopup.period') }}</label>
              <div class="d-block w-100 mb-3">
                <sdl-datepicker v-model="popupPeriod" ref="popupPeriod" :period="popupPeriod" :start-disabled-date="startDisabledDate" :wrap-class="'input-group input-date-in'" :default="false"></sdl-datepicker>
              </div>
            </div>
          </div>
        </div>
        <template v-if="boardInfo.editorUsed && lazyLoad">
          <sdl-editor v-model="post.postDetail"></sdl-editor>
        </template>
        <template v-else-if="!boardInfo.editorUsed">
          <textarea style="width: 100%; overflow: scroll; height: 250px; max-height: 250px" class="form-control" v-model="post.postDetail"></textarea>
        </template>
        <div v-else v-html="this.$filters.nl2br(post.postDetail)" ref="postDetail" class="form-control" style="overflow: scroll; height: 250px; max-height: 250px" contenteditable="true"></div>
        <hr class="mb-4" />
        <template v-if="boardInfo.fileAttachUsed || boardInfo.imageAttachUsed">
          <h4 class="mb-3">
            {{ $t('sdl.common.label.attachments') }}
          </h4>
        </template>
        <template v-if="boardInfo.imageAttachUsed">
          <h5>{{ $t('sdl.board.label.uploadPicture') }}</h5>
          <!-- upload -->
          <sdl-fileuploader
            ref="imageUploader"
            :fileList="post.imageAttachments"
            @complete="uploadCompleted"
            :downloadType="`${boardId}_IMAGE`"
            :maxTotalSize="1073741824"
            :modifyFlag="true"
            useExtList="png|jpg|jpeg|bmp|gif"
          ></sdl-fileuploader>
          <!-- //upload -->
        </template>
        <template v-if="boardInfo.fileAttachUsed">
          <h5>{{ $t('sdl.common.label.attachments') }}</h5>
          <!-- upload -->
          <sdl-fileuploader ref="fileUploader" :fileList="post.attachments" @complete="uploadCompleted" :downloadType="boardId" :maxTotalSize="1073741824" :modifyFlag="true" useExtList="zip|xlsx|xls|ppt|pptx"></sdl-fileuploader>
        </template>

        <hr class="mb-4" v-if="boardInfo.imageAttachUsed || boardInfo.fileAttachUsed" />
        <div class="ui--button-container">
          <button class="btn btn-secondary btn-lg" type="button" @click="cancelPost()">
            {{ $t('sdl.common.label.cancel') }}
          </button>
          <button class="btn btn-primary btn-lg" type="button" @click="saveConfirm()" v-authorization="['update', 'execute']">
            {{ !postId ? $t('sdl.common.label.register') : $t('sdl.common.label.save') }}
          </button>
        </div>
      </form>
    </div>
  </div>
  <pre>
    post:{{ post }}
    
  </pre>
</template>

<script>
import axios from 'axios';
import _ from 'lodash';
import { SDLUtil, DateUtil } from '@/utils';
import SDLEditor from '@/components/common/control/editor';
import StoreParams from '@/mixin/StoreParams';

export default {
  mixins: [StoreParams],
  components: {
    'sdl-editor': SDLEditor,
  },
  data() {
    return {
      form: null,
      urlPath: _.replace(this.$route.path, `${this.$CONTEXT}/`, ''),
      isAdminBoard: false,
      roleType: '',
      boardId: '',
      mode: '',
      boardInfo: {},
      postId: this.$route.params.postId,
      post: {
        postTitle: '',
        classificationId: '',
        noticePopupUsed: false,
        noticeLabelType: 'NO',
        noticeLabelStartDate: '',
        noticeLabelEndDate: '',
        noticePopupStartDate: '',
        noticePopupEndDate: '',
        postDetail: '',
        attachments: [],
        imageAttachments: [],
        hierarchyLevel: 1,
        upperPostId: '',
      },
      noticePeriod: {},
      popupPeriod: {
        startDate: DateUtil.now(),
        endDate: DateUtil.addDate(1, 'M', DateUtil.now()),
      },
      lazyLoad: false,
      startDisabledDate: DateUtil.now(),
    };
  },
  methods: {
    /**
     * param:
     * return:
     * exception:
     * description : Initialize Page
     */
    init() {
      this.boardId = this.urlPath.split('/')[1] || '';
      this.roleType = this.urlPath.split('/')[2] || '';
      this.mode = this.urlPath.split('/')[3] || '';
      this.isAdminBoard = _.eq(this.roleType, 'admin');
      this.getBoardInfo();
    },
    checkTitleLength(str) {
      let len = 0;
      for (let i = 0; i < str.length; i += 1) {
        if (escape(str.charAt(i)).length === 6) {
          len += 1;
        }
        len += 1;
      }
      return !(len > 100);
    },
    /**
     * param:
     * return:
     * exception:
     * description : Retrieving board information
     */
    async getBoardInfo() {
      SDLUtil.showLoadingBar(true);
      await axios
        .get(`${SDLUtil.API_URL}/boards/${this.boardId}`)
        .then(({ data }) => {
          this.boardInfo = data;
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
      if (this.postId) {
        await this.getPostInfo();
      } else {
        this.post.boardId = this.boardInfo.boardId;
        this.lazyLoad = true;
      }
    },
    /**
     * 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;
          // If writing a reply, change the post property
          if (_.eq(this.mode, 'reply')) {
            this.post = {
              ...this.post,
              ...{
                boardId: this.boardId,
                postTitle: `Re: ${this.post.postTitle}`,
                classificationId: this.post.classificationId,
                postDetail: '',
                hierarchyLevel: this.post.hierarchyLevel + 1,
                upperPostId: this.postId,
                attachments: [],
                imageAttachments: [],
              },
            };
          } else {
            // initialization of notice label period
            if (this.isAdminBoard && this.boardInfo.noticeLabelUsed) {
              if (!_.isEmpty(this.post.noticeLabelStartDate)) {
                this.$refs.noticePeriod.updateStartDate(DateUtil.stdFormat(this.post.noticeLabelStartDate));
              }
              if (!_.isEmpty(this.post.noticeLabelEndDate)) {
                this.$refs.noticePeriod.updateEndDate(DateUtil.stdFormat(this.post.noticeLabelEndDate));
              }
            }
            // initialization of Main announcement popup period
            if (this.isAdminBoard && this.boardInfo.noticePopupUsed) {
              if (!_.isEmpty(this.post.noticePopupStartDate)) {
                this.$refs.popupPeriod.updateStartDate(DateUtil.stdFormat(this.post.noticePopupStartDate));
              }
              if (!_.isEmpty(this.post.noticePopupEndDate)) {
                this.$refs.popupPeriod.updateEndDate(DateUtil.stdFormat(this.post.noticePopupEndDate));
              }
            }
          }
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
      this.lazyLoad = true;
      // file Uploader Initialization > Import existing upload files (if in modify mode)
      if (_.eq(this.mode, 'edit') && this.boardInfo.fileAttachUsed) this.$refs.fileUploader.init();
      if (_.eq(this.mode, 'edit') && this.boardInfo.imageAttachUsed) this.$refs.imageUploader.init();
    },
    /**
     * param: downloadType -> String
     * param: fileList -> Array
     * return:
     * exception:
     * description : file upload callback
     */
    uploadCompleted(downloadType, fileList) {
      // File / image upload status
      const attachType = _.includes(downloadType, '_IMAGE') ? 'imageAttachments' : 'attachments';
      // Setting uploaded file information
      this.post[attachType] = fileList;
      /**
       * Configure the attachment after executing the file upload depending on whether the file is uploaded or not
       * Run image file upload sequentially
       */
      if (_.eq(attachType, 'attachments') && this.boardInfo.fileAttachUsed) {
        if (this.boardInfo.imageAttachUsed) this.$refs.imageUploader.onUpload();
        else this.savePost();
      } else if (_.eq(attachType, 'imageAttachments') && this.boardInfo.imageAttachUsed) {
        // If it is an image type board, check image attachment
        if (_.eq(this.boardInfo.boardType, 'PICTURE') && _.isEmpty(fileList)) {
          SDLUtil.alert('sdl.board.alert.valid.picture');
          SDLUtil.showLoadingBar(false);
          return;
        }
        this.savePost();
      } else {
        this.$refs.imageUploader.onUpload();
      }
    },
    /**
     * param:
     * return:
     * exception:
     * description : Verification of posting input
     */
    validatePost() {
      // Check the message post input
      if (SDLUtil.onSubmitValidation()) return false;
      if (this.post.noticePopupUsed && SDLUtil.onSubmitValidation('noticePopup')) return false;
      // Set the contents of the post to the div area value when the editor is not used
      // if (!this.boardInfo.editorUsed) this.post.postDetail = this.$refs.postDetail.innerText;
      // Check if the notice label posting period is entered.
      if (this.isAdminBoard && !_.eq(this.mode, 'reply') && this.boardInfo.noticeLabelUsed && !_.eq(this.post.noticeLabelType, 'NO')) {
        if (_.isEmpty(this.noticePeriod.startDate) || _.isEmpty(this.noticePeriod.endDate)) {
          SDLUtil.alert('sdl.board.alert.valid.noticeLabel.period');
          return false;
        }
        this.post.noticeLabelStartDate = _.replace(DateUtil.stdFormat(this.noticePeriod.startDate), /-/g, '');
        this.post.noticeLabelEndDate = _.replace(DateUtil.stdFormat(this.noticePeriod.endDate), /-/g, '');
      }
      // Check if the notice popup posting period is entered
      if (this.isAdminBoard && !_.eq(this.mode, 'reply') && this.post.noticePopupUsed) {
        if (_.isEmpty(this.popupPeriod.startDate) || _.isEmpty(this.popupPeriod.endDate)) {
          SDLUtil.alert('sdl.board.alert.valid.noticePopup.period');
          return false;
        }
        this.post.noticePopupStartDate = _.replace(DateUtil.stdFormat(this.popupPeriod.startDate), /-/g, '');
        this.post.noticePopupEndDate = _.replace(DateUtil.stdFormat(this.popupPeriod.endDate), /-/g, '');
      }
      if (_.isEmpty(this.post.postDetail.trim()) || _.eq(this.post.postDetail.trim(), '<p>&nbsp;</p>')) {
        SDLUtil.alert('sdl.board.alert.valid.boardDetail');
        return false;
      }
      return true;
    },
    /**
     * param:
     * return:
     * exception:
     * description : Confirm when saving - Save posts after uploading files / images
     */
    saveConfirm() {
      if (this.validatePost()) {
        SDLUtil.confirm({
          title: 'sdl.common.label.save',
          msg: 'sdl.common.message.doSave',
          okLabel: 'sdl.common.label.confirm',
          cancelLabel: 'sdl.common.label.cancel',
          onOkEvt: () => {
            SDLUtil.showLoadingBar(true, { msg: 'sdl.common.message.uploading' });
            if (this.boardInfo.fileAttachUsed) this.$refs.fileUploader.onUpload();
            else if (!this.boardInfo.fileAttachUsed && this.boardInfo.imageAttachUsed) this.$refs.imageUploader.onUpload();
            else this.savePost();
          },
          onCancelEvt: () => console.log('cancel'),
        });
      }
    },
    /**
     * param:
     * return:
     * exception:
     * description : Save posts
     */
    savePost() {
      // Apply board information properties
      this.post.noticeLabelUsed = this.boardInfo.noticeLabelUsed;
      SDLUtil.showLoadingBar(true);
      if (!_.eq(this.mode, 'edit')) {
        // registration
        axios
          .post(`${SDLUtil.API_URL}/boards/${this.boardId}/posts`, this.post)
          .then(({ data }) => {
            this.postId = data;
            SDLUtil.showLoadingBar(false);
            this.moveViewPage();
          })
          .catch(err => {
            SDLUtil.showLoadingBar(false);
            SDLUtil.errorAlert(err);
          });
      } else {
        // modification
        axios
          .put(`${SDLUtil.API_URL}/boards/${this.boardId}/posts/${this.postId}`, this.post)
          .then(() => {
            SDLUtil.showLoadingBar(false);
            this.moveViewPage();
          })
          .catch(err => {
            SDLUtil.showLoadingBar(false);
            SDLUtil.errorAlert(err);
          });
      }
    },
    /**
     * param:
     * return:
     * exception:
     * description : Cancel posting
     */
    cancelPost() {
      SDLUtil.confirm({
        msg: 'sdl.common.message.doCancel',
        title: 'sdl.common.label.save',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => (_.eq(this.mode, 'regist') ? this.goBackToList() : this.moveViewPage()),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param:
     * return:
     * exception:
     * description : Move to Detail Page
     */
    moveViewPage() {
      this.$router.push(`${this.$CONTEXT}/board/${this.boardId}/${this.roleType}/view/${this.postId}/default`);
    },
    /**
     * param:
     * return:
     * exception:
     * description : Move to List Page
     */
    moveListPage() {
      this.$router.push(`${this.$CONTEXT}/board/${this.boardId}/${this.roleType}/list/post`);
    },
  },
  mounted() {
    this.$nextTick(() => {
      console.info('initialize Board Edit Page');
      this.init();
    });
  },
};
</script>

<style scoped></style>
