<!--
  Program: Login page
  Author: SDL
  Brief: User login page
-->
<template>
  <template v-if="isLoaderVisible">
    <div class="sdl-center wd-3">
      <!-- message box -->
      <div class="msg-box">
        <div class="msg-icon"><i class="bi bi-info-circle text-warning icon-size-48"></i></div>
        <div class="msg-text">
          <h3 class="mb-4">Information Message</h3>
          <strong class="d-block mb-3">{{ $t('sdl.common.message.initLoadingMsg') }}</strong>
          <ol class="list-unstyled">
            <li>{{ $t('sdl.common.message.browserInfo1') }}</li>
            <li>{{ $t('sdl.common.message.browserInfo2') }}</li>
            <li>{{ $t('sdl.common.message.browserInfo3') }}</li>
            <li>{{ $t('sdl.common.message.browserInfo4') }}</li>
          </ol>
        </div>
      </div>
      <!-- //message box -->
    </div>
  </template>
  <template v-else-if="errorState.code !== '196'">
    <form class="ui--form-login" @submit.prevent @keyup.enter="handleSubmit">
      <header class="mb-4">
        <img :src="$CONTEXT + '/static/image/main/simbol.png'" class="mb-3 ui--brand-simbol" alt="System Simbol" />
        <span class="brand-text">{{ title }}</span>
      </header>

      <label for="inputID" class="visually-hidden-focusable">{{ $t('sdl.identity.label.id') }}</label>
      <input type="text" v-model="userId" id="inputID" class="form-control ui--login-id" :placeholder="$t('sdl.identity.label.id')" required autofocus @keyup.enter.stop="$refs.inputPassword.focus()" />
      <label for="inputPassword" class="visually-hidden-focusable">{{ $t('sdl.identity.label.password') }}</label>
      <input type="password" v-model="password" id="inputPassword" ref="inputPassword" autocomplete="true" class="form-control ui--login-pass" :placeholder="$t('sdl.identity.label.password')" required />
      <div class="checkbox mb-4">
        <label><input type="checkbox" v-model="rememberMe" /> Remember ID</label>
      </div>
      <button class="btn btn-lg btn-primary d-block w-100 mb-2" type="button" @click="handleSubmit()">Login</button>
      <button class="btn btn-lg btn-outline-secondary d-block w-100 mb-2" type="button" @click="loginByAd()">AD SSO Login</button>
      <button class="btn btn-lg btn-outline-secondary d-block w-100" type="button" @click="loginByNewEpTray()">New EpTray Login</button>
      <p class="mt-3">
        <router-link :to="$CONTEXT + '/register'">{{ $t('sdl.common.label.membership') }}</router-link>
        <span class="slide me-2 ms-2">|</span>
        <router-link :to="$CONTEXT + '/initPassword'">{{ $t('sdl.common.label.initPassword') }}</router-link>
      </p>
    </form>
  </template>
  <div class="ui--form-login login-info" v-else>
    <header class="mb-4">
      <img :src="$CONTEXT + '/static/image/main/simbol.png'" class="mb-3 ui--brand-simbol" alt="System Simbol" />
      <span class="brand-text">{{ title }}</span>
    </header>
    <hr class="mb-4" />
    <div class="message">
      <p v-html="$t('sdl.common.label.selectRole')"></p>
      <div class="file-list mb-3">
        <ul>
          <li v-for="(role, index) in roleList" :key="index">
            <div class="form-check text-left">
              <label class="form-check-label"><input type="checkbox" class="form-check-input" v-model="role.selected" /> {{ role.roleName }}</label>
            </div>
          </li>
        </ul>
        <!-- // file-list -->
      </div>
    </div>

    <button class="btn btn-lg btn-primary" type="button" @click="signonReg">
      {{ $t('sdl.identity.label.userRegistration') }}
    </button>
  </div>

  <!-- Footer -->
  <footer class="ui--footer-container">
    <template v-if="isLoaderVisible">
      <div class="ui--footer-in">
        <span>&copy; Samsung</span>
      </div>
    </template>
    <template v-else>
      <p class="text-muted">
        {{ $t('sdl.common.message.onlyAuthUserLegalSanctions') }}
      </p>
      <span>&copy; Samsung</span>
    </template>
  </footer>
</template>
<script>
import { mapActions, mapGetters } from 'vuex';
import axios from 'axios';
import SDLUtil from '@/utils/SDLUtil';
import loginService from '@/service/loginService';

export default {
  data() {
    return {
      title: SDLUtil.getMsgProp('sdl.common.projectName'),
      userId: 'admin',
      password: '!QAZxsw23edc',
      rememberMe: false,
      submitted: false,
      roleList: [],
      isLoaderVisible: true,
      websocket: null,
      newEpTrayKey: null,
    };
  },
  methods: {
    ...mapActions(['login', 'logout', 'loginNewEpTray']),
    async handleSubmit() {
      // SDLUtil.alert({ msg: 'sdp.currency.exchRate.gdatu' });
      this.submitted = true;
      const { userId, password } = this;
      if (userId && password) {
        const loginResult = await this.login({ userId: this.userId, password: this.password });
        this.afterLoginProcess(loginResult);
      }
    },
    loginByAd() {
      const redirect = this.$route.query.redirect || '';
      if (redirect) {
        window.location.href = `${SDLUtil.API_URL}/noauth/saml-request?redirect=${redirect}`;
      } else {
        window.location.href = `${SDLUtil.API_URL}/noauth/saml-request`;
      }
    },
    async loginByNewEpTray() {
      let loginResult = false;
      SDLUtil.showLoadingBar(true);
      await this.socConnect()
        .then(data => {
          this.newEpTrayKey = data;
          this.websocket.close();
        })
        .catch(err => {
          SDLUtil.alert(err);
        });
      SDLUtil.showLoadingBar(false);

      if (this.newEpTrayKey) {
        if (this.newEpTrayKey.result === 'success') {
          const { userInfo, key } = this.newEpTrayKey;
          loginResult = await this.loginNewEpTray({ userInfo, key });
        } else {
          SDLUtil.alert(`sdl.epTray.error.${this.newEpTrayKey.errorCode}`);
        }
      }

      if (!loginResult) {
        if (this.$route.query.token) {
          loginService.setToken(this.$route.query.token);
          document.location = `${SDLUtil.WEB_CONTEXT_PATH}/`;
        }
      }
      this.afterLoginProcess(loginResult);
    },
    afterLoginProcess(loginResult) {
      // console.log('LoginPage:', loginResult);
      if (loginResult) {
        // console.log('userInfo:', SDLUtil.getLoginedUserInfo());
        // this.$store.commit('ERROR_STATE', { code: 'authOk' });
        if (this.rememberMe) {
          localStorage.setItem('rememberMe', 'true');
          localStorage.setItem('rememberId', this.userId);
        } else {
          localStorage.removeItem('rememberMe');
          localStorage.removeItem('rememberId');
        }
        this.gotoMain();
      }
    },
    gotoMain() {
      // this.$router.push({
      //   path: '/',
      // });
      // Do not use the router, because you need to bring the menu dynamically, reload it again with a token
      const redirect = this.$route.query.redirect || '';
      if (redirect) {
        window.location.href = `${this.$CONTEXT}/?redirect=${redirect}`;
      } else {
        window.location.href = `${this.$CONTEXT}/`;
      }
    },
    getRoleList() {
      axios
        .get(`${SDLUtil.API_URL}/auth/noauth/roles`)
        .then(({ data }) => {
          // console.log(data);
          this.roleList = data;
        })
        .catch(err => {
          console.error(err);
        });
    },
    signonReg() {
      const chkRoleList = [];
      this.roleList.forEach(role => {
        if (role.selected) chkRoleList.push(role.roleName);
      });
      if (chkRoleList.length === 0) {
        SDLUtil.alert('sdl.common.message.checkRoleUser');
        return;
      }
      axios
        .post(`${SDLUtil.API_URL}/auth/noauth/user-reg-integration?roleList=${encodeURIComponent(chkRoleList.join(','))}&jwtData=${encodeURIComponent(this.errorState.message)}`)
        // eslint-disable-next-line no-unused-vars
        .then(({ response }) => {
          this.$store.commit('ERROR_STATE', {
            code: '191',
            reason: SDLUtil.getMsgProp('sdl.auth.message.user.waiting'),
          });
        })
        .catch(err => {
          console.error(err);
          SDLUtil.errorAlert(err);
        });
    },
    socConnect() {
      return new Promise((resolve, reject) => {
        const server = new WebSocket('wss://localhost:29283');
        this.websocket = server;
        server.onopen = () => {
          server.send('{"rqtype":"getknoxsso","token":"","data":"KCC60TRAY0072"}');
          server.onmessage = event => {
            const socketData = JSON.parse(event.data);
            if (socketData.rpcode === 'RETURN_SUCCESS') {
              resolve(JSON.parse(socketData.data));
            } else {
              this.websocket.close();
              let err;
              if (socketData.rpcode === 'EMPTY_BOX') err = 'sdl.epTray.rpCode.EMPTY_BOX';
              else err = `sdl.epTray.rpCode.${socketData.detail}`;
              reject(err);
            }
          };
        };
        server.onerror = () => {
          const err = 'sdl.epTray.rpCode.CONNECTION_FAILED';
          reject(err);
        };
      });
    },
  },
  watch: {
    errorState() {
      if (this.errorState.code === '196') {
        this.isLoaderVisible = false;
        this.getRoleList();
        // } else if (this.errorState.code === '191') {
        //   SDLUtil.alert(this.errorState.reason);
      } else if (this.errorState.code !== 'authOk') {
        if (this.errorState.code === '185' || this.errorState.code === '190') {
          this.isLoaderVisible = false;
          SDLUtil.alert(this.errorState.reason);
        } else {
          document.location = `${SDLUtil.WEB_CONTEXT_PATH}/error?code=${this.errorState.code}`;
        }
      }
    },
    isLoaderVisible() {
      if (this.isLoaderVisible) {
        document.querySelector('body').classList.add('sdl-wrap');
      } else {
        document.querySelector('body').classList.remove('sdl-wrap');
      }
    },
  },
  computed: {
    ...mapGetters({
      errorState: 'getErrorState',
    }),
  },
  created() {
    document.querySelector('body').classList.add('ui--login-wrap');
    document.querySelector('body').classList.add('sdl-wrap');

    // this.logout();
    const rememberMe = localStorage.getItem('rememberMe');
    if (rememberMe === 'true') {
      this.rememberMe = true;
      this.userId = localStorage.getItem('rememberId');
    }

    // for AdLogin RegistrationException
    if (this.$route.query.code) {
      this.$store.commit('ERROR_STATE', {
        code: this.$route.query.code,
        message: this.$route.query.message,
      });
    }
  },
  mounted() {
    if (SDLUtil.isLogin()) {
      this.gotoMain();
    } else if (this.$route.query.token) {
      loginService.setToken(this.$route.query.token);
      this.gotoMain();
    } else {
      this.isLoaderVisible = false;
    }

    if (this.$route.query.userId) {
      // Automatically enter the ID you entered when you passed the membership registration
      this.password = '';
      this.userId = this.$route.query.userId;
    }
  },
};
</script>
