<template>
  <div class="datatable-wrapper datatable-loading no-footer sortable searchable fixed-columns">


    <div class="datatable-container">
      <div class="d-flex justify-content-end gap-1">
              <button
                type="button"
                class="btn sm btn-outline-primary"
                @click="requestApproval"
              >
                승인요청
              </button>
              <button
                type="button"
                class="btn sm btn-outline-secondary"
                @click="registerLeave"
              >
                등록
              </button>
              <button
                type="button"
                class="btn sm btn-outline-success"
                @click="saveChanges"
              >
                저장
              </button>
              <button
                type="button"
                class="btn sm btn-outline-danger"
                @click="deletePending"
              >
                삭제
              </button>
            </div>
      <table class="table datatable datatable-table">
        <!-- 동적으로 <th> 생성 -->
        <thead>
          <tr>
            <th v-for="(header, index) in headers" :key="index">
              {{ header.label }}
            </th>
          </tr>
        </thead>
        <!-- 동적으로 <td> 생성 -->
        <tbody>
          <tr v-for="(row, index) in tableData" :key="index">
          <td v-for="(header, colIndex) in tableHeaders" :key="colIndex">
            <!-- 입력 필드를 추가할 때 -->
            <template v-if="isEditing && newRow === row">
              <input v-model="row[header.key]" type="text" :placeholder="header.label" />
            </template>
            <!-- 수정 전에는 그냥 값 표시 -->
            <template v-else>
              {{ row[header.key] }}
            </template>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <div class="datatable-bottom justify-content-center pagination">

      <nav class="datatable-pagination">
        <ul class="datatable-pagination-list">
          <li :class="{ 'datatable-disabled': currentPage === 1 }" @click="changePage(currentPage - 1)">
            <button class="datatable-pagination-list-item-link">‹</button>
          </li>
          <li v-for="page in totalPages" :key="page" :class="{ 'datatable-active': currentPage === page }">
            <button class="datatable-pagination-list-item-link" @click="changePage(page)">
              {{ page }}
            </button>
          </li>
          <li :class="{ 'datatable-disabled': currentPage === totalPages }" @click="changePage(currentPage + 1)">
            <button class="datatable-pagination-list-item-link">›</button>
          </li>
        </ul>
      </nav>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isEditing: false,  // 새 행을 추가하는 동안 편집 모드 활성화 여부
      newRow: null, 
     tableHeaders: [
        { label: "No", key: "no" },
        { label: "", key: "check" },
        { label: "구분", key: "Se" },
        { label: "시작일자", key: "startDate" },
        { label: "시작일자", key: "endDate" },
        { label: "사용일", key: "count" },
        { label: "사유", key: "prvonsh" },
        { label: "승인여부", key: "mngAprv" },
      ],
      tableData: [
        {
          no: 1,
          check: "",
          Se: "A",
          startDate: "2025-01-01",
          endDate: "2025-01-01",
          count: "1일",
          prvonsh: "개인사유",
          mngAprv: "승인",
        },
        {
          no: 2,
          check: "",
          Se: "B",
          startDate: "2025-02-01",
          endDate: "2025-02-01",
          count: "1일",
          prvonsh: "출장",
          mngAprv: "대기",
        },
      ],
      perPage: 10,
      currentPage: 1
    };
  },
 
  computed: {
    filteredRows() {
      if (!this.searchQuery) return this.rows;
      return this.rows.filter(row =>
        Object.values(row).some(val =>
          String(val).toLowerCase().includes(this.searchQuery.toLowerCase())
        )
      );
    },
    totalPages() {
      return Math.ceil(this.filteredRows.length / this.perPage);
    },
    startIndex() {
      return (this.currentPage - 1) * this.perPage;
    },
    endIndex() {
      return Math.min(this.currentPage * this.perPage, this.filteredRows.length);
    },
    paginatedRows() {
      return this.filteredRows.slice(this.startIndex, this.endIndex);
    }
  },
  methods: {
    formatDate(date) {
      const dateParts = date.split('/');
      return `${dateParts[0]}/${dateParts[1]}/${dateParts[2]}`;
    },
    updatePage() {
      this.currentPage = 1;
    },
    changePage(page) {
      if (page < 1 || page > this.totalPages) return;
      this.currentPage = page;
    },
    requestApproval() {
      // 승인 요청 처리 로직
      alert("승인 요청이 전송되었습니다.");
    },
    registerLeave() {
      // 등록 처리 로직
      const newRow = {
        no: this.tableData.length + 1,
        Se: '',
        startDate: '',
        endDate: '',
        count: '',
        prvonsh: '',
        mngAprv: '',
      };
      this.tableData.push(newRow);
      this.isEditing = true;
      this.newRow = newRow; 
    },
    saveChanges() {
      // 저장 처리 로직
      alert("변경 사항이 저장되었습니다.");
    },
    deletePending() {
  // 체크된 항목 중 승인되지 않은 데이터 필터링
  const checkedPending = this.tableData.filter(
    (item) => item.check === true && item.mngAprv !== "승인"
  );

  if (checkedPending.length > 0) {
    // 삭제되지 않을 항목: 승인된 항목 + 체크되지 않은 항목
    this.tableData = this.tableData.filter(
      (item) => item.check !== true || item.mngAprv === "승인"
    );
    alert("선택된 승인 전 상태의 데이터가 삭제되었습니다.");
  } else {
    alert("삭제할 승인 전 데이터가 없습니다.");
  }
},
  }
};
</script>

<style scoped>
/* Add your styles here */
</style>
