<template>
   <div class="login-container">

      <div class="login ">
         <div class="logo flex justify-end"><img src="../resources/img/logo.png" alt=""></div>

         <div class="login-box">
            <div class="flex align-center justify-start mb40">
               <img src="../resources/img/icon1.png" alt="" class="mr20">
               <h2> 로그인 하기</h2>
            </div>
            <form @submit.prevent="submitForm" class="login-form ">
               <div class="mb30">
                  <p class="mb15 title" for="username">아이디</p>
                  <input type="text" id="username" v-model="username" placeholder="아이디를 입력하세요.">
               </div>
               <div>
                  <p class="mb15 title" for="password">비밀번호</p>
                  <input type="password" id="password" v-model="password" placeholder="비밀번호를 입력하세요.">
               </div>
               <button class="login-btn mt50" type="submit" @click="goToApp"><img src="../resources/img/button.png"
                     alt="">
                  <p>로그인</p>
               </button>
               <div class="flex justify-between mt40">
                  <button>
                     <p class="underline title2" @click="buttonSearch">아이디/비밀번호 찾기</p>
                  </button>
                  <button>
                     <p class="underline title2" @click="goToPage('Join')">회원가입</p>
                  </button>
               </div>
            </form>
         </div>
      </div>
   </div>
   <div v-show="searchOpen" class="popup-wrap">
      <div class="popup-box ">
         <div class="flex justify-end mb10">
            <!-- <p class="popup-title">학교 검색</p> -->
            <button type="button" class="popup-close-btn" @click="closeBtn">
               <svg-icon type="mdi" :path="mdiWindowClose" class="close-btn"></svg-icon>

            </button>
         </div>
         <div class="tab-box" v-show="selectedTab !== 'tab3' && selectedTab !== 'tab4'">
            <label class="mr20 title1">
               <input type="radio" v-model="selectedTab" value="tab1" />
               아이디 찾기
            </label>
            <label class="mr20 title1">
               <input type="radio" v-model="selectedTab" value="tab2" />
               비밀번호 찾기
            </label>
         </div>
         <!-- 아이디 찾기 -->
         <div class="find-form mt30" v-if="selectedTab === 'tab1'">
            <div class="mb20 flex justify-between align-center">
               <p class="title2" for="username" style="width: 12rem;">이름</p>
               <input class="data-wrap" type="text" id="username" v-model="findUserNm" placeholder="이름을 입력하세요.">
            </div>
            <div class="mb30 flex justify-between align-center">
               <p class="title2" for="username" style="width: 12rem;">전화번호</p>
               <div class="flex justify-between align-center" style="width: 100%;"><input class="data-wrap"
                     style="width: 12rem;" type="text" id="username" v-model="findTel1">
                  <p class="title2">-</p><input class="data-wrap" style="width: 14rem;" type="text" id="username"
                     v-model="findTel2">
                  <p class="title2">-</p><input class="data-wrap" style="width: 14rem;" type="text" id="username"
                     v-model="findTel3">
               </div>
            </div>
            <div class="flex justify-center ">
               <button type="button" title="글쓰기" class="new-btn mr10" @click="closeBtn">
                  취소
               </button>
               <button @click="findId" type="button" title="글쓰기" class="new-btn">
                  찾기
               </button>
            </div>
         </div>
         <!-- 비밀번호 찾기 -->
         <div class="find-form mt30" v-else-if="selectedTab === 'tab2'">
            <div class="mb20 flex justify-between align-center">
               <p class="title2" for="username" style="width: 12rem;">아이디</p>
               <input class="data-wrap" type="text" id="username" v-model="changeUserNm" placeholder="아이디를 입력하세요.">
            </div>
            <div class="mb20 flex justify-between align-center">
               <p class="title2" for="username" style="width: 12rem;">변경할 비밀번호</p>
               <input class="data-wrap" type="text" id="username" v-model="changeUserPw" placeholder="변경할 비밀번호를 입력하세요.">
            </div>
            <p class="title2 mb20 flex align-center help" for="username"><img src="../resources/img/img193_78p.png"
                     alt=""><em class="gray ml10">영문, 숫자, 특수문자 3가지를 조합하여 주세요.(6자리 이상)</em></p>
            <div class="mb20 flex justify-between align-center">
               <p class="title2" for="username" style="width: 12rem;">비밀번호 확인</p>
               <input class="data-wrap" type="text" id="username" v-model="changeUserPwCheck" placeholder="변경할 비밀번호를 입력하세요.">
            </div>
            <div class="flex justify-center ">
               <button type="button" title="글쓰기" class="new-btn mr10" @click="closeBtn">
                  취소
               </button>
               <button @click="changePw" type="button" title="글쓰기" class="new-btn">
                  찾기
               </button>
            </div>
         </div>
         <!-- 아이디 찾기 결과 -->
         <div v-else-if="selectedTab === 'tab3'">
            <div class="flex justify-center mt30">
               <p class="title2">아이디 찾기가 완료 되었습니다.</p>
            </div>
            <table class="find-table mt30 mb30">
               <tr>
                  <td class="thead">이름</td>
                  <td>{{ findUserInfo.userNm }}</td>
               </tr>
               <tr>
                  <td class="thead">아이디</td>
                  <td>{{ findUserInfo.loginId }}</td>
               </tr>
            </table>
            <div class="flex justify-center ">
               <button @click="closeBtn" type="button" title="글쓰기" class="new-btn">
                  로그인 하기
               </button>
            </div>
         </div>
         <!-- 비밀번호 찾기 결과 -->
         <div v-else-if="selectedTab === 'tab4'">
            <div class="flex justify-center mt30">
               <p class="title2">비밀번호가 변경되었습니다.</p>
            </div>
            <table class="find-table mt30 mb30">
               <tr>
                  <td class="thead">변경된 비밀번호에 맞춰 로그인해주세요.</td>
               </tr>
            </table>
            <div class="flex justify-center ">
               <button @click="closeBtn" type="button" title="글쓰기" class="new-btn">
                  로그인하기
               </button>
            </div>
         </div>
      </div>
   </div>
</template>

<script>
import SvgIcon from '@jamescoyle/vue-icon';
import { mdiMagnify, mdiWindowClose } from '@mdi/js';
import axios from "axios";
import store from './pages/AppStore';

export default {
   data() {
      return {
         selectedTab: 'tab1',
         username: '',
         password: '',
         mdiWindowClose: mdiWindowClose,
         showModal: false,
         searchOpen: false,
         findUserNm: '',
         findTel1: '',
         findTel2: '',
         findTel3: '',
         findUserInfo : {},
      }
   },
   methods: {
      // 로그인
      submitForm() {
         console.log('Username:', this.username);
         console.log('Password:', this.password);

         const vm = this;

         axios({
            url: "/auth/login.json",
            method: "post",
            data: {
               loginId: this.username,
               password: this.password,
            },
         }).then(function (response) {

            const token = response.headers.get('Authorization');
            store.dispatch('login', token);

            vm.branchPage();
         }).catch(function (error) {
            alert("아이디나 비밀번호가 잘못됐습니다 !");
            console.log(error);
         });

      },
      // 로그인 후 권한에 따라 이동
      branchPage() {
         const vm = this;
         const token = localStorage.getItem('token');

         if (token) {
            // JWT 토큰을 '.'로 분리
            const tokenParts = token.split('.');
            if (tokenParts.length === 3) {
               const payload = tokenParts[1];

               const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');

               // Base64 디코딩 후 UTF-8로 변환
               const jsonPayload = decodeURIComponent(
                  Array.prototype.map.call(atob(base64), c => {
                     return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
                  }).join('')
               );

               const userInfo = JSON.parse(jsonPayload);

               // Vuex 스토어에 사용자 정보 저장
               store.commit('setToken', token);
               store.commit('setUser', userInfo.usid);
               store.commit('setUserNm', userInfo.userNm);
               store.commit('setAuthcd', userInfo.author[0].authority);
               const roles = userInfo.author.map(role => role.authority);

               console.log(userInfo);

               // 역할에 따라 페이지 이동
               if (roles.includes("STUDENT")) {
                  vm.goToPage('MyPlan');
               } else if (roles.includes("TEACHER")) {
                  vm.goToPage('Board');
               } else if (roles.includes("PARENT")) {
                  vm.goToPage('Main_p');
               } else if (roles.includes("ADMIN")) {
                  vm.goToPage('MyPlan');
               }
            } else {
               console.error('Invalid token structure');
            }
         } else {
            console.error('No token found');
         }
      },

      // 아이디 찾기
      findId() {
         const vm = this;

         const telno = vm.findTel1 + '-' + vm.findTel2 + '-' + vm.findTel3;

         axios({
            url: "/auth/findId.json",
            method: "post",
            data: {
               telno: telno,
               userNm: vm.findUserNm,
            },
         }).then(function (response) {
            vm.selectedTab = 'tab3';
            vm.findUserInfo = response.data;
         }).catch(function (error) {
            alert("등록되지 않은 사용자입니다!");
            console.log(error);
         });
      },

      // 비밀번호 확인하기

      closeModal() {
         this.showModal = false;
      },
      buttonSearch() {
         this.searchOpen = true;
      },
      closeBtn() {
         this.searchOpen = false;

      },
      goToPage(page) {
         this.$router.push({ name: page });
      },

   },
   components: {
      SvgIcon
   },
}
</script>

<style scoped></style>