<template>
  <div class="card">
    <div class="card-body">
      <h2 class="card-title">출장 신청</h2>
      <p class="require"><img :src="require" alt=""> 필수입력</p>
      <!-- Multi Columns Form -->
      <form class="row g-3 pt-3  needs-validation" @submit.prevent="handleSubmit">


        <div class="col-12">
          <label for="where" class="form-label"><p>출장구분<p class="require"><img :src="require" alt=""></p></p></label>
          <select class="form-select"  style="width: 110px;">
                <option value="" selected>국내</option>
                <option value="">국외</option>
              </select>
        </div>
        <div class="col-12">
          <label for="where" class="form-label"><p>출장지<p class="require"><img :src="require" alt=""></p></p></label>
          <input type="text" class="form-control" id="where" v-model="where" />
        </div>
        <div class="col-12">
          <label for="where" class="form-label"><p>출장목적<p class="require"><img :src="require" alt=""></p></p></label>
          <input type="text" class="form-control" id="where" v-model="where" />
        </div>
        <div class="col-12">
          <label for="where" class="form-label"><p>출장기간<p class="require"><img :src="require" alt=""></p></p></label>
          <div class="d-flex gap-1">
            <input type="date" class="form-control" id="startDate" v-model="startDate" />
            <!-- 시간 선택을 위한 select 사용 -->
            <select class="form-control" id="startTime" v-model="startTime">
              <option value="09:00">09:00</option>
              <option value="10:00">10:00</option>
              <option value="11:00">11:00</option>
              <option value="12:00">12:00</option>
              <option value="13:00">13:00</option>
              <option value="14:00">14:00</option>
              <option value="15:00">15:00</option>
              <option value="16:00">16:00</option>
              <option value="17:00">17:00</option>
              <option value="18:00">18:00</option>
            </select>
            ~
          </div>
          <div class="d-flex gap-1">
            <input type="date" class="form-control" id="endDate" v-model="endDate" />
            <!-- 종료 시간을 위한 select 사용 -->
            <select class="form-control" id="endTime" v-model="endTime">
              <option value="09:00">09:00</option>
              <option value="10:00">10:00</option>
              <option value="11:00">11:00</option>
              <option value="12:00">12:00</option>
              <option value="13:00">13:00</option>
              <option value="14:00">14:00</option>
              <option value="15:00">15:00</option>
              <option value="16:00">16:00</option>
              <option value="17:00">17:00</option>
              <option value="18:00">18:00</option>
            </select>
          </div>
          <div class="col-12 border-x">
          <label for="dayCount" class="form-label">일수</label>
          <input type="text" class="form-control" id="dayCount" v-model="dayCount" readonly />
        </div>
        </div>

        <div class="col-12">
          <label for="purpose" class="form-label">동행자 <button type="button" title="추가" @click="showPopup1 = true">
              <PlusCircleFilled />
            </button></label>
            <HrPopup v-if="showPopup1" @close="showPopup1 = false" @select="addMember"/>
            <div v-for="(member, index) in members" :key="index" class="d-flex gap-2 addapproval mb-2">

              <form class="d-flex align-items-center border-x">
                <input type="text" class="form-control" v-model="member.name" style="max-width: 150px;" />
                <button type="button" @click="removeMember(index)" class="delete-button">
                  <CloseOutlined />
                </button>
              </form>
            </div>
        </div>
       
        <div class="col-12">
          <label for="member" class="form-label">
            <p>승인자<button type="button" title="추가" @click="showPopup = true">
              <PlusCircleFilled />
            </button><p class="require"><img :src="require" alt=""></p></p>
            
          </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"><p>품의내용<p class="require"><img :src="require" alt=""></p></p></label>
          <input type="text" class="form-control textarea" id="reason" v-model="reason" />
        </div>
        <div class="col-12">
          <label for="purpose" class="form-label">법인카드 <button type="button" title="추가" @click="showPopup3 = true">
              <PlusCircleFilled />
            </button></label>
            <CorpCardPopup v-if="showPopup3" @close="showPopup3 = false" @select="addCard"/>
            <div class="approval-container">
            <div v-for="(card, index) in cards" :key="index" class="d-flex gap-2 addapproval mb-2">

              <form class="d-flex align-items-center border-x">
                <input type="text" class="form-control" v-model="card.name" style="max-width: 150px;" />
                <button type="button" @click="removeCard(index)" class="delete-button">
                  <CloseOutlined />
                </button>
              </form>
            </div>
          </div>
        </div>
        <div class="col-12 border-x">
          <label for="purpose" class="form-label">법인차량 <button type="button" title="추가" @click="showPopup2 = true">
              <PlusCircleFilled />
            </button></label>
            <CorpCarPopup v-if="showPopup2" @close="showPopup2 = false" @select="addCar"/>
            <div class="approval-container">
            <div v-for="(car, index) in cars" :key="index" class="d-flex gap-2 addapproval mb-2">
              <input type="text" class="form-control" v-model="car.name" style="max-width: 150px;" />
              <select class="form-select" v-model="car.category" style="width: 120px;">
                <option value="운전자">운전자</option>
              </select>
              <button type="button" @click="removeCar(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';
import CorpCarPopup from '../../../component/Popup/CorpCarPopup.vue';
import CorpCardPopup from '../../../component/Popup/CorpCardPopup.vue';
export default {
  data() {
    const today = new Date().toISOString().split('T')[0];
    return {
      showPopup: false,
      showPopup1: false,
      showPopup2: false,
      showPopup3: false,
      require: "/client/resources/img/require.png",
      fileName: '',
      startDate: today,
      startTime: '09:00',
      endDate: today,
      endTime: '18:00',
      where: '',
      purpose: '',
      approvals: [        
      ],
      members: [        
      ],
      cards: [
      ],
      cars: [
      ],
     receipts: [
        {
          type: '개인결제',
          category: '결재',
          category1: '구분',
        },
      ],
    };
  },
  components: {
    PlusCircleFilled, CloseOutlined, HrPopup, CorpCarPopup, CorpCardPopup
  },
  computed: {
    loginUser() {
      const authStore = useAuthStore();
      return authStore.getLoginUser;
    },
  },

  methods: {
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (file) {
        this.fileName = file.name;
      }
    },
    addApproval(selectedUser) {
      this.approvals.push({
        category: '결재',
        name: selectedUser.name, // or other fields if needed
      });
      this.showPopup = false; // 팝업 닫기
    },
    addMember(selectedUser) {
      this.members.push({
        category: '결재',
        name: selectedUser.name, // or other fields if needed
      });
      this.showPopup1 = false; // 팝업 닫기
    },
    addCard(selectedCard) {
      this.cards.push({
        category: '결재',
        name: selectedCard.name, // or other fields if needed
      });
      this.showPopup3 = false; // 팝업 닫기
    },
    addCar(selectedCar) {
      this.cars.push({
        category: '결재',
        name: selectedCar.name, // or other fields if needed
      });
      this.showPopup2 = false; // 팝업 닫기
    },
    addReceipt() {
  this.receipts.push({
    type: '개인결제',
    category: '결재',
    category1: '',
    name: '',
    file: null,
  });
},
    // 승인자 삭제
    removeApproval(index) {
      this.approvals.splice(index, 1);
    },
    removeMember(index) {
      this.members.splice(index, 1);
    },
    removeCard(index) {
      this.cards.splice(index, 1);
    },
    removeCar(index) {
      this.cars.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>
