<template>
  <div class="login-page page">
      <div>
        <div class="background-img">
          <p>
            콘텐츠 관리 시스템에 오신 것을 환영합니다.<br />
            원활한 관리와 운영을 위해 로그인하세요.
          </p>
        </div>
        <div class="login-wrap">
            <div class="login">
              <div
                :class="{
                  'login-title': true,
                  'user-login': !isAdminPage,
                }"
              >
                LOGIN
              </div>
              <div class="form-group">
                <label for="id" class="login-label">아이디</label>
                <input
                  type="text"
                  name=""
                  id="id"
                  class="form-control md"
                  placeholder="아이디를 입력하세요"
                  v-model="member['lgnId']"
                />
              </div>
              <div class="form-group">
                <label for="pw" class="login-label">비밀번호</label>
                <input
                  type="password"
                  name=""
                  id="pw"
                  class="form-control md"
                  placeholder="비밀번호를 입력하세요"
                  v-model="member['pswd']"
                  @keydown.enter="fnLogin"
                />
              </div>
              <button
                class="btn md main user-btn"
                v-if="!isAdminPage"
                @click="fnLogin"
                   @keydown.enter="fnLogin"
              >
                로그인
              </button>
              <button
                class="btn md main"
                v-else
                @click="fnLogin"
                @keydown.enter="fnLogin"
              >
                로그인
              </button>

              <div
                class="input-group"
                v-if="!isAdminPage"
              >
                <p class="pl10 pr10 cursor" @click="moveSearchId">아이디찾기</p>
                <p class="pl10 pr0 cursor" @click="moveResetPswd">비밀번호 초기화</p>
              </div>
            </div>
        </div>
      </div>
  </div>
</template>

<script>
import { useStore } from "vuex";
import store from "../AppStore";
import { loginProc } from "../../../resources/api/login";
import queryParams from "../../../resources/js/queryParams";

export default {
  mixins: [queryParams],
  data: () => {
    return {
      member: {
        lgnId: null,
        pswd: null,
      },
      store: useStore(),
      isAdminPage: false,
    };
  },
  methods: {
    checkAdminPage() {
      if (
        this.restoreRedirect("redirect") &&
        this.restoreRedirect("redirect").includes("/adm/")
      ) {
        this.isAdminPage = true;
      } else {
        this.isAdminPage = false;
      }
    },
    async fnLogin() {
      try {
        const res = await loginProc(this.member);
        if (res.status == 200) {
          const loginType = res.headers['login-type']; // 세션/토큰 로그인 구분
          if (loginType === 'J') {
              // JWT 방식
              store.commit("setAuthorization", res.headers.authorization);
              store.commit("setLoginMode", "J");
              localStorage.setItem("loginMode", "J");
              const base64String = store.state.authorization.split(".")[1];
              const base64 = base64String.replace(/-/g, "+").replace(/_/g, "/");
              const jsonPayload = decodeURIComponent(
                atob(base64).split("").map((c) => {
                  return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
                }).join("")
              );
              const mbr = JSON.parse(jsonPayload);
              store.commit("setMbrId", mbr.mbrId);
              store.commit("setMbrNm", mbr.mbrNm);
              store.commit("setRoles", mbr.roles);
          } else if (loginType === 'S') {
              store.commit("setLoginMode", "S");
              localStorage.setItem("loginMode", "S");
              const mbr = res.data;
              store.commit("setAuthorization", null);
              store.commit("setMbrId", mbr.mbrId);
              store.commit("setMbrNm", mbr.mbrNm);
              const roles = mbr.roles.map(r => ({ authority: r.authrtCd }));
              store.commit("setRoles", roles);
          } else {
              alert("알 수 없는 로그인 방식입니다.");
              return;
          }
          const isAdmin = store.state.roles.some(role => role.authority === "ROLE_ADMIN");
          let url = this.restoreRedirect("redirect");
          if (url != null && url != "") {
            const ctx = store.state.contextPath;
            if (ctx !== "") {
              // redirect 값에서 Context Path 추가
              url = this.$filters.ctxPath(url);
            } else {
              // redirect 값에서 기존 Context Path 제거
              url = url.replace(/^\/[^\/]+/, ""); // 첫 번째 '/' 이후의 경로만 남김
            }
            
            if (url == this.$filters.ctxPath("/searchId.page") || url == this.$filters.ctxPath("/resetPswd.page")) {
              this.$router.push({ path: this.$filters.ctxPath("/main.page") });
            } else {
              this.$router.push({ path: url });
            }
          } else {
            this.$router.push({
                path: isAdmin ? this.$filters.ctxPath("/adm/main.page") : this.$filters.ctxPath("/")
              });
          }

          
        }
      } catch (error) {
        alert(error.response.data.message);
      }
    },
    moveSearchId() {
      this.$router.push({
        path: this.$filters.ctxPath("/resetPswd.page"),
        query: {
          tab: "id",
        },
      });
    },
    moveResetPswd() { 
      this.$router.push({
        path: this.$filters.ctxPath("/resetPswd.page"),
        query: {
          tab: "pw",
        },
      });
    },
  },
  watch: {},
  computed: {},
  components: {},
  created() {
    this.checkAdminPage();
  },
  mounted() {},
};
</script>
