<template>
  <div class="card ">
    <div class="card-body ">
      <h2 class="card-title">직원 검색</h2>
      <div class="name-box flex  simple">
        <div class="img-area">
          <div class="img"><img :src="selectedUser.thumbnail?.filePath || photoicon" alt="">
          </div>
        </div>
        <div class="row g-3 needs-validation " :class="{ 'was-validated': formSubmitted }"
          @submit.prevent="handleRegister" novalidate>
          <div class="col-12">
            <label for="loginId" class="form-label">아이디</label>
            <input v-model="selectedUser.loginId" 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="userNm" class="form-label ">이름<p class="require"><img :src="require" alt=""></p></label>
              <input v-model="selectedUser.userNm" type="text" name="username" class="form-control" id="youremail"
                required readonly>
            </div>
            <div class="col-12 border-x">
              <label for="deptNm" class="form-label">부서</label>
              <input v-model="selectedUser.deptNm" type="text" name="password" class="form-control" id="yourPassword"
                required readonly placeholder="주식회사 테이큰 소프트">
            </div>
          </div>
          <div class="col-12 border-x">
            <div class="col-12 border-x">
              <label for="clsfNm" class="form-label">직급</label>
              <input v-model="selectedUser.clsfNm" type="text" name="username" class="form-control" id="youremail"
                required readonly>
            </div>
            <div class="col-12 border-x">
              <label for="rspofcNm" class="form-label">직책</label>
              <input v-model="selectedUser.rspofcNm" type="password" name="password" class="form-control"
                id="yourPassword" required readonly>
            </div>
          </div>
        </div>
      </div>
      <div class="row g-3 needs-validation detail" :class="{ 'was-validated': formSubmitted }"
        @submit.prevent="handleRegister" novalidate style="margin-bottom: 20px;">
        <div class="col-12">
          <label for="mbtlnum" class="form-label">연락처</label>
          <input v-model="selectedUser.mbtlnum" type="text" name="name" class="form-control " id="yourName" required
            readonly placeholder="admin">
        </div>
        <div class="col-12">
          <label for="brthdy" class="form-label">생년월일</label>
          <input v-model="selectedUser.brthdy" type="text" name="name" class="form-control" id="yourName" required
            readonly placeholder="admin">
        </div>
        <div class="col-12 border-x">
          <label for="encpn" class="form-label">입사일</label>
          <input v-model="selectedUser.encpn" type="text" name="name" class="form-control" id="yourName" required
            readonly placeholder="admin">
        </div>
      </div>
      <div class="row g-3 needs-validation detail salary" :class="{ 'was-validated': formSubmitted }"
        @submit.prevent="handleRegister" novalidate>
        <div class=" col-12 border-x"><label>연봉</label>
          <div class="yearsalary">
            <div class="col-12" v-for="(salary, index) in selectedUser.salaryList" :key="index">
              <label for="year" class="second-label">{{ salary.year }}</label>
              <input v-model="salary.amount" type="text" name="amount" class="form-control" id="amount" required
                readonly placeholder="admin" />
            </div>
          </div>
        </div>
      </div>
      <div class="buttons">
        <button type="delete" class="btn sm sm btn-red" @click="submitDeleteForm"
          v-if="selectedUser.useAt === 'Y'">탈퇴</button>
        <button type="delete" class="btn sm sm btn-red" @click="submitRepairForm"
          v-if="selectedUser.useAt === 'N'">복구</button>
        <button type="reset" class="btn sm sm secondary" @click="goToDetail"
          v-if="selectedUser.useAt === 'Y'">수정</button>
        <button type="submit" class="btn sm sm tertiary" @click="goToPage">목록</button>
      </div>
    </div>
  </div>
</template>

<script>
import GoogleCalendar from "../../../component/GoogleCalendar.vue"
import { SearchOutlined } from '@ant-design/icons-vue';
import { findUsersDetProc, updateUsersProc } from "../../../../resources/api/user"
export default {
  data() {
    return {
      photoicon: "/client/resources/img/photo_icon.png",
      img1: "/client/resources/img/img.png",
      icon1: "/client/resources/img/icon.png",
      dateicon: "/client/resources/img/date.png",
      startbtn: "/client/resources/img/start.png",
      stopbtn: "/client/resources/img/stop.png",
      moreicon: "/client/resources/img/more.png",
      selectedUser: {},
    }
  },
  components: {
    SearchOutlined, findUsersDetProc
  },
  methods: {
    //사용자 정보 상세 조회
    async searchUser() {
      try {
        const response = await findUsersDetProc(this.$route.query.id);
        if (response.status === 200) {
          this.selectedUser = response.data.data.user; // API 응답에서 카테고리 목록을 가져옴

          console.log("유저 아이디", this.selectedUser);
        }
      } catch (error) {
        console.error("검색 중 오류 발생:", error);
      }
    },
    goToPage() {
      this.$router.push({ name: 'HrmManagement' });
    },
    goToDetail() {
      this.$router.push({
        name: 'hrInsert',
        query: { id: this.selectedUser.userId }
      });
    },
    async submitDeleteForm() {
      const confirmDelete = confirm("정말로 사용자를 탈퇴시키겠습니까?\n이 작업은 되돌릴 수 없습니다.");

      if (!confirmDelete) { // 사용자가 '아니오'를 눌렀을 때
        alert("사용자 탈퇴가 취소되었습니다.");
        return; // 함수 실행 중단
      }

      // 2. FormData 객체 생성
      const formData = new FormData();

      // 수정용 DTO 생성 (기존 데이터 + 수정 데이터)
      const updateDTO = {
        userNm: this.selectedUser.userNm,
        useAt: "N",
        fileId: this.selectedUser.fileId,
      };

      formData.append('updateUserDTO', new Blob([JSON.stringify(updateDTO)], {
        type: 'application/json'
      }));

      // 4. API 통신
      try {
        const response = await updateUsersProc(this.$route.query.id, formData);

        if (response.status === 200) {
          alert('사용자 탈퇴퇴가 성공적으로 저장되었습니다!');
        }
      } catch (error) {
        console.error("사용자 정보 저장 중 오류 발생:", error);
        alert("사용자 정보 저장 중 오류가 발생했습니다.");
        if (error.response && error.response.data && error.response.data.message) {
          alert(`오류: ${error.response.data.message}`);
        }
      }
    },
    async submitRepairForm() {
      const confirmDelete = confirm("정말로 사용자를 복구시키겠습니까?\n이 작업은 되돌릴 수 없습니다.");

      if (!confirmDelete) { // 사용자가 '아니오'를 눌렀을 때
        alert("사용자 복구가 취소되었습니다.");
        return; // 함수 실행 중단
      }

      // 2. FormData 객체 생성
      const formData = new FormData();

      // 수정용 DTO 생성 (기존 데이터 + 수정 데이터)
      const updateDTO = {
        userNm: this.selectedUser.userNm,
        useAt: "Y",
        fileId: this.selectedUser.fileId,
      };

      formData.append('updateUserDTO', new Blob([JSON.stringify(updateDTO)], {
        type: 'application/json'
      }));

      // 4. API 통신
      try {
        const response = await updateUsersProc(this.$route.query.id, formData);

        if (response.status === 200) {
          alert('사용자 탈퇴퇴가 성공적으로 저장되었습니다!');
        }
      } catch (error) {
        console.error("사용자 정보 저장 중 오류 발생:", error);
        alert("사용자 정보 저장 중 오류가 발생했습니다.");
        if (error.response && error.response.data && error.response.data.message) {
          alert(`오류: ${error.response.data.message}`);
        }
      }
    },
  },
  watch: {

  },
  computed: {

  },
  mounted() {
    this.searchUser();
  }
}
</script>
<style scoped>
tr {
  cursor: pointer;
}
</style>