<template>
  <div class="sidemenu">
    <div class="myinfo profile">
      <div class="name-box">
        <div class="img-area">
          <div class="img">
            <img :src="previewImg || placeholder" alt="미리보기 이미지" />
            <button class="close-btn" @click="removeImage">&#215;</button>
          </div>
          <div class="info">
            <div class="file">
              <label for="fileUpload" class="file-label">
                <img :src="file" alt="">
                <p>업로드</p>
              </label>
              <input id="fileUpload" type="file" @change="handleFileUpload" accept="image/*" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="content">

    <div class="d-flex justify-content-center py-4">
      <a href="index.html" class="logo d-flex align-items-center w-auto">
        <!-- <span class="d-none d-lg-block"> <img :src="logo" alt=""></span> -->
      </a>
    </div><!-- End Logo -->

    <div class="card mb-3">
      <p class="require"><img :src="require" alt=""> 필수입력</p>
      <div class="card-body">

        <form class="row g-3 needs-validation " :class="{ 'was-validated': formSubmitted }"
          @submit.prevent="handleRegister" novalidate>
          <div class="col-12">
            <label for="yourName" class="form-label">아이디</label>
            <input v-model="name" type="text" name="name" class="form-control" id="yourName" required readonly
              placeholder="admin">
          </div>
          <div class="col-12 ">
            <div class="col-12 border-x">
              <label for="youremail" class="form-label ">
                <p>이름
                <p class="require"><img :src="require" alt=""></p>
                </p>
              </label>
              <input v-model="email" type="text" name="username" class="form-control" id="youremail" required>
            </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" required
                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" required 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" required
                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" required>
          </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" required>
          </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" required readonly
              placeholder="2025-01-01">
          </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" required>
          </div>
          <div class="col-12">
            <label for="yourName" class="form-label">새 비밀번호</label>
            <div class="box">
              <input v-model="name" type="text" name="name" class="form-control" id="yourName" required>
              <div class="invalid-feedback">※ 비밀번호는 6~12자의 영문자와 숫자, 특수기호조합으로 작성해주세요.</div>
            </div>
          </div>
          <div class="col-12 border-x">
            <label for="yourName" class="form-label">연락처</label>
            <input v-model="name" type="text" name="name" class="form-control" id="yourName" required>
          </div>

        </form>
        <div class="buttons">
          <button class="btn btn-red " type="submit">회원탈퇴</button>
          <button class="btn secondary " type="submit">수정</button>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
export default {
  data() {
    return {
      previewImg: null,
      placeholder: "/client/resources/img/img1.png",
      require: "/client/resources/img/require.png",
      file: "/client/resources/img/file.png",
      name: '',
      email: '',
      password: '',
      dept: '',
      level: '',
      acceptTerms: false,
      formSubmitted: false,
    };
  },
  methods: {
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (file && file.type.startsWith('image/')) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.previewImg = e.target.result; // 파일 읽기 완료 후 미리보기 이미지 설정
        };
        reader.readAsDataURL(file); // 파일을 데이터 URL로 읽기
      } else {
        alert('이미지 파일만 선택할 수 있습니다.');
      }
    },

    // 이미지 삭제 함수
    removeImage() {
      this.previewImg = null; // 미리보기 이미지 삭제
      this.$refs.fileUpload.value = null; // 파일 input 초기화
    },
    handleRegister() {
      this.formSubmitted = true;
      // 이메일과 비밀번호가 빈 값이 아니어야 한다
      if (!this.email.includes('@')) {
        alert('이메일은 @를 포함해야 합니다.');
        return; // Stop further processing if email is invalid
      }

      console.log('Email:', this.email);
      console.log('Password:', this.password);
      console.log('Name:', this.name);
      console.log('Accept Terms:', this.acceptTerms);
      if (this.email && this.password && this.name && this.acceptTerms && this.dept && this.level) {
        // 로컬 스토리지에 회원가입 정보 저장
        const userData = {
          name: this.name,
          email: this.email,
          password: this.password,
          dept: this.dept,
          level: this.level,
        };

        console.log('User Data to be saved:', userData);
        try {
          localStorage.setItem("UserInfo", JSON.stringify(userData));
          alert('회원가입이 완료되었습니다!');

          // Redirect to login page
          this.$router.push("/login");
        } catch (error) {
          console.error("Error saving to localStorage:", error);
          alert("회원가입 중 오류가 발생했습니다.");
        }
      } else {
        alert("모든 필드를 입력해주세요.");
      }
    },
  },
  created() {
    // 로컬스토리지에서 데이터 불러오기
    const storedData = localStorage.getItem('DeptData');
    if (storedData) {
      this.DeptData = JSON.parse(storedData);
    }
  },
};
</script>

<style scoped></style>