<template>
  <div class="card">
    <div class="card-body">
      <h2 class="card-title">출장 복명서 등록</h2>
      <!-- Multi Columns Form -->
      <form class="row g-3 pt-3  needs-validation detail" @submit.prevent="handleSubmit">


        <div class="col-12">
          <label for="where" class="form-label">출장구분</label>
          <input type="text" class="form-control" id="where" v-model="where" readonly/>
        </div>
        <div class="col-12">
          <label for="where" class="form-label">출장지</label>
          <input type="text" class="form-control" id="where" v-model="where" readonly/>
        </div>
        <div class="col-12">
          <label for="where" class="form-label">출장목적</label>
          <input type="text" class="form-control" id="where" v-model="where" readonly/>
        </div>
        <div class="col-12">
          <label for="where" class="form-label">출장기간</label>
          <input type="text" class="form-control" id="where" v-model="where" readonly/>
        </div>

        <div class="col-12">
          <label for="purpose" class="form-label">동행자</label>
          <input type="text" class="form-control" id="purpose" v-model="purpose" readonly/>
        </div>
        <div class="col-12">
          <label for="purpose" class="form-label">법인카드</label>
          <input type="text" class="form-control" id="purpose" v-model="purpose" readonly/>
        </div>
        <div class="col-12">
          <label for="purpose" class="form-label">법인차량</label>
          <input type="text" class="form-control" id="purpose" v-model="purpose" readonly/>
        </div>

        <div class="col-12">
          <label for="member" class="form-label">
            승인자
            <button type="button" title="추가"  @click="showPopup = true">
              <PlusCircleFilled />
            </button>
          </label>
          <HrPopup v-if="showPopup" @close="showPopup = false" @select="addApproval"/>
          <div class="approval-container">
            <div v-for="(approval, index) in approvals" :key="index" class="d-flex gap-2 addapproval mb-2">
              <select class="form-select" v-model="approval.category" style="width: 110px;">
                <option value="결재">결재</option>
                <option value="전결">전결</option>
                <option value="대결">대결</option>
              </select>

              <form class="d-flex align-items-center border-x">
                <input type="text" class="form-control" v-model="approval.name" style="max-width: 150px;" />
                <button type="button" @click="removeApproval(index)" class="delete-button">
                  <CloseOutlined />
                </button>
              </form>
            </div>
          </div>
        </div>
        <div class="col-12 chuljang">
          <label for="prvonsh" class="form-label">복명내용</label>
          <input type="text" class="form-control textarea" id="reason" v-model="reason" />
        </div>
        <div class="col-12 border-x">
          <label for="member" class="form-label">
            여비계산
            <button type="button" title="추가" @click="addReceipt">
              <PlusCircleFilled />
            </button>
          </label>

          <div class="approval-container">
            <div v-for="(receipt, index) in receipts" :key="index" class="d-flex gap-2 addapproval mb-2">
              <select class="form-select" style="width: 140px;">
                <option value="">개인결제</option>
                <option value="">법인결제</option>
              </select>
              <select class="form-select"  style="width: 110px;">
                <option value="">법인</option>
                <option value="">개인</option>
              </select>
              <select class="form-select"  style="width: 110px;">
                <option value="" selected>구분</option>
                <option value="">여비사용</option>
              </select>

              <input type="text" class="form-control" placeholder="금액입력" style="max-width: 150px;" />
             
                <!-- 커스텀 업로드 버튼 -->
                <label :for="'fileUpload-' + index" class="upload-label">
    영수증 첨부
  </label>

                <!-- 실제 파일 input (숨김 처리) -->
                <input
    :id="'fileUpload-' + index"
    type="file"
    @change="handleFileUpload(index, $event)"
    class="hidden-file-input"
  />


              <!-- 선택된 파일 이름 표시 -->
              <span v-if="receipt.fileName" class="file-name">{{ receipt.fileName }}</span>

              <button type="button" @click="removeReceipt(index)" class="delete-button">
                <CloseOutlined />
              </button>
            </div>
          </div>
        </div>

      </form>
      <div class="buttons">
        <button type="submit" class="btn primary">등록</button>
        <button type="reset" class="btn secondary">취소</button>
      </div>

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

<script>
import { PlusCircleFilled, CloseOutlined } from '@ant-design/icons-vue';
import HrPopup from '../../../component/Popup/HrPopup.vue';
export default {
  data() {
    const today = new Date().toISOString().split('T')[0];
    return {
      showPopup: false,
      fileName: '',
      startDate: today,
      startTime: '09:00',
      endDate: today,
      endTime: '18:00',
      where: '',
      purpose: '',
      approvals: [
      ],
     receipts: [
        {
          type: '개인결제',
          category: '결재',
          category1: '구분',
        },
      ],
    };
  },
  components: {
    PlusCircleFilled, CloseOutlined,HrPopup
  },
  computed: {
    loginUser() {
      const authStore = useAuthStore();
      return authStore.getLoginUser;
    },
  },

  methods: {
    handleFileUpload(index, event) {
    const file = event.target.files[0];
    if (file) {
      this.receipts[index].file = file;
      this.receipts[index].fileName = file.name;
    }
  },
    addApproval(selectedUser) {
      this.approvals.push({
        category: '결재',
        name: selectedUser.name, // or other fields if needed
      });
      this.showPopup = false; // 팝업 닫기
    },
    addReceipt() {
    this.receipts.push({
      type: '개인결제',
      category: '',
      category1: '',
      name: '',
      file: null,
      fileName: '',
    });
  },
    // 승인자 삭제
    removeApproval(index) {
      this.approvals.splice(index, 1);
    },
    removeReceipt(index) {
  this.receipts.splice(index, 1);
},
    validateForm() {
      // 필수 입력 필드 체크
      if (
        this.startDate &&
        this.startTime &&
        this.endDate &&
        this.endTime &&
        this.where &&
        this.purpose.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('ChuljangFormData', JSON.stringify(this.$data));
        alert("승인 요청이 완료되었습니다.");
        // 추가 처리 로직 (API 요청 등)
      } else {
        alert("모든 필드를 올바르게 작성해주세요.");
      }
    },
    loadFormData() {
      const savedData = localStorage.getItem('ChuljangFormData');
      if (savedData) {
        this.$data = JSON.parse(savedData);
      }
    },
  },
  mounted() {
    // Load the saved form data when the page is loaded
    this.loadFormData();
  },
  watch: {
    startDate: 'calculateDayCount',
    startTime: 'calculateDayCount',
    endDate: 'calculateDayCount',
    endTime: 'calculateDayCount',
    where: 'validateForm',
    purpose: "validateForm",
  },
};
</script>

<style scoped>
/* 필요한 스타일 추가 */
</style>
