<template>
  <div class="col-lg-12">
    <div class="card">
      <div class="card-body">
        <h2 class="card-title">출장 현황</h2>
        <div class="sch-form-wrap">
          <div class="input-group">
            <select class="form-select" v-model="searchParams.year" @change="handleSearchChange">
              <option value="">연도 전체</option>
              <option v-for="year in yearOptions" :key="year" :value="year">{{ year }}년</option>
            </select>
            <select class="form-select" v-model="searchParams.month" @change="handleSearchChange">
              <option value="">월 전체</option>
              <option v-for="month in monthOptions" :key="month" :value="month">{{ month }}월</option>
            </select>
          </div>
        </div>
        <div class="tbl-wrap">
          <table id="myTable" class="tbl data">
            <thead>
              <tr>
                <th>출장구분</th>
                <th>출장지</th>
                <th>목적</th>
                <th>출장기간</th>
                <th>품의서 상태</th>
                <th>복명서 등록 여부</th>
                <th>복명서 상태</th>
              </tr>
            </thead>
            <tbody>
              <template v-if="hasBusinessTrips">
                <tr v-for="(item, idx) in businessTripList" :key="`${item.bsrpId}-${idx}`" @click="handleItemClick(item.bsrpId)">
                  <td>{{ item.bsrpSeNm }}</td>
                  <td>{{ item.bsrpPlace }}</td>
                  <td>{{ item.bsrpPurps }}</td>
                  <td>{{ $formattedDates(item) }}</td>
                  <td>{{ item.cnsulConfmAtNm }}</td>
                  <td>{{ getReportRegistrationStatus(item.hasRport) }}</td>
                  <td>{{ getReportStatus(item) }}</td>
                </tr>
              </template>
              <tr v-else>
                <td colspan="7">게시물이 존재하지 않습니다.</td>
              </tr>
            </tbody>
          </table>
        </div>
        <Pagination :search="searchParams" @onChange="handlePageChange" />
      </div>
    </div>
  </div>
</template>
<script>
// API
import { findBsrpsProc } from '../../../../resources/api/bsrp';

export default {
  name: 'BsrpList',

  // 상수 - 라우트 맵
  ROUTE_MAP: {
    'list': { name: 'BsrpListPage' },
    'view': { name: 'BsrpViewPage', query: { id: null } },
    'bsrpInsert': { name: 'BsrpInsertPage', query: {} },
    'bsrpReapply': { name: 'BsrpInsertPage', query: { type: 'reapply' } },
    'bsrpRportInsert': { name: 'BsrpRportInsertPage', query: {} },
    'bsrpRportReapply': { name: 'BsrpRportInsertPage', query: { type: 'reapply' } },
  },

  data() {
    return {
      searchParams: {
        year: '',
        month: '',
        currentUserId: this.$store.state.userInfo.userId,
      },
      businessTripList: [],
    };
  },

  computed: {
    // 연도 옵션
    yearOptions() {
      const startYear = 2020;
      const currentYear = new Date().getFullYear();
      const years = [];

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

    // 월 옵션
    monthOptions() {
      return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
    },

    // 출장 목록 유무
    hasBusinessTrips() {
      return this.businessTripList.length > 0;
    },
  },

  async mounted() {
    await this.fetchBusinessTripList(); // 출장 목록 조회
  },

  methods: {
    // 출장 목록 조회
    async fetchBusinessTripList() {
      try {
        const response = await findBsrpsProc(this.searchParams);
        const result = response.data.data;

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

    // 검색 핸들러 (검색 시 현재 페이지를 1로 변경 후 조회)
    async handleSearchChange() {
      await this.handlePageChange(1);
    },

    // 페이지 변경 핸들러
    async handlePageChange(currentPage) {
      this.searchParams.currentPage = Number(currentPage);
      await this.$nextTick();
      await this.fetchBusinessTripList();
    },

    // 상세 페이지 이동 핸들러
    handleItemClick(id) {
      this.handleNavigation('view', id);
    },

    // 페이지 이동 핸들러
    handleNavigation(type, id) {
      const routeMap = {
        'list': { name: 'BsrpListPage' },
        'view': { name: 'BsrpViewPage', query: { id } },
        'bsrpInsert': { name: 'BsrpInsertPage', query: this.$isEmpty(id) ? {} : { id } },
        'bsrpReapply': { name: 'BsrpInsertPage', query: { id, type: 'reapply' } },
        'bsrpRportInsert': { name: 'BsrpRportInsertPage', query: this.$isEmpty(id) ? {} : { id } },
        'bsrpRportReapply': { name: 'BsrpRportInsertPage', query: { id, type: 'reapply' } },
      };

      const route = routeMap[type];
      if (route) {
        this.$router.push(route);
      } else {
        alert("올바르지 않은 경로입니다.");
        this.$router.push(routeMap['list']);
      }
    },

    // 에러 핸들러
    handleError(error) {
      const message = error.response?.data?.message || "에러가 발생했습니다.";
      alert(message);
    },

    // 등록 여부 유틸
    getReportRegistrationStatus(hasRport) {
      return hasRport ? '등록' : '미등록';
    },

    // 상태 유틸
    getReportStatus(item) {
      return item.hasRport ? item.rportConfmAtNm : '-';
    },
  },
};
</script>
<style scoped>
tr {
  cursor: pointer;
}
</style>