<template>
  <div class="title-box flex justify-between mb40">
    <p class="title">게시판</p>
    <select name="" id="">
      <option value="">A반</option>
    </select>
  </div>
  <div class="search-wrap flex justify-end mb20">
    <select v-model="selectedSearchOption" class="mr10 data-wrap">
      <option value="bbsTtl">제목</option>
      <option value="bbsCnt">내용</option>
      <option value="userNm">작성자</option>
      <option value="bbsCls">카테고리</option>
    </select>
    <input
      v-model="searchKeyword"
      type="text"
      placeholder="검색하세요."
      @keyup.enter="boardDataSearch"
    />
    <button type="button" @click="boardDataSearch()" title="게시글 검색">
      <img src="../../../resources/img/look_t.png" alt="" />
    </button>
  </div>
  <div class="table-wrap">
    <table>
      <thead>
        <td>No.</td>
        <td>제목</td>
        <td>카테고리</td>
        <td>작성자</td>
        <td>등록일</td>
      </thead>
      <tbody>
        <tr
          v-for="(item, index) in dataList"
          :key="item.id"
          :class="{ 'selected-row': selectedRow == item.dataList }"
          @click="[goToPage('noticeDetail'), selectBoardList(item)]"
        >
          <td>{{ totalBoard - index }}</td>
          <td>{{ item.bbsTtl }}</td>
          <td>{{ item.bbsCls }}</td>
          <td>{{ userNm }}</td>
          <td>{{ item.bbsTm }}</td>
        </tr>
      </tbody>
    </table>
    <article
      class="table-pagination flex justify-center align-center mb20 mt30"
      style="gap: 10px"
    >
      <button>
        <img
          src="../../../resources/img/btn27_90t_normal.png"
          alt=""
          @click="previousPage"
          :disabled="page === 1"
        />
      </button>
      <button class="selected-btn">{{ page }}</button>
      <button>
        <img
          src="../../../resources/img/btn28_90t_normal.png"
          alt=""
          @click="nextPage"
          :disabled="page === totalPages"
        />
      </button>
    </article>
    <div class="flex justify-end">
      <button
        type="button"
        title="글쓰기"
        class="new-btn"
        @click="goToPage('noticeInsert')"
      >
        글쓰기
      </button>
    </div>
  </div>
</template>

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

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

      // 게시글 정보
      dataList: [],
      totalBoard: null,
      selectedRow: "",

      // 페이징
      page: 1,
      pageSize: 8,
      totalPages: null,

      // 반 아이디 (추후 세션에서 받는걸로 수정)
      sclsId: "1",

      // 검색어
      searchKeyword: "",
      selectedSearchOption: "bbsTtl",
    };
  },
  methods: {
    goToPage(page) {
      this.$router.push({ name: page });
    },
    showConfirm(type) {
      let message = "";
      if (type === "cancel") {
        message = "삭제하시겠습니까?";
      } else if (type === "reset") {
        message = "초기화하시겠습니까?";
      } else if (type === "save") {
        message = "등록하시겠습니까?";
      }

      if (confirm(message)) {
        this.goBack();
      }
    },

    // 게시글 전체 조회
    boardList() {
      const vm = this;
      axios({
        url: "/board/findAll.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: { page: vm.page, pageSize: vm.pageSize, sclsId: vm.sclsId },
      })
        .then(function (res) {
          console.log("dataList - response : ", res.data);
          console.log(res.data.result[0].boardClass[0].board);

          vm.dataList = res.data.result[0].boardClass[0].board;
          vm.userNm = res.data.result[0].userNm;
          vm.userId = res.data.result[0].userId;
          vm.totalBoard = res.data.totalBoard;
          vm.totalPages = Math.ceil(vm.totalBoard / vm.pageSize);
        })
        .catch(function (error) {
          console.log("result - error : ", error);
          alert("비상 비상!");
        });
    },

    // 게시글 정보 세션에 저장
    selectBoardList(item) {
      sessionStorage.setItem("selectedBoardList", JSON.stringify(item));
    },

    // 반 아이디 세션에 저장
    setClassId() {
      sessionStorage.setItem("sclsId", JSON.stringify(this.sclsId));
    },

    // 게시글 검색
    boardDataSearch() {
      const vm = this;
      let searchPayload = {
        keyword: vm.searchKeyword,
        option: vm.selectedSearchOption,
        page: vm.page,
        pageSize: vm.pageSize,
        sclsId: vm.sclsId,
      };
      axios({
        url: "/board/search.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: searchPayload,
      })
        .then(function (res) {
          console.log("boardDataSearch - response : ", res.data);
          vm.dataList = res.data.result[0].boardClass[0].board;
          vm.userNm = res.data.result[0].userNm;
          vm.userId = res.data.result[0].userId;
          vm.totalBoard = res.data.totalBoard;
        })
        .catch(function (error) {
          console.log("dataSearch - error : ", error);
          alert("게시글이 존재하지 않습니다.");
        });
    },

    previousPage() {
      if (this.page > 1) {
        this.page -= 1;
        this.boardList();
      }
    },

    nextPage() {
      if (this.page < this.totalPages) {
        this.page += 1;
        this.boardList();
      }
    },
  },
  watch: {},
  computed: {},
  components: {
    SvgIcon,
  },
  mounted() {
    console.log("Main2 mounted");
    this.boardList();
    this.setClassId();
  },
};
</script>
