<template>
<div class="card ">
      <div class="card-body">
          <h2 class="card-title">출장 현황</h2>
       
      <div class="form-card">
        <h1>출장품의서</h1>
        <div class="approval-box tbl-wrap tbl2">
         <table class="tbl data">
          <tbody>
            <tr class="thead">
              <td rowspan="2" class="th">승인자</td>
              <td>과장</td>
              <td>소장</td>
            </tr>
            <tr>
              <td><p class="name">홍길동</p><p class="date">2025/05/09</p></td>
              <td><p class="name">홍길동</p><p class="date">2025/05/09</p></td>
            </tr>
          </tbody>

         </table>
        </div>
          <form class="row g-3 needs-validation "  :class="{ 'was-validated': formSubmitted }" @submit.prevent="handleRegister" novalidate>
                <div class="col-12 ">
                  <div class="col-12 border-x">
                    <label for="youremail" class="form-label ">출장구분<p class="require"><img :src="require" alt=""></p></label>
                    <input  v-model="email" type="text" name="username" class="form-control" id="youremail" readonly >
                  </div>
    
                  <div class="col-12 border-x">
                    <label for="yourPassword" class="form-label">이름</label>
                    <input  v-model="password" type="password" name="password" class="form-control" id="yourPassword" readonly   placeholder="주식회사 테이큰 소프트"> 
                  </div>
               </div>
               <div class="col-12">
                  <div class="col-12 border-x">
                    <label for="youremail" class="form-label">부서</label>
                    <input  v-model="email" type="text" name="username" class="form-control" id="youremail" readonly  placeholder="과장">
                  </div>
    
                  <div class="col-12 border-x">
                    <label for="yourPassword" class="form-label">직급</label>
                    <input  v-model="password" type="password" name="password" class="form-control" id="yourPassword" readonly  placeholder="팀장"> 
                  </div>
               </div>
               <div class="col-12">
                  <label for="yourName" class="form-label">출장지</label>
                  <input  v-model="name" type="text" name="name" class="form-control" id="yourName" readonly>
            </div>
            <div class="col-12">
                  <label for="yourName" class="form-label">출장목적</label>
                  <input v-model="name" type="text" name="name" class="form-control " id="yourName" readonly>
            </div>
            <div class="col-12">
                  <label for="yourName" class="form-label">동행자</label>
                  <input v-model="name" type="text" name="name" class="form-control " id="yourName" readonly>
            </div>
            <div class="col-12 chuljang">
                  <label for="yourName" class="form-label">내용</label>
                  <input v-model="name" type="text" name="name" class="form-control textarea " id="yourName" readonly>
            </div>
            <div class="col-12">
                  <label for="yourName" class="form-label">법인카드</label>
                  <input v-model="name" type="text" name="name" class="form-control " id="yourName" readonly>
            </div>
            <div class="col-12">
                  <label for="yourName" class="form-label">법인차량</label>
                  <input v-model="name" type="text" name="name" class="form-control " id="yourName" readonly>
            </div>
            <div class="col-12">
                  <label for="yourName" class="form-label">품의 신청일</label>
                  <input v-model="name" type="text" name="name" class="form-control " id="yourName" readonly>
            </div>
            <div class="col-12 border-x" :class="{ return: isReturned }">
                  <label for="yourName" class="form-label">반려사유</label>
                  <input  v-model="name" type="text" name="name" class="form-control" id="yourName" readonly   placeholder="2025-01-01">
            </div>
           
                
              </form>
      </div>
            <div class="buttons">
              <button class="btn btn-red "  type="submit">신청취소</button>
              <button class="btn secondary"  type="submit">  {{ isReturned ? '재신청' : '수정' }}</button>
              <button class="btn primary" type="submit" v-if="!isReturned">복명서 작성</button>
                <button class="btn tertiary "  type="submit">목록</button>
              </div>

      </div>
    </div>
</template>

<script>
export default {
  data() {
    const today = new Date().toISOString().split('T')[0];
    return {
      isReturned: true,
      startDate: today,
      startTime: "09:00", // 기본 시작 시간 09:00
      endDate: today,
      endTime: "18:00", // 기본 종료 시간 18:00
      category: "", 
      dayCount: 1, 
      reason: "", // 사유
      listData: [
  {
    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: '승인'
  }],
    };
  },
  computed: {
    // Pinia Store의 상태를 가져옵니다.
    loginUser() {
      const authStore = useAuthStore();
      return authStore.getLoginUser;
    },
  },
  methods: {
    // 폼 검증 메서드
    validateForm() {
      // 필수 입력 필드 체크
      if (
        this.category &&
        this.startDate &&
        this.startTime &&
        this.endDate &&
        this.endTime &&
        this.dayCount > 0 &&
        this.reason.trim() !== ""
      ) {
        this.isFormValid = true;
      } else {
        this.isFormValid = false;
      }
    },
    calculateDayCount() {
    const start = new Date(`${this.startDate}T${this.startTime}:00`);
    const end = new Date(`${this.endDate}T${this.endTime}:00`);
    
    let totalHours = (end - start) / (1000 * 60 * 60);  // 밀리초를 시간 단위로 변환
    
    if (this.startDate !== this.endDate) {
      // 시작일과 종료일이 다른경우
      const startDateObj = new Date(this.startDate);
      const endDateObj = new Date(this.endDate);
      const daysDifference = (endDateObj - startDateObj) / (1000 * 60 * 60 * 24); // 두 날짜 사이의 차이를 일수로 계산
      if (this.startTime !== "09:00" || this.endTime !== "18:00") {
        this.dayCount = daysDifference + 0.5; // 시간 조건이 기준에서 벗어날 경우
      } else {
        this.dayCount = Math.ceil(daysDifference + 1); // 시간 조건이 기준에 맞을 경우
      }
    } else {
      // 시작일과 종료일이 같은 경우
      if (this.startTime !== "09:00" || this.endTime !== "18:00") {
        this.dayCount = 0.5; // 시작 시간 또는 종료 시간이 기준과 다를 경우 0.5
      } else {
        this.dayCount = 1; // 기준 시간(09:00~18:00)이 맞으면 1일로 간주
      }
    }

    this.validateForm(); // dayCount 변경 후 폼 재검증
  },
    handleSubmit() {
      this.validateForm(); // 제출 시 유효성 확인
      if (this.isFormValid) {
        localStorage.setItem('HyugaFormData', JSON.stringify(this.$data));
        alert("승인 요청이 완료되었습니다.");
        // 추가 처리 로직 (API 요청 등)
      } else {
        alert("모든 필드를 올바르게 작성해주세요.");
      }
    },
    
    
  },
  mounted() {
    // Load the saved form data when the page is loaded
    this.loadFormData();
  },
  watch: {
  startDate: 'calculateDayCount',
  startTime: 'calculateDayCount',
  endDate: 'calculateDayCount',
  endTime: 'calculateDayCount',
  reason: "validateForm",
  category: 'category',
  },
};
</script>
