<template>
  <div class="login-page">
    <div class="login-wrap flex-column justify-center align-center">
      <div class="login-content">
        <div class="logo">
          <img src="../../../resources/img/logo.png" alt="" />
        </div>
        <div class="login-zone">
          <div class="input-wrap">
            <div class="inputContainer">
              <input required="" class="customInput" type="text" v-model="member.userId" v-on:keyup.enter="login" />
              <label class="inputLabel">ID</label>
              <div class="inputUnderline"></div>
            </div>
            <div class="inputContainer">
              <input required="" class="customInput" type="password" v-model="member.userPassword" v-on:keyup.enter="login" />
              <label class="inputLabel">PASSWORD</label>
              <div class="inputUnderline"></div>
            </div>
          </div>
        </div>
        <button class="blue-btn large-btn mt20" @click="login">로그인</button>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import { useStore } from "vuex";
import store from "../AppStore";

export default {
  data() {
    return {
      member: {
        userId: null,
        userPassword: null,
      },
      store: useStore(),

      // 서비스워커 파일 경로
      serviceWorkerFilePath: "client/views/pages/push/service-worker.js",

      vapidPublicKey:
        "BIutPAvTT3p5sd6ulWCKmnGrEqIEOhU-8aZfWtBA_Ks9t_MG4a1WzXGe0QDh1nOqwxycYdymKE2bNm3lP0xG8CU",
      privateKey: "oiIhTnhQ0J-IO2a-ziuwqS-Vg8FYg07oiCMrF8YV9CE",
      // 서비스워커 정보
      registration: null,
      // 알림 구독 정보
      subscription: null,
      // 구독 버튼 텍스트
      subscriptionBtnText: null,
      // 알림 구독 취소 정보
      unsubscribed: null,
    };
  },
  methods: {
    // 모달 샘플
    getPostList: async function () {
      alert(await this.$showConfirm("메세지 타이틀", "메세지를 입력하세요"));
    },
    // 로그인 처리
    login: function () {
      var vm = this;
      axios({
        url: "/login.json",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: vm.member,
      })
        .then(async function (response) {
          await vm.$showAlert("메세지", response.data.checkMessage.message);
          if (response.data.checkMessage.status > 0) {
            store.commit(
              "setLoginUser",
              response.data.resultData.LoginUserInfo
            );
            vm.$router.push({ path: "/fileManagement.page", query: {} });
            await vm.requestPermission(); // 구독 요청
          }
        })
        .catch(function (error) {
          this.$showAlert(
            "에러 발생",
            "에러가 발생했습니다. 관리자에게 문의해 주세요."
          );
        });
    },

    // 서비스워커 등록
    registerServiceWorker: async function () {
      if ("serviceWorker" in navigator) {
        // 웹 브라우저가 서비스워커 기능을 지원하는지
        try {
          this.registration = await navigator.serviceWorker.register(
            this.serviceWorkerFilePath
          ); // 서비스워커 등록
          if (this.registration) {
            this.subscription =
              await this.registration.pushManager.getSubscription(); // 구독 정보 가져오기
          }
        } catch (e) {
          console.error(e.message);
        }
      } else {
        console.error("Service Worker in navigator error");
      }
    },

    // 권한 요청
    requestPermission: async function () {
      try {
        // const registrations = navigator.serviceWorker.ready;
        this.subscription =
          await this.registration.pushManager.getSubscription(); // 요청 전 구독 정보 조회
        if (!this.subscription) {
          // 구독이 되어있지 않으면 구독하기
          const subscribeInfo = await this.registration.pushManager.subscribe({
            userVisibleOnly: true,
            applicationServerKey: this.vapidPublicKey,
          });
          // TODO: DB에 구독 정보 보내기
          await this.userPushTokenInsert(subscribeInfo.toJSON());
        }
      } catch (e) {
        console.error(e.message);
      } finally {
        this.subscription =
          await this.registration.pushManager.getSubscription(); // 요청 후 구독 정보 조회
      }
    },

    async userPushTokenInsert(token) {
      const vm = this;

      axios({
        url: "/push/userPushTokenInsert",
        method: "post",
        headers: {
          "Content-Type": "application/json; charset=UTF-8",
        },
        data: {
          userId: store.state.loginUser.LoginUserInfo["user_id"],
          userToken: token,
          tokenState: "Y",
        },
      })
        .then(function (response) {
          vm.user = response.data;
        })
        .catch(function (error) {
          alert("웹 푸시 토큰 등록에 오류가 발생했습니다.");
        });
    },
  },

  created() {
    const vm = this;
    axios({
      url: "/getLoginInfo.json",
      method: "post",
      headers: { "Content-Type": "application/json; charset=UTF-8" },
    })
      .then(function (response) {
        if (response.data.checkMessage.status > 0) {
          vm.$store.commit("setLoginUser", response.data.resultData.LoginUserInfo);

          let authList = vm.$store.state.loginUser.user_auth;
          console.log(authList)
          let userAdmAuthCheck = false;
          for (let auth of authList) {
            if (auth == "ROLE_ADMIN") {
              userAdmAuthCheck = true;
              break;
            }
          }
          if (userAdmAuthCheck) { // ROLE_ADMIN
            vm.$router.push({ path: "/fileManagement.page" });
          } else { // ROLE_ADMIN 외 모든 롤
            let userViewerAuthCheck = false;
            for (let auth of authList) {
              if (auth == "ROLE_VIEWER") {
                userViewerAuthCheck = true;
                break;
              }
            }
            if (userViewerAuthCheck) {
              vm.$router.push({ path: "/openApiList.page" });
            } else {
              vm.$router.push({ path: "/customSelectList.page" });
            }
          }
        }
      })
      .catch(function (error) {
        vm.$showAlert("에러 발생", "에러가 발생했습니다. 관리자에게 문의해 주세요.");
      });
  },
  mounted() {
    this.registerServiceWorker();
  },
};
</script>
<style scoped>
.login-page {
  width: 100%;
  height: 100%;
}

.login-content {
  min-width: 400px;
  max-width: 400px;
  padding: 30px;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0 0 20px #ddd;
}

.logo {
  width: 200px;
  /* height: 50px; */
  margin: 0 auto;
  margin-bottom: 50px;
}

.logo>img {
  display: block;
  height: 100%;
  margin: auto;
}

.inputContainer {
  position: relative;
  margin-bottom: 40px;
}

.inputContainer:last-child {
  margin-bottom: 0;
}

.customInput {
  width: 100%;
  padding: 10px;
  font-size: 13px;
  background-color: transparent;
  border: none;
  outline: none;
  transition: border-color 0.3s ease;
}

.inputLabel {
  position: absolute;
  top: 0;
  left: 0;
  pointer-events: none;
  padding: 5px;
  font-size: 13px;
  color: #eee;
  transform: translateY(-80%);
}

.inputUnderline {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #eee;
}

.found-zone {
  padding: 20px 0;
}

.found-zone>a {
  font-size: 1.3rem;
  padding: 0 10px;
}

.login-page .blue-btn {
  margin-left: 0;
  padding: 10px 0;
}
</style>