<template>
  <div
    :class="{
      content: true,
      'admin-style overflow-y': pageRole === 'adm',
      'w1400 pt50 pb50': pageRole === 'portal',
    }"
  >
    <div
      :class="{
        'admin-page-title point-font2 mb30': pageRole == 'adm',
        'page-title point-font mb30': pageRole == 'portal',
      }"
    >
      <p>{{ bbsMng.bbsNm }}</p>
    </div>
    <table class="form-table mb30">
      <colgroup>
        <col width="10%" />
        <col width="90%" />
      </colgroup>
      <tbody>
        <tr>
          <th
            colspan="4"
            :class="{
              'text-lf': true,
              'point-font2': pageRole == 'adm',
              'point-font': pageRole == 'portal',
            }"
          >
            <span>내용</span>
          </th>
        </tr>
        <tr>
          <td v-if="ansPageId != null" colspan="4">
            <textarea
              name=""
              id=""
              class="content"
              placeholder="답변을 입력하세요."
              v-model="bbsCn.ansCn"
            ></textarea>
          </td>
          <td v-else colspan="4">
            <textarea
              name=""
              id=""
              class="content"
              placeholder="내용을 입력하세요."
              v-model="bbsCn.bbsCn"
            ></textarea>
          </td>
        </tr>
        <tr v-if="bbsMng.atchFileUseYn === 'Y'" class="border-top">
          <th
            :class="{
              'text-lf': true,
              'point-font2': pageRole == 'adm',
              'point-font': pageRole == 'portal',
            }"
          >
            첨부파일
          </th>
          <td colspan="3">
            <div class="flex align-center">
              <div class="gd-10">
                <div>
                  <input
                    v-if="fileList.length < 1"
                    class="upload-name full-input"
                    placeholder="첨부파일이 없습니다."
                    disabled
                  />
                  <ul v-else class="pl10 pr10 border radius align-center">
                    <li
                      v-for="(file, idx) in fileList"
                      :key="idx"
                      class="file-wrap"
                    >
                      <p v-if="file['fileId'] != null">
                        {{ file["fileNm"] }}.{{ file["extnNm"] }}
                        <button
                          class="del-btn"
                          @click="fnFileDelete(file, idx)"
                        >
                          X
                        </button>
                      </p>
                      <p v-else>
                        {{ file.name }}
                        <button
                          class="del-btn"
                          @click="fnFileDelete(file, idx)"
                        >
                          X
                        </button>
                      </p>
                    </li>
                  </ul>
                </div>
              </div>
              <div class="gd-2">
                <label for="file" class="large-btn green-border-btn text-ct"
                  >파일찾기</label
                >
                <input
                  type="file"
                  id="file"
                  ref="file"
                  @change="fnFileInsert"
                  multiple
                />
              </div>
            </div>
          </td>
        </tr>
        <tr v-if="bbsMng.ntcUseYn === 'Y'" class="border-top">
          <th
            :class="{
              'text-lf': true,
              'point-font2': pageRole == 'adm',
              'point-font': pageRole == 'portal',
            }"
          >
            공지글
          </th>
          <td colspan="3">
            <div class="flex align-center no-gutters">
              <div class="gd-4">
                <input
                  type="radio"
                  name="notice"
                  id="notice-y"
                  class="mr5"
                  value="Y"
                  v-model="bbsCn.ntcPstYn"
                />
                <label for="notice-y">사용</label>
              </div>
              <div class="gd-4">
                <input
                  type="radio"
                  name="notice"
                  id="notice-n"
                  class="mr5"
                  value="N"
                  v-model="bbsCn.ntcPstYn"
                />
                <label for="notice-n">미사용</label>
              </div>
            </div>
          </td>
        </tr>
        <tr v-if="bbsCn.ntcPstYn === 'Y'" class="border-top">
          <th
            :class="{
              'text-lf': true,
              'point-font2': pageRole == 'adm',
              'point-font': pageRole == 'portal',
            }"
          >
            공지글 게시기간
          </th>
          <td colspan="3">
            <div class="flex align-center no-gutters">
              <div class="gd-4">
                <input
                  type="date"
                  class="full-input ml0"
                  v-model="bbsCn.ntcBgngDt"
                  @change="checkDateValidity('ntcBgngDt', $event)"
                />
              </div>
              <div class="pd10">-</div>
              <div class="gd-4">
                <input
                  type="date"
                  class="full-input ml0"
                  v-model="bbsCn.ntcEndDt"
                  @change="checkDateValidity('ntcEndDt', $event)"
                />
              </div>
            </div>
          </td>
        </tr>
        <tr v-if="bbsMng.prvtPstUseYn === 'Y'" class="border-top">
          <th
            :class="{
              'text-lf': true,
              'point-font2': pageRole == 'adm',
              'point-font': pageRole == 'portal',
            }"
          >
            비밀글
          </th>
          <td colspan="3">
            <div class="flex align-center no-gutters">
              <div class="gd-4">
                <input
                  type="radio"
                  name="private"
                  id="private-y"
                  class="mr5"
                  value="Y"
                  v-model="bbsCn.prvtPstYn"
                />
                <label for="private-y">사용</label>
              </div>
              <div class="gd-4">
                <input
                  type="radio"
                  name="private"
                  id="private-n"
                  class="mr5"
                  value="N"
                  v-model="bbsCn.prvtPstYn"
                />
                <label for="private-n">미사용</label>
              </div>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="flex justify-end align-center no-gutters">
      <div class="gd-1 mr10">
        <button
          v-if="ansPageId == null"
          :class="{
            'large-btn': true,
            'blue-btn': pageRole == 'adm',
            'green-btn': pageRole == 'portal',
          }"
          @click="fnInsert"
        >
          {{ bbsCn.bbsId == null ? "등록" : "수정" }}
        </button>
        <button
          v-else
          class="large-btn blue-btn"
          :class="{
            'large-btn': true,
            'blue-btn': pageRole == 'adm',
            'green-btn': pageRole == 'portal',
          }"
          @click="fnAnsInsert"
        >
          {{ bbsCn.ansStts == "N" ? "답변 등록" : "답변 수정" }}
        </button>
      </div>
      <div class="gd-1">
        <button class="large-btn gray-btn" @click="fnCancel">취소</button>
      </div>
    </div>
  </div>
</template>

<script>
import { mdiClose } from "@mdi/js";
import { findByBbsCn, fnqSave } from "../../../../../../resources/api/bbsCn.js";
import queryParams from "../../../../../../resources/js/queryParams";
import defaultAxios from "../../../../../../resources/js/defaultAxios";

export default {
  mixins: [queryParams],
  data() {
    return {
      iconPath: mdiClose,
      pageRole: this.$store.state.userType,
      path: this.$store.state.path,
      pageAuth: this.$store.state.pageAuth,
      bbsMngId: null,
      bbsCn: {},
      bbsMng: {},

      // 답변
      ansPageId: null,

      // 파일 업로드
      files: null,
      fileList: [],
      deleteFileList: [],

      //이미지 업로드
      imgFiles: null,
      imgFileList: [],
      deleteImgFileList: [],
    };
  },
  created() {
    this.fnBbsIdExtraction();
    this.fnSelectOne();
  },
  methods: {
    // 상세조회
    async fnSelectOne() {
      let bbsId = null;
      if (this.$route.query.ansPageId != null) {
        bbsId = this.$route.query.ansPageId;
      } else {
        bbsId = this.$route.query.pageId;
      }
      try {
        const params = {
          bbsId: bbsId,
          bbsMngId: this.bbsMngId,
        };
        const res = await findByBbsCn(params);
        if (res.status == 200) {
          this.bbsCn = res.data.data.bbsCn;
          this.bbsMng = res.data.data.bbsMng;
          this.fileList = res.data.data.fileList;

          if (this.$route.query.ansPageId != null) {
            this.ansPageId = this.$route.query.ansPageId;
          }
        }
      } catch (error) {
        alert("에러가 발생했습니다.\n시스템관리자에게 문의하세요.");
      }
    },
    /*
        // 첨부파일 등록
        fnFileInsert() {
            // files 개수 만큼 반복해서 type, size 체크
            this.files = this.$refs.file.files;
            for (let i = 0; i < this.files.length; i++) {
                const file = this.files[i];
                const extnNm = file.name.split('.').pop();
                if(this.bbsMng.fileExtnNmList.length >= 1){
                    if (!this.bbsMng.fileExtnNmList.includes(extnNm)) {
                        alert('첨부파일 확장자를 확인해주세요.');
                        return;
                    }
                }
                if(this.bbsMng.fileSzLmt != 0 && this.bbsMng.fileSzLmt != null) {
                    if (file.size > this.bbsMng.fileSzLmt) {
                        alert('첨부파일 용량을 확인해주세요.');
                        return;
                    }
                }

            }

            this.fileList = [...this.fileList, ...Array.from(this.files)];
        },
        // 첨부파일 삭제
        fnFileDelete(file, index) {
            if (file["fileId"] != null) {
                this.deleteFileList.push(file);
            }
            this.fileList.splice(index, 1);
        },
        */
    fnInsert() {
      if (this.ansPageId != null) {
        // 질의형 게시판 답변 등록 수정
        if (this.bbsCn.ansStts == null || this.bbsCn.ansStts == "") {
          this.fnAnsInsert();
        } else {
          this.fnAnsUpdate();
        }
      } else {
        // 질의형 게시판 등록/ 수정
        if (this.bbsCn.bbsId == null || this.bbsCn.bbsId == 0) {
          this.fnSave();
        } else {
          this.fnUpdate();
        }
      }
    },
    // 등록
    async fnSave() {
      // 내용 null검사
      if (this.bbsCn.bbsCn === null || this.bbsCn.bbsCn.trim() == "") {
        alert("내용을 입력하세요.");
        return;
      }
      // 줄바꿈 처리 적용
      // 답변 상태 추가
      this.bbsCn.ansStts = "N";
      // 폼데이터 생성
      this.bbsCn.bbsMngId = this.bbsMngId;
      var formData = new FormData();
      const paramsToBlob = new Blob([JSON.stringify(this.bbsCn)], {
        type: "application/json; charset=UTF-8",
      });
      formData.append("bbsCn", paramsToBlob);
      for (const file of this.fileList) {
        formData.append("multipartFileList", file);
      }
      for (const imgFile of this.imgFileList) {
        formData.append("multipartImgList", imgFile);
      }
      // axios 호출
      await defaultAxios({
        url: "/sys/bbsCn/saveBbsCn.file",
        method: "post",
        headers: {
          "Content-Type": "multipart/form-data; charset=UTF-8",
          Authorization: this.$store.state.authorization,
        },
        data: formData,
      })
        .then((response) => {
          const bbsId = response.data.data.bbsId;
          alert("게시글이 등록되었습니다.");
          this.$router.push({
            path: this.path + "/list.page",
          });
        })
        .catch((error) => {
          const message = error.response.data.message;
          alert(message);
        });
    },
    // 수정
    async fnUpdate() {
      // 내용 null검사
      if (this.bbsCn.bbsCn.trim() == "" || this.bbsCn.bbsCn === null) {
        alert("내용을 입력하세요.");
        return;
      }
      // 폼데이터 생성
      this.bbsCn.bbsMngId = this.bbsMngId;
      var formData = new FormData();
      const paramsToBlob = new Blob([JSON.stringify(this.bbsCn)], {
        type: "application/json; charset=UTF-8",
      });
      formData.append("params", paramsToBlob);
      const deleteFileListToBlob = new Blob(
        [JSON.stringify(this.deleteFileList)],
        {
          type: "application/json; charset=UTF-8",
        }
      );
      formData.append("deleteFileList", deleteFileListToBlob);
      // 추가 첨부파일
      for (const file of this.fileList) {
        if (file["fileId"] == null) {
          formData.append("multipartFileList", file);
        }
      }
      // 이미지 파일
      const deleteImgFileListToBlob = new Blob(
        [JSON.stringify(this.deleteImgFileList)],
        {
          type: "application/json; charset=UTF-8",
        }
      );
      formData.append("deleteImgFileList", deleteImgFileListToBlob);
      for (const imgFile of this.imgFileList) {
        formData.append("multipartImgList", imgFile);
      }
      // axios 호출
      defaultAxios({
        url: "/sys/bbsCn/updateBbsCn.file",
        method: "post",
        headers: {
          "Content-Type": "multipart/form-data; charset=UTF-8",
          Authorization: this.$store.state.authorization,
        },
        data: formData,
      })
        .then((response) => {
          const bbsId = response.data.data;
          this.$router.push({
            path: this.path + "/list.page",
          });
        })
        .catch((error) => {
          // console.log(error)
          const message = error.response.data.message;
          alert(message);
        });
    },
    // 질의 답변 등록
    async fnAnsInsert() {
      this.bbsCn.bbsId = this.ansPageId;
      this.bbsCn.ansStts = "Y";
      try {
        const res = await fnqSave(this.bbsCn);
        if (res.status == 200) {
          alert("답변이 등록되었습니다.");
          this.$router.push({
            path: this.path + "/list.page",
          });
        }
      } catch (error) {
        const message = error.response.data.message;
        alert(message);
      }
    },
    // 질의 답변 수정
    async fnAnsUpdate() {
      try {
        const res = await fnqUpdate(this.bbsCn);
        if (res.status == 200) {
          alert("답변이 수정되었습니다.");
          this.$router.push({
            path: this.path + "/list.page",
          });
        }
      } catch (error) {
        const message = error.response.data.message;
        alert(message);
      }
    },

    // 취소 버튼 동작
    fnCancel() {
      if (!confirm("등록을 취소하시겠습니까?")) {
        return;
      }

      this.$router.push({
        path: this.path + "/list.page",
      });
    },
  },
  watch: {},
  computed: {},
  components: {},
  mounted() {},
};
</script>
