<template>
  <div class="col-lg-12">
    <div class="card">
      <div class="card-body">
        <h2 class="card-title">승인 대기 목록</h2>
        <div class="sch-form-wrap title-wrap">
          <h3><img :src="h3icon" alt="">승인 대기</h3>
          <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>
            <select name="" id="" class="form-select">
              <option :value="currentMonth">{{ currentMonth }}월</option>
              <option value="all">전체</option>
              <option v-for="month in remainingMonths" :key="month" :value="month" v-if="month !== currentMonth">
                {{ month }}월
              </option>
            </select>
            <div class="sch-input">
              <input type="text" class="form-control" placeholder="신청자명">
              <button class="ico-sch">
                <SearchOutlined />
              </button>
            </div>
          </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>
              </tr>
            </thead>
            <!-- 동적으로 <td> 생성 -->
            <tbody>
              <tr v-for="(item, index) in listData" :key="index" :class="{ 'expired': isPastPeriod(item.period) }" @click="goToPage(item)">
                <td>{{ item.type }}</td>
                <td>{{ item.approvalType }}</td>
                <td>{{ item.applicant }}</td>
                <td>{{ item.period }}</td>
                <td>{{ item.requestDate }}</td>
              </tr>
            </tbody>
          </table>

        </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>
        <div class="sch-form-wrap title-wrap">
          <h3><img :src="h3icon" alt="">승인 이력</h3>
          <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>
            <select name="" id="" class="form-select">
              <option :value="currentMonth">{{ currentMonth }}월</option>
              <option value="all">전체</option>
              <option v-for="month in remainingMonths" :key="month" :value="month" v-if="month !== currentMonth">
                {{ month }}월
              </option>
            </select>
            <select name="" id="" class="form-select">
              <option value="all">상태</option>
              <option value="">승인</option>
              <option value="">반려</option>
            </select>
            <div class="sch-input">
              <input type="text" class="form-control" placeholder="신청자명">
              <button class="ico-sch">
                <SearchOutlined />
              </button>
            </div>
          </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 filteredList" :key="index" :class="{ 'expired': isPastPeriod(item.period) }">
                <td>{{ item.type }}</td>
                <td>{{ item.approvalType }}</td>
                <td>{{ item.applicant }}</td>
                <td>{{ item.period }}</td>
                <td>{{ item.requestDate }}</td>
                <td :class="getStatusClass(item.status)">{{ item.status }}</td>
              </tr>
            </tbody>
          </table>

        </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>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import { SearchOutlined } from '@ant-design/icons-vue';
const currentYear = new Date().getFullYear();
const currentMonth = new Date().getMonth() + 1;
export default {
  data() {
    return {
      selectedStatus: 'all',
      currentMonth,
      selectedMonth: currentMonth,
      remainingMonths: Array.from({ length: 12 }, (_, i) => i + 1),
      currentYear,
      selectedYear: currentYear,
      remainingYears: Array.from({ length: 10 }, (_, i) => currentYear - i),
      currentPage: 1,
      totalPages: 3,
      photoicon: "/client/resources/img/photo_icon.png",
      h3icon: "/client/resources/img/h3icon.png",
      // 데이터 초기화
      years: [2023, 2024, 2025], // 연도 목록
      months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], // 월 목록
      selectedYear: '',
      selectedMonth: '',
      listData: [
        {
          type: '연차',
          approvalType: '결재',
          applicant: '홍길동',
          period: '2025-05-10 ~ 2025-15-03',
          requestDate: '2025-04-25',
        }, {
          type: '출장-복명',
          approvalType: '전결',
          applicant: '홍길동',
          period: '2025-05-01 ~ 2025-05-03',
          requestDate: '2025-04-25',
        }, {
          type: '출장-품의',
          approvalType: '전결',
          applicant: '홍길동',
          period: '2025-05-01 ~ 2025-05-03',
          requestDate: '2025-04-25',
        }
      ],
      listData2: [
        {
          type: '연차',
          approvalType: '결재',
          applicant: '홍길동',
          period: '2025-05-10 ~ 2025-15-03',
          requestDate: '2025-04-25',
          status: '대기'
        }, {
          type: '반차',
          approvalType: '전결',
          applicant: '홍길동',
          period: '2025-05-01 ~ 2025-05-03',
          requestDate: '2025-04-25',
          status: '승인'
        }],
      filteredData: [],
    };
  },
  computed: {
    filteredList() {
      if (this.selectedStatus === 'all') {
        return this.listData2;
      }
      return this.listData2.filter((item) => item.status === this.selectedStatus);
    },
  },
  components: {
    SearchOutlined
  },
  methods: {
    goToPage(item) {
    const type = item.type;
    if (type === '연차' || type === '반차') {
      this.$router.push('/hyugaDetail.page');
    } else if (type === '출장-품의') {
      this.$router.push('/ChuljangPumui.page');
    } else if (type === '출장-복명') {
      this.$router.push('/ChuljangBokmyeong.page');
    } else {
      alert('이동할 수 없는 항목입니다.');
    }
  },
    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);
      }
    },
    registerLeave() {
      console.log("등록 버튼 클릭됨");

      // Vue의 반응성 문제를 피하기 위해, 새로운 객체를 추가합니다.
      this.DeptData = [
        ...this.DeptData,
        { member: '', deptNM: '', acceptTerms: false }
      ];

      console.log(this.DeptData); // 배열 상태 출력
    },
    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>
tr{cursor: pointer;}
</style>