<template>
  <div class="title-box flex justify-between mb40">
    <p class="title">공지 등록</p>
  </div>
  <div class="board-wrap">
    <form @submit.prevent="handleSubmit">
      <div class="flex align-center">
        <label for="title" class="title2">제목</label>
        <input type="text" id="title" class="data-wrap" v-model="title" />
      </div>
      <hr />
      <textarea name="" id="content" v-model="content"></textarea>
      <hr />
      <div class="flex align-center">
        <label for="file" class="title2">첨부파일</label>
        <input type="file" ref="fileInput" @change="handleFileUpload" />
      </div>
      <div class="flex justify-between mt50">
        <button title="글쓰기" class="new-btn" @click="goToPage('Board')">
          목록
        </button>
        <button title="글쓰기" class="new-btn">등록</button>
      </div>
    </form>
  </div>
</template>

<script>
import SvgIcon from "@jamescoyle/vue-icon";
import { mdiMagnify } from "@mdi/js";
import axios from "axios";

export default {
  data() {
    return {
      mdiMagnify: mdiMagnify,

      title: "",
      content: "",
      category: "Notice",
      sclsId: "",
      selectedFile: null,
    };
  },
  methods: {
    goToPage(page) {
      this.$router.push({ name: page });
    },

    handleFileUpload(e) {
      this.selectedFile = e.target.files[0];
      console.log(this.selectedFile);
    },

    created() {
      const vm = this;
      const sclsId = JSON.parse(sessionStorage.getItem("sclsId"));

      if (sclsId) {
        vm.sclsId = sclsId;
      }
      console.log(sclsId);
    },

    async handleSubmit() {
      const vm = this;
      try {
        // 파일 업로드
        const formData = new FormData();
        formData.append("files", this.selectedFile);

        const fileUploadResponse = await axios.post(
          "/file/upload.json",
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          }
        );

        // 업로드 후 파일 매니지 아이디 호출
        const fileMngId = fileUploadResponse.data.fileMngId;

        // 게시물 등록
        const newData = {
          bbsTtl: vm.title,
          bbsCls: vm.category,
          bbsCnt: vm.content,
          fileMngId: fileMngId,
          sclsId: vm.sclsId,
        };

        await axios.post("/board/insert.json", newData);

        alert("게시물 등록 성공");
      } catch (error) {
        console.error("게시물 등록 실패 ", error);
        alert("게시물 등록 실패");
      }
    },
  },
  watch: {},
  computed: {},
  components: {
    SvgIcon,
  },
  mounted() {
    console.log("Main2 mounted");
    this.created();
  },
};
</script>
