<template>
  <div class="card">
    <div class="card-body">
     <h2 class="card-title">프로젝트 현황</h2>
      <!-- Multi Columns Form -->
      <div class=" sch-form-wrap title-wrap"><h3><img :src="h3icon" alt="">프로젝트 정보</h3></div>
      <form class="row g-3 pt-3  needs-validation detail" @submit.prevent="handleSubmit" style="margin-bottom: 3rem;">

        <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">
          <div class="col-12 border-x">
            <label for="where" class="form-label">주관기관</label>
            <input type="text" class="form-control" id="where" v-model="where" readonly/>
          </div>
          <div class="col-12 border-x">
            <label for="where" class="form-label">담당부서</label>
            <input type="text" class="form-control" id="where" v-model="where" readonly/>
          </div>
  
       </div>
       <div class="col-12">
          <div class="col-12 border-x">
            <label for="where" class="form-label">프로젝트 책임자</label>
            <input type="text" class="form-control" id="where" v-model="where" readonly/>
          </div>
          <div class="col-12 border-x">
            <label for="where" class="form-label">사업비</label>
            <input type="text" class="form-control" id="where" v-model="where" readonly/>
          </div>
  
       </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="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 chuljang border-x">
          <label for="prvonsh" class="form-label">비고</label>
          <input type="text" class="form-control textarea" id="reason" v-model="reason" readonly/>
        </div>
       

      </form>
      <div class="buttons">
        <button type="reset" class="btn sm secondary">수정</button>
        <button type="delete" class="btn sm btn-red">삭제</button>
        <button type="submit" class="btn sm tertiary">목록</button>
      </div>
      <div class=" sch-form-wrap title-wrap"><h3><img :src="h3icon" alt="">회의록 정보</h3></div>
      <div class="cost-statue">
        <p class="costtitle">회의비 사용내역</p>
        <div class="d-flex">
          <div class="col-12 border-x ">
            <p style="color: #219A8C;">전체</p>
            <input type="text" class="form-control">
          </div>
          <div class="col-12 border-x">
            <p style="color: #1D75E1;">사용</p>
            <input type="text" class="form-control">
          </div>
          <div class="col-12 border-x">
            <p style="color: #E92727;">미사용</p>
            <input type="text" class="form-control">
          </div>
        </div>
      </div>
      <div class="tbl-wrap">
        <table id="myTable" class="tbl data">
          <colgroup>
            <col style="width: 200px;">
            <col style=" width: ">
          </colgroup>
          <thead>
            <tr>
              <th>제목</th>
              <th>참석자</th>
              <th>회의비</th>
              <th>일시</th>
            </tr>
          </thead>
          <!-- 동적으로 <td> 생성 -->
          <tbody>
            <tr v-for="(item, index) in listData" :key="index" @click="goToPage('회의록 상세')">
              <td>{{ item.title }}</td>
              <td>{{ item.member }}</td>
              <td>{{ item.cost }}</td>
              <td>{{ item.period }}</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="buttons">
    <button type="insert" class="btn sm primary sm" @click="goToPage('회의록 등록')">회의록 등록</button>
  </div>

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

<script>
import { PlusCircleFilled, CloseOutlined } from '@ant-design/icons-vue';

export default {
  data() {
    const today = new Date().toISOString().split('T')[0];
    return {
      currentPage: 1,
      totalPages: 3,
      listData: [
        {
          title: '프로젝트 회의록',
          member: 'ooo외 3명',
          cost: '100,000',
          period: '2025-01-01 14:00 ~ 2025-01-01 16:00',
        }, ],
      h3icon: "/client/resources/img/h3icon.png",
      fileName: '',
      startDate: today,
      startTime: '09:00',
      endDate: today,
      endTime: '18:00',
      where: '',
      purpose: '',
      approvals: [
        {
          category: '결재',
          name: '',
        },
      ],
     receipts: [
        {
          type: '개인결제',
          category: '결재',
          category1: '구분',
        },
      ],
    };
  },
  components: {
    PlusCircleFilled, CloseOutlined
  },
  computed: {
    loginUser() {
      const authStore = useAuthStore();
      return authStore.getLoginUser;
    },
  },

  methods: {
    goToPage(type) {
  if (type === '회의록 등록') {
    this.$router.push({ name: 'meetingInsert' });
  } else if (type === '회의록 상세') {
    this.$router.push({ name: 'meetingDetail' });
  }
},
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (file) {
        this.fileName = file.name;
      }
    },
    addApproval() {
      this.approvals.push({
        category: '결재',
        name: '',
      });
    },
    addReceipt() {
  this.receipts.push({
    type: '개인결제',
    category: '결재',
    category1: '',
    name: '',
    file: null,
  });
},
    // 승인자 삭제
    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>
tr{cursor: pointer;}
</style>
