<template>
    <div class="card">
      <div class="card-body">
        <div>
          <h2 class="card-title">결재 요청</h2>
          <div class="search-wrap mb20">
              <select name="yearPicker" id="yearPicker" class="form-select sm" v-model="searchParams.year" @change="handlePageChange(1)">
                <option value="">연도 전체</option>
                <option v-for="year in yearOptions" :key="year" :value="year">{{ year }}년</option>
              </select>
              <select name="monthPicker" id="monthPicker" class="form-select sm" v-model="searchParams.month" @change="handlePageChange(1)">
                <option value="">월 전체</option>
                <option v-for="month in monthOptions" :key="month" :value="month">{{ month }}월</option>
              </select>
              <select name="sanctnIemPicker" id="sanctnIemPicker" class="form-select sm" v-model="searchParams.sanctnIem" @change="handlePageChange(1)">
                <option value="">전체</option>
                <option v-for="(item, idx) of approvalTypeOptions" :key="idx" :value="item.code">{{ item.codeNm }}</option>
              </select>
          </div>
          <div class="tbl-wrap">
            <table class="tbl data common-radius">
              <colgroup>
                <col style="width: 13.33%;">
                <col style="width: 13.33%;">
                <col style="width: 13.33%;">
                <col style="width: 30%;">
                <col style="width: 16.66%;">
                <col style="width: 13.33%;">
              </colgroup>
              <thead>
                <tr>
                  <th style="border-radius: 1rem 0 0 0;">구분</th>
                  <th>결재구분</th>
                  <th>신청자</th>
                  <th>기간</th>
                  <th>신청일</th>
                  <th style="border-radius: 0 1rem 0 0;">상태</th>
                </tr>
              </thead>
              <tbody>
                <template v-if="approvalRequestList.length > 0">
                  <tr v-for="(item, idx) of approvalRequestList" :key="idx" @click="handleDetailNavigation(item.sanctnMbyId)">
                    <td>{{ item.sanctnIemNm }}</td>
                    <td>{{ item.sanctnSeNm }}</td>
                    <td>{{ item.registerNm }}</td>
                    <td>{{ $formattedDates(item) }}</td>
                    <td>{{ item.rgsde }}</td>
                    <td>{{ item.confmAtNm }}</td>
                  </tr>
                </template>
                <tr v-else>
                  <td colspan="6">게시물이 존재하지 않습니다.</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <div class="d-flex justify-between align-center">
      <div></div>
      <Pagination :search="searchParams" @onChange="handlePageChange" />
      <button class="btn sm primary" @click="isOptionsModalVisible = true">신청하기</button>
    </div>
    <Modal :showModal="isOptionsModalVisible" :className="'small-modal'">
      <template #header>
        <div class="modal-title">
          <p>신청 종류 선택</p>
        </div>
        <button class="btn-close" @click="isOptionsModalVisible = false"></button>
      </template>
      <div class="d-flex justify-between align-center mb20">
        <button class="btn lg" @click="handleRegistrationNavigation('휴가')">휴가신청</button>
        <button class="btn lg" @click="handleRegistrationNavigation('출장')">출장신청</button>
      </div>
      <!-- <template #footer>
        <button class="btn sm primary" @click="isOptionsModalVisible = false">닫기</button>
      </template> -->
    </Modal>
</template>
<script>
import Pagination from '../../../component/Pagination.vue';
import Modal from '../../../component/modal/Modal.vue';
// API
import { findMyApprovalRequestsProc } from '../../../../resources/api/sanctns';

export default {
  components: {
    Modal,
    Pagination,
  },

  data() {
    return {
      photoicon: "/client/resources/img/photo_icon.png",
      isOptionsModalVisible: false,

      yearOptions: [],
      monthOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],

      approvalTypeOptions: [],

      approvalRequestList: [],
      searchParams: {
        year: '',
        month: '',
        sanctnIem: '',
        currentUserId: this.$store.state.userInfo.userId, // 변경불가 (고정값)
      },
    };
  },

  async created() {
    this.generateYearOptions();
    this.approvalTypeOptions = await this.$sanctnIemCodes(); // 휴가 및 출장 구분 코드 조회
  },

  mounted() {
    this.fetchApprovalRequestList(); // 목록 조회
  },

  methods: {
    generateYearOptions() {
      const startYear = 2020;
      const currentYear = new Date().getFullYear();

      for (let year = currentYear; year >= startYear; year--) {
        this.yearOptions.push(year);
      }
    },

    // 목록 조회
    async fetchApprovalRequestList() {
      const vm = this;
      try {
        const response = await findMyApprovalRequestsProc(vm.searchParams);
        const result = response.data.data;

        this.approvalRequestList = result.lists;
        this.searchParams = result.search;
      } catch (error) {
        this.handleError(error);
      };
    },

    // 페이지 변경
    handlePageChange(currentPage) {
      this.searchParams.currentPage = Number(currentPage);
      this.$nextTick(() => {
        this.fetchApprovalRequestList();
      });
    },

    // 상세 페이지 이동
    handleDetailNavigation(id) {
      const approvalType = id.split('_')[0];

      if (approvalType === "VCATN") {
        this.$router.push({ name: 'VcatnView', query: { id } });
      } if (approvalType === "BSRP") {
        this.$router.push({ name: 'ChuljangDetailAll', query: { id } });
      }
    },

    // 등록 페이지 이동
    handleRegistrationNavigation(type) {
      if (type === "휴가") {
        this.$router.push({ name: 'VcatnInsert' });
      } else if (type === "출장") {
        this.$router.push({ name: 'ChuljangInsert' });
      }
    },

    // 에러 처리
    handleError(error) {
      const message = error.response?.data?.message || "에러가 발생했습니다.";
      alert(message);
      console.error(error.message);
    },
  },
};
</script>