<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");
              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') {
              // 세션 방식 (서버에서 따로 body에 사용자 정보 내려줘야 함)
              store.commit("setLoginMode", "S");
              const mbr = res.data;
              store.commit("setAuthorization", null);
              store.commit("setMbrId", mbr.mbrId);
              store.commit("setMbrNm", mbr.mbrNm);
              store.commit("setRoles", mbr.roles);
          } else {
              alert("알 수 없는 로그인 방식입니다.");
              return;
          }
          const url = this.restoreRedirect("redirect");
          if (url != null && url != "") {
            if (url == "/searchId.page" || url == "/resetPswd.page") {
              this.$router.push({ path: "/main.page" });
            } else {
              this.$router.push({ path: url });
            }
          } else {
            this.$router.push({ path: "/" });
          }

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