<template>
  <!-- <div class="wrap bg-wrap"> -->
  <div>
    <div class="dimmed modal52" @click="ModalClose()"></div>
    <div class="popup-wrap modal52">
      <!-- 공지사항 수정 -->
      <div class="popup modal52 popup_form" style="width: 70vw">
        <div class="pop-head">
          <h3 class="pop-tit">공지사항 수정</h3>
        </div>
        <form autocomplete="off">
          <table>
            <colgroup>
              <col width="10%" />
              <col width="40%" />
              <col width="10%" />
              <col width="10%" />
              <col width="10%" />
              <col width="10%" />
            </colgroup>
            <tbody>
              <tr>
                <th style="width: 10%">분류코드</th>
                <td>
                  <div class="select_box">
                    <select name="" id="right" v-model="ctgCd" style="min-width: 500px" ref="_ctgCd">
                      <option v-for="(option, i) in ctgCdOption" :value="option.code" v-bind:key="i">
                        {{ option.codeNm }}
                      </option>
                    </select>
                  </div>
                </td>
                <th style="width: 10%">긴급여부</th>
                <td>
                  <div class="select_box">
                    <select name="" id="right" v-model="emgYn" style="min-width: 150px" v-bind:disabled="ctgCd=='06'">
                      <option value="Y">긴급</option>
                      <option value="N">일반</option>
                    </select>
                  </div>
                </td>
                <th style="width: 10%">사용여부</th>
                <td>
                  <div class="select_box">
                    <select name="" id="right" v-model="useYn" style="min-width: 150px">
                      <option value="Y">사용</option>
                      <option value="N">사용 안함</option>
                    </select>
                  </div>
                </td>
              </tr>
              <tr v-show="ctgCd=='06'">
                <th style="width: 10%">노출기간</th>
                <td colspan="5">
                  <div class="input_box cal">
                    <div class="term">
                      <span class="custom_input icon_date">
                        <vuejs-datepicker
                          :language="ko"
                          :format="customFormatter"
                          :disabled-dates="disabledSDate"
                          v-model="startDate"
                          @selected="selectedStartDate(0)"
                          @closed="closeDate('start')"
                        ></vuejs-datepicker> </span
                      >~
                      <span class="custom_input icon_date">
                        <vuejs-datepicker
                          :language="ko"
                          :format="customFormatter"
                          :disabled-dates="disabledEDate"
                          v-model="endDate"
                          @selected="selectedEndDate(0)"
                          @closed="closeDate('end')"
                        ></vuejs-datepicker>
                      </span>
                    </div>
                  </div>
                </td>
              </tr>
              <tr>
                <th style="width: 10%">제목</th>
                <td colspan="5">
                  <input type="text" placeholder="제목을 입력하세요" v-model="title" ref="_title" />
                </td>
              </tr>
              <tr>
                <th style="width: 10%">내용</th>
                <td class="sender" colspan="5">
                  <vue-editor
                    id="editor"
                    useCustomImageHandler
                    @imageAdded="handleImageAdded"
                    v-model="ntSbst"
                    ref="_ntSbst"
                  >
                  </vue-editor>
                </td>
              </tr>
              <tr>
                <th style="width: 10%">첨부파일</th>
                <td class="sender" colspan="5">
                  <p class="file" style="width: 100%; margin-bottom: 15px">파일형식 : jpg, png, pdf, tiff, zip</p>
                  <div class="btn plus">
                    파일 추가
                    <input
                      type="file"
                      accept=".jpg,.png,.pdf,.tiff,.zip"
                      multiple="multiple"
                      ref="imageUploader"
                      @change="onFileChange"
                      class="form-control-file"
                      id="my-file"
                    />
                  </div>
                  <div class="img_list_wrap" v-if="updateFileList.length > 0" style="margin-top: 15px">
                    <div
                      class="img_list"
                      v-for="(item, index) in updateFileList"
                      :key="index"
                      style="margin-bottom: 5px"
                    >
                      <a
                        href="javascript:void(0);"
                        v-if="item.filePath"
                        @click="download(item.filePath, item.fileName, item.name)"
                        >{{ item.name }}</a
                      >
                      <p class="file_name" v-else>{{ item.name }} {{ item.fileNo ? `(${item.fileNo})` : '' }}</p>

                      <button type="button" class="btn_del" @click="popupHandleRemove(index, item.fileNo)">X</button>
                    </div>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </form>
        <div class="popup-btn2">
          <button class="btn-pcolor" @click="updateConfirm()">수정</button>
          <button class="btn-default" @click="ModalClose()">취소</button>
        </div>
      </div>
      <!-- <common-modal ref="commonModal"></common-modal> -->
      <validation-confirm-popup ref="ValidationConfirmPopup"></validation-confirm-popup>
    </div>
  </div>
</template>
<script>
import { utils_mixin, chkPattern2 } from '../service/mixins';
import homeMgtApi from '../service/homeMgtApi';
import ValidationConfirmPopup from './ValidationConfirmPopup.vue';
import { VueEditor } from 'vue2-editor';
import moment from 'moment';

export default {
  name: 'NoticeUpdatePop',
  mixins: [utils_mixin, chkPattern2],
  components: {
    VueEditor,
    ValidationConfirmPopup,
    vuejsDatepicker
  },
  data() {
    return {
      props: {},
      row: {},
      rsnType: [],
      tpType: [],
      ko: vdp_translation_ko.js,
      startDate: '',
      endDate: '',
      disabledSDate : {},
      disabledEDate : {},
      // 공지사항
      ntNo: '',
      title: '',
      ntSbst: '',
      emgYn: 'N',
      useYn: 'Y',
      ctgCd: 'null',
      fileNm: '',
      filePath: '',
      fileTitle: '',
      fileNo: '',
      updateFileList: [], // 업로드한 이미지 파일
      delFileList: [],
      ctgCdOption: [
        { code: 'null', codeNm: '분류코드를 선택하세요' },
        { code: '01', codeNm: '서비스' },
        { code: '02', codeNm: '개발/작업' },
        { code: '03', codeNm: '정책/약관' },
        { code: '04', codeNm: '오류/장애' },
        { code: '05', codeNm: '이벤트' },
        { code: '06', codeNm: '팝업공지' }
      ],
      // 공지사항
      LINE_FEED: 10, // '\n',
      maxByte: 2000,
    };
  },
  create() {
  },
  mounted() {
  },
  methods: {
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      var fd = new FormData();
      fd.append('files', file);

      homeMgtApi
        .getImageUrl(fd)
        .then((response) => {
          const url =
            '/api/v1/bo/homeMgt/preview/' +
            encodeURIComponent(response.data.data.replaceAll('\\', '/').replaceAll('/', '|')); // Get url from response
          Editor.insertEmbed(cursorLocation, 'image', url);
          resetUploader();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //모달 띄우기
    ModalOpen(props) {
      var dimmed = document.getElementsByClassName('modal52');
      for (var i = 0; i < dimmed.length; i++) {
        dimmed[i].style.display = 'block';
      }
      this.formReset();
      if (props) {
        this.ntNo = props.ntNo;
        this.title = props.title;
        this.ntSbst = props.ntSbst;
        this.emgYn = props.emgYn;
        this.useYn = props.useYn;
        this.ctgCd = props.ctgCd;
        this.fileNm = props.fileNm && props.fileNm.split(',');
        this.filePath = props.filePath && props.filePath.split(',');
        this.fileTitle = props.fileTitle && props.fileTitle.split(',');
        this.fileNo = props.fileNo && props.fileNo.split(',');
        this.fileCount = props.fileCount;
        //팝업 공지가 아닐경우 현재 날짜 셋팅
        console.log(props.ctgCd);
        console.log(props.ntStrtDt);
        console.log(props.ntEndDt);

        if(props.ctgCd != "06"){
          this.startDate = new Date();
          this.endDate = moment(new Date()).add(7, 'days').toDate();
        }else{
          this.startDate = moment(props.ntStrtDt).toDate();
          this.endDate = moment(props.ntEndDt).toDate();
        }
        this.closeDate('start');
        this.closeDate('end');
      }

      for (let i = 0; i < this.fileCount; i++) {
        this.updateFileList.push({
          src: '' + encodeURIComponent(this.filePath[i].replaceAll('\\', '/')) + '/' + this.fileNm[i],
          filePath: this.filePath[i],
          fileNo: this.fileNo[i],
          fileName: this.fileNm[i],
          name: this.fileTitle[i],
        });
      }
    },
    // 모달 끄기
    ModalClose() {
      this.formReset();

      var dimmed = document.getElementsByClassName('modal52');
      for (var i = 0; i < dimmed.length; i++) {
        dimmed[i].style.display = 'none';
      }
    },
    // 저장 후 부모창 호출
    toComplete() {
      this.$parent.$refs.table.reloadData();
      this.ModalClose();
    },
    doValidate() {
      if (this.isNull(this.ctgCd) || this.ctgCd === 'null') {
        this.row.title = '공지사항 등록';
        this.row.msg1 = '분류코드를 선택해 주세요.';
        this.row.focusTaget = '_ctgCd';
        this.$refs.ValidationConfirmPopup.alertModalOpen(this.row);
        return false;
      }

      if (this.isNull(this.title)) {
        this.row.title = '공지사항 등록';
        this.row.msg1 = '제목을 입력해 주세요.';
        this.row.focusTaget = '_title';
        this.$refs.ValidationConfirmPopup.alertModalOpen(this.row);
        return false;
      }
      if (this.isNull(this.ntSbst)) {
        this.row.title = '공지사항 등록';
        this.row.msg1 = '내용을 입력해 주세요.';
        this.row.focusTaget = '_ntSbst';
        this.$refs.ValidationConfirmPopup.alertModalOpen(this.row);
        return false;
      }
      this.row.ctgCd = this.ctgCd;
      return true;
    },
    formReset() {
      Object.assign(this.$data, this.$options.data());
    },
    updateConfirm() {
      if (this.doValidate()) {
        this.$refs.ValidationConfirmPopup.confirmUpdateOpen();
      }
    },
    // 바이트길이 구하기
    getByteLength: function (decimal) {
      return decimal >> 7 || this.LINE_FEED === decimal ? 2 : 1;
    },

    getByte: function (str) {
      return str
        .split('')
        .map((s) => s.charCodeAt(0))
        .reduce((prev, unicodeDecimalValue) => prev + this.getByteLength(unicodeDecimalValue), 0);
    },
    getLimitedByteText: function (inputText, maxByte) {
      const characters = inputText.split('');
      let validText = '';
      let totalByte = 0;

      for (let i = 0; i < characters.length; i += 1) {
        const character = characters[i];
        const decimal = character.charCodeAt(0);
        const byte = this.getByteLength(decimal); // 글자 한 개가 몇 바이트 길이인지 구해주기
        // 현재까지의 바이트 길이와 더해 최대 바이트 길이를 넘지 않으면
        if (totalByte + byte <= maxByte) {
          totalByte += byte; // 바이트 길이 값을 더해 현재까지의 총 바이트 길이 값을 구함
          validText += character; // 글자를 더해 현재까지의 총 문자열 값을 구함
        } else {
          // 최대 바이트 길이를 넘으면
          break; // for 루프 종료
        }
      }
      return validText;
    },

    memoLimitByte() {
      this.meno = this.getLimitedByteText(this.meno, this.maxByte);
    }, //END 바이트길이 구하기

    updateNotice() {
      const fd = new FormData();
      let legacyFiles = [];
      for (let i = 0; i < this.updateFileList.length; i++) {
        if (this.updateFileList[i].fileName) {
          legacyFiles.push(this.updateFileList[i].fileName);
        } else {
          fd.append('files', this.updateFileList[i]);
        }
      }

      const params = {
        ntNo: this.ntNo,
        title: this.title,
        ntSbst: this.ntSbst,
        emgYn: this.emgYn,
        useYn: this.useYn,
        ntStrtDt: moment(this.startDate).format('YYYYMMDD'),
        ntEndDt: moment(this.endDate).format('YYYYMMDD'),
        ctgCd: this.ctgCd,
        chgId: this.$store.getters['login/userId'],
        legacyFiles: legacyFiles.join(),
        delFileNo: this.delFileList.join(),
      };

      fd.append('key', new Blob([JSON.stringify(params)], { type: 'application/json' }));

      homeMgtApi.updateNotice(fd).then((response) => {
        if (response.data.retCode == '0000') {
          this.row.title = '공지사항 수정';
          this.row.msg1 = '수정이 완료되었습니다.';
          this.row.type = 'update';
          this.toComplete();
        } else {
          this.row.title = '공지사항 수정 실패';
          this.row.msg1 = response.retMsg;
          this.row.type = '';
          this.$refs.ValidationConfirmPopup.alertModalOpen(this.row);
        }
      });
    },

    checkFocus() {
      if (this.row.focusTaget === '_title') {
        this.$refs._title.focus();
      } else if (this.row.focusTaget === '_ntSbst') {
        //this.$refs._ntSbst.focus();
      } else if (this.row.focusTaget === '_ctgCd') {
        this.$refs._ctgCd.focus();
      }
    },
    /////////////////////////////////// 파일 첨부 ////////////////////////////////////////
    onFileChange(event) {
      const files = event.target.files || event.dataTransfer.files;
      if (!files.length) return;
      this.addFiles(files);
    },
    async addFiles(files) {
      for (let i = 0; i < files.length; i++) {
        const src = await this.readFiles(files[i]);
        files[i].src = src;
        this.updateFileList.push(files[i]);
      }
      console.log(this.updateFileList);
      this.$refs.imageUploader.value = ''; // 이미지 중복 가능하도록 input 초기화
    },
    // FileReader를 통해 파일을 읽어 thumbnail 영역의 src 값으로 셋팅
    async readFiles(files) {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = async (e) => {
          resolve(e.target.result);
        };
        reader.readAsDataURL(files);
      });
    },
    getImageSize(src) {
      const img = new Image();
      let _width = 0;
      let _height = 0;
      img.src = src;

      img.onload = function () {
        _width = img.width;
        _height = img.height;
        if (_width >= 1500 || _height >= 1440) {
          return false;
        } else {
          return true;
        }
      };
    },
    popupHandleRemove(index, fileNo) {
      this.delFileList.push(fileNo);
      this.updateFileList.splice(index, 1);
    },
    download(filePath, fileName, fileTitle) {
      this.row = {};
      this.row.fileTitle = fileTitle;
      this.row.filePath = filePath;
      this.row.fileNm = fileName;
      homeMgtApi.fileDownload(this.row);
    },
    setPeriodDay(day) {
      this.periodDay = day;
      this.startDate = new Date();
      this.endDate = moment(new Date()).add(7, 'days').toDate();
      this.closeDate('start');
      this.closeDate('end');
    },
    selectedStartDate(day) {
      if (day != undefined && day != null) {
        this.periodDay = day;
      }
      if (this.startDate > this.endDate) {
        this.startDate = this.endDate;
      }
    },
    selectedEndDate(day) {
      if (day != undefined && day != null) {
        this.periodDay = day;
      }
    },
    closeDate(type) {
      if (type != undefined && type != null) {
        if (type == 'start') {
          this.disabledSDate = { to: new Date(), from: this.endDate };
          this.disabledEDate = { to: this.startDate};
        } else if (type == 'end') {
          this.disabledSDate = { to: new Date(), from: this.endDate };
          this.disabledEDate = { to: this.startDate };
        }
      }
    },
    customFormatter: function (date) {
        return moment(date).format('YYYY-MM-DD');
    },
  },
};
</script>

<style scoped>
.popup-btn-wrap {
  width: 500px;
  margin: auto;
  padding: 100px 0;
}

.popup-btn-wrap button {
  width: 100%;
  margin-bottom: 10px;
  height: 50px;
  border-radius: 5px;
  box-shadow: none;
  border: 1px solid #000;
}

.popup-btn-wrap button:hover {
  background: #000;
  color: #fff;
}

.btn.plus {
  font-family: SpoqaHanSansNeo;
  font-weight: 400;
  font-size: 16px;
  color: #fff;
  background-color: #35354f;
  border-radius: 4px;
  text-align: center;
  min-width: 89px;
  height: 36px;
  padding: 10px 20px;
  letter-spacing: -0.025em;
  border: none;
  position: relative;
  line-height: 1;
  display: inline-block;
  box-sizing: border-box;
  transition: 0.3s;
}
.btn input {
  width: 100%;
  height: 100%;
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
  cursor: pointer;
  z-index: 1;
}
.file_name {
  display: inline-flex;
}
.btn_del {
  background: #e4e4e4;
  width: 15px;
  height: 15px;
  border-radius: 50%;
  border: none;
  font-size: 10px;
  margin: 0 0 0 5px;
}
</style>
