<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 name="" id="" class="form-select">
              <option :value="currentYear">{{ currentYear }}년</option>
              <option value="all">전체</option>
              <option v-for="year in remainingYears" :key="year" :value="year" v-if="year !== currentYear">
                {{ year }}년
              </option>
            </select>
          </div>
        </div>

        <!-- Table  -->
        <div class="tbl-wrap">
          <table id="myTable" class="tbl data">
            <!-- 동적으로 <th> 생성 -->
            <thead>
              <tr>
                <th>월 </th>
                <th>지급액</th>
                <th>공제액</th>
                <th>수령액</th>
                <th>지급일</th>
                <th>명세서 보기</th>
              </tr>
            </thead>
            <!-- 동적으로 <td> 생성 -->
            <tbody>
              <tr v-for="(item, index) in listData" :key="index">
                <td>{{ item.month }}</td>
                <td>{{ formatCurrency(item.payment) }}</td>
                <td>{{ formatCurrency(item.deduction) }}</td>
                <td>{{ formatCurrency(item.actual) }}</td>
                <td>{{ item.payDate }}</td>
                <td>
                  <button class="btn secondary xsm" @click="showPopup = true">보기</button>
                </td>
              </tr>
            </tbody>
          </table>
          <PaySlipPopup v-if="showPopup" @close="showPopup = false"/>
        </div>
        <div class="pagination">
          <ul>
            <!-- 왼쪽 화살표 (이전 페이지) -->
            <li class="arrow" :class="{ disabled: currentPage === 1 }" @click="changePage(currentPage - 1)">
              &lt;
            </li>

            <!-- 페이지 번호 -->
            <li v-for="page in totalPages" :key="page" :class="{ active: currentPage === page }"
              @click="changePage(page)">
              {{ page }}
            </li>

            <!-- 오른쪽 화살표 (다음 페이지) -->
            <li class="arrow" :class="{ disabled: currentPage === totalPages }" @click="changePage(currentPage + 1)">
              &gt;
            </li>
          </ul>
        </div>
        <!-- End Table -->
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import PaySlipPopup from '../../../component/Popup/PaySlipPopup.vue';
const currentYear = new Date().getFullYear();
export default {
  data() {
    return {
      showPopup: false,
      currentYear,
      selectedYear: currentYear,
      remainingYears: Array.from({ length: 10 }, (_, i) => currentYear - i),
      showOptions: false,
      currentPage: 1,
      totalPages: 3,
      photoicon: "/client/resources/img/photo_icon.png",
      // 데이터 초기화
      years: [2023, 2024, 2025], // 연도 목록
      months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], // 월 목록
      selectedYear: '',
      selectedMonth: '',
      listData: [
        {
          month: '3',
          payment: 3000000,
          deduction: 500000,
          actual: 2500000,
          payDate: '2024-12-25',
          slipUrl: '/slips/2024-12.pdf' // 예: 파일 경로나 상세 정보용 키
        },
        {
          month: '4',
          payment: 3100000,
          deduction: 510000,
          actual: 2590000,
          payDate: '2025-01-25',
          slipUrl: '/slips/2025-01.pdf'
        }
      ],
      filteredData: [],
    };
  },
  components: {
    PaySlipPopup
  },
  computed: {
  },
  methods: {
    formatCurrency(amount) {
      return new Intl.NumberFormat('ko-KR').format(amount) + ' 원';
    },
    viewPayslip(item) {
      // 예: 모달 열기, PDF 보기, 페이지 이동 등
      console.log('명세서 보기:', item);
      // window.open(item.slipUrl, '_blank'); // 외부 링크 열기 예시
    },
    changePage(page) {
      if (page < 1 || page > this.totalPages) return;
      this.currentPage = page;
      this.$emit('page-changed', page); // 필요 시 부모에 알림
    },
    async onClickSubmit() {
      // `useMutation` 훅을 사용하여 mutation 함수 가져오기
      const { mutate, onDone, onError } = useMutation(mygql);

      try {
        const result = await mutate();
        console.log(result);
      } catch (error) {
        console.error('Mutation error:', error);
      }
    },
    goToPage(type) {
      if (type === '명세서') {
        this.$router.push({ name: 'HyugaInsert' });
      } else if (type === '출장') {
        this.$router.push({ name: 'ChuljangDetail' });
      }
    },
    getStatusClass(status) {
      if (status === '승인') return 'status-approved';
      if (status === '대기') return 'status-pending';
      return '';
    },
    isPastPeriod(period) {
      // 예: '2025-05-01 ~ 2025-05-03' → 종료일 추출
      const endDateStr = period.split('~')[1]?.trim();
      if (!endDateStr) return false;

      const endDate = new Date(endDateStr);
      const today = new Date();

      // 현재 날짜보다 과거면 true
      return endDate < today;
    }
  },
  created() {
  },
  mounted() {


  },
};
</script>

<style scoped></style>
