<template>
  <div class="card">
    <div class="card-body">
      <h2 class="card-title">휴가 현황</h2>
      <div class="form-card">
        <h1>휴가신청서</h1>
        <SanctnViewList v-if="detailData.sanctnList.length > 0" :sanctns="detailData.sanctnList" />
        <form class="row g-3 needs-validation detail" novalidate>
          <div class="col-12">
            <div class="col-12 border-x">
              <label for="vcatnType" class="form-label">유형</label>
              <p>{{ detailData.vcatnKndNm }}</p>
            </div>
            <div class="col-12 border-x">
              <label for="applicant" class="form-label">신청자</label>
              <p>{{ detailData.userNm }}</p>
            </div>
          </div>
          <div class="col-12">
            <div class="col-12 border-x">
              <label for="department" class="form-label">부서</label>
              <p>{{ detailData.deptNm }}</p>
            </div>
            <div class="col-12 border-x">
              <label for="position" class="form-label">직급</label>
              <p>{{ detailData.clsfNm }}</p>
            </div>
          </div>
          <div class="col-12">
            <label for="period" class="form-label">기간</label>
            <p>{{ $formattedDates(detailData) }}</p>
          </div>
          <div class="col-12 hyuga">
            <label for="details" class="form-label">세부사항</label>
            <ViewerComponent :content="detailData.detailCn" />
          </div>
          <div class="col-12">
            <label for="requestDate" class="form-label">신청일</label>
            <p>{{ detailData.rgsde }}</p>
          </div>
          <div class="col-12">
            <label for="status" class="form-label">상태</label>
            <p>{{ detailData.confmAtNm }}</p>
          </div>
          <div v-if="detailData.confmAt === 'R'" class="col-12 border-x return">
            <label for="rejectReason" class="form-label">반려사유</label>
            <template v-for="(item, idx) of detailData.sanctnList" :key="idx">
              <p v-if="item.confmAt === 'R'">{{ item.returnResn }}</p>
            </template>
          </div>
        </form>
      </div>
      <div class="buttons">
        <button v-if="detailData.confmAt === 'W' || detailData.confmAt === 'R'" class="btn sm btn-red" type="button" @click="deleteData">신청취소</button>
        <button v-if="detailData.confmAt === 'W'" class="btn sm secondary" type="button" @click="fnMoveTo('edit', pageId)">수정</button>
        <button v-if="detailData.confmAt === 'R'" class="btn sm secondary" type="button" @click="fnMoveTo('edit', pageId)">재신청</button>
        <button class="btn sm tertiary" type="button" @click="fnMoveTo('list')">목록</button>
      </div>
      <ReturnPopup v-if="showPopup" @close="showPopup = false" />
    </div>
  </div>
</template>
<script>
import ReturnPopup from '../../../component/Popup/ReturnPopup.vue';
import ViewerComponent from '../../../component/editor/ViewerComponent.vue';
import SanctnViewList from '../../../component/Sanctn/SanctnViewList.vue';
// API
import { findVcatnProc, deleteVcatnProc } from '../../../../resources/api/vcatn';

export default {
  components: {
    ReturnPopup, ViewerComponent,
    SanctnViewList,
  },

  data() {
    return {
      require: "/client/resources/img/require.png",

      pageId: null,
      showPopup: false,
      isRegister: false,

      detailData: {
        vcatnId: null,
        userId: null,
        userNm: null,
        vcatnKnd: null,
        vcatnKndNm: null,
        deptId: null,
        deptNm: null,
        clsf: null,
        clsfNm: null,
        bgnde: null,
        beginHour: null,
        beginMnt: null,
        endde: null,
        endHour: null,
        endMnt: null,
        detailCn: null,
        confmAt: null,
        confmAtNm: null,
        rgsde: null,
        register: null,
        updde: null,
        updusr: null,
        sanctnList: []
      },
    };
  },

  computed: {},

  async created() {
    this.pageId = this.$route.query.id;
    if (this.$isEmpty(this.pageId)) {
      alert("게시물이 존재하지 않습니다.");
      this.fnMoveTo('list');
    }
  },

  mounted() {
    this.findData(); // 상세 조회
  },

  methods: {
    // 상세 조회
    async findData() {
      try {
        const response = await findVcatnProc(this.pageId);
        const result = response.data.data;

        this.detailData = result.vo;
        this.isRegister = this.$registerChk(result.vo.register);
      } catch (error) {
        if (error.response) {
          alert(error.response.data.message);
        } else {
          alert("에러가 발생했습니다.");
        }
        console.error(error.message);
        this.fnMoveTo('list');
      }
    },

    // 일수 계산
    calculateDayCount() {
      if (!this.detailData.bgnde || !this.detailData.endde) return 0;

      let dayCnt = 1; // 기본값

      // 반차인 경우
      if (this.detailData.vcatnKnd === 'MORNING_HALF' || this.detailData.vcatnKnd === 'AFTERNOON_HALF') {
        dayCnt = 0.5;
      }

      const startDate = new Date(this.detailData.bgnde);
      const endDate = new Date(this.detailData.endde);
      const timeDiff = endDate.getTime() - startDate.getTime();
      const dayDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24)) + 1;

      return dayCnt * Math.max(0, dayDiff);
    },

    // 삭제
    async deleteData() {
      const isCheck = confirm("삭제하시겠습니까?");
      if (!isCheck) {
        return;
      }

      try {
        const response = await deleteVcatnProc(this.pageId);

        this.fnMoveTo('list');
      } catch (error) {
        if (error.response) {
          alert(error.response.data.message);
        } else {
          alert("에러가 발생했습니다.");
        }
        console.error(error.message);
        this.fnMoveTo('list');
      }
    },

    // 페이지 이동
    fnMoveTo(type, id) {
      const routes = {
        'list': { name: 'hyugaStatue' },
        'view': { name: 'HyugaDetail', query: { id } },
        'edit': { name: 'hyugaInsert', query: this.$isEmpty(id) ? {} : { id } },
      };

      if (routes[type]) {
        if (!this.$isEmpty(this.pageId) && type === 'list') {
          this.$router.push({ name: 'HyugaDetail', query: { id: this.pageId } });
        }
        this.$router.push(routes[type]);
      } else {
        alert("올바르지 않은 경로를 요청하여 목록으로 이동합니다.");
        this.$router.push(routes['list']);
      }
    },
  }
};
</script>