<!--
  Program: membership
  Author: SDL
  Brief: membership page
-->
<template>
  <div class="ui--wrapper fluid-width">
    <!-- GNB -->
    <header class="container-fluid fixed-top ui--header">
      <nav class="navbar navbar-expand-lg justify-content-between ui--top">
        <!--      <img :src="$CONTEXT + '/static/image/main/simbol.png'" class="ui--brand-simbol" :alt="$t('sdl.common.projectName')" />-->
        <!--      <router-link :to="{ name: 'mainIndexPage' }" tag="span" class="brand-text cursor-pointer">-->
        <!--        {{ $t('sdl.common.projectName') }}-->
        <!--      </router-link>-->
        <router-link :to="{ name: 'mainIndexPage' }" class="navbar-brand cursor-pointer" href="javascript:">
          <img :src="$CONTEXT + '/static/image/main/simbol.png'" class="ui--brand-simbol" :alt="$t('sdl.common.projectName')" />
          <span class="brand-text">{{ $t('sdl.common.projectName') }}</span>
        </router-link>
        <!--      <span class="brand-text">{{title}}</span>-->
      </nav>
    </header>
    <!-- SUB Layout -->
    <section class="ui--section-container">
      <!-- SUB Contents -->
      <div class="ui--content-wrapper">
        <div class="ui--content-heading">
          <strong>{{ $t('sdl.identity.label.userRegistration') }}</strong>
          <small>{{ $t('sdl.identity.label.userRegisInfo1') }}</small>
          <small class="text-danger">{{ $t('sdl.identity.label.userRegisInfo2') }}</small>
        </div>
        <!--Contents Area -->

        <div class="form-register">
          <h4 class="mb-3">
            {{ $t('sdl.identity.label.userInfo') }}
            <div class="float-end">
              <small class="ui--text-required">&#42; {{ $t('sdl.identity.label.mandatoryInputItem') }}</small>
            </div>
          </h4>
          <!-- <form class="form-horizontal" @submit.prevent=""> -->
          <div class="form-horizontal">
            <div class="row mb-3">
              <label class="col-2 col-form-label"> {{ $t('sdl.user.label.userName') }} <span class="ui--text-required">&#42;</span> </label>
              <div class="col-10">
                <input type="text" class="form-control" v-model.trim="userInfo.userName" v-validation="" errorMessage="sdl.identity.message.emptyName" />
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-2 col-form-label"> {{ $t('sdl.identity.label.company') }} <span class="ui--text-required">&#42;</span> </label>
              <div class="col-10">
                <input type="text" class="form-control" v-model.trim="userInfo.companyName" v-validation="" errorMessage="sdl.identity.message.emptyCompany" />
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-2 col-form-label"> {{ $t('sdl.identity.label.project') }} <span class="ui--text-required">&#42;</span> </label>
              <div class="col-10">
                <input type="text" class="form-control" v-model.trim="userInfo.description" v-validation="" errorMessage="sdl.identity.message.emptyProject" />
              </div>
            </div>
            <hr />
            <div class="row mb-3">
              <label class="col-2 col-form-label">ID <span class="ui--text-required">&#42;</span></label>
              <div class="col-10">
                <div class="input-group">
                  <input type="text" class="form-control" placeholder="" v-model.trim="userInfo.userId" @keyup="userIdDupCheck = false" v-validation="" errorMessage="sdl.identity.message.emptyId" />
                  <button class="btn btn-outline-secondary" type="button" @click="checkId()">
                    {{ $t('sdl.identity.label.checkDup') }}
                  </button>
                </div>
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-2 col-form-label"> {{ $t('sdl.identity.label.password') }} <span class="ui--text-required">&#42;</span> </label>
              <div class="col-10">
                <input type="password" class="form-control" v-model.trim="userInfo.password" v-validation="" errorMessage="sdl.identity.message.emptyPasswd" />
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-2 col-form-label"> {{ $t('sdl.identity.label.confirmPwd') }} <span class="ui--text-required">&#42;</span> </label>
              <div class="col-10">
                <input type="password" class="form-control" v-model.trim="password2" v-validation="" errorMessage="sdl.identity.message.emptyConfirmPasswd" />
                <div>{{ $t('sdl.identity.message.invalidPassword.alphaNumeric') }}</div>
              </div>
            </div>
            <hr />
            <div class="row mb-3">
              <label class="col-2 col-form-label"> {{ $t('sdl.identity.label.email') }} <span class="ui--text-required">&#42;</span></label>
              <div class="col-10">
                <div class="input-group">
                  <input type="text" class="form-control" placeholder="" v-model.trim="emailId" @keyup="emailDupCheck = false" v-validation="" errorMessage="sdl.identity.message.emptyEmail" />
                  <div class="input-group-text">@</div>
                  <input type="text" class="form-control" placeholder="" v-model.trim="emailDomain" :disabled="emailDomainSelect !== ''" @keyup="emailDupCheck = false" />
                  <select
                    class="form-select"
                    v-model="emailDomainSelect"
                    @change="
                      emailDomain = emailDomainSelect;
                      emailDupCheck = false;
                    "
                  >
                    <option value="">{{ $t('sdl.identity.label.directInput') }}</option>
                    <option v-for="(item, index) in emailList" :value="item" :key="index">{{ item }}</option>
                  </select>
                  <button class="btn btn-outline-secondary ms-2" type="button" @click="checkEmail()">
                    {{ $t('sdl.identity.label.checkDup') }}
                  </button>
                </div>
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-2 col-form-label">{{ $t('sdl.identity.label.phoneNumber') }}</label>
              <div class="col-10"><input type="text" class="form-control" v-model.trim="userInfo.mobile" /></div>
            </div>
            <button class="btn btn-lg btn-primary d-block w-100" type="submit" @click="confirm()">
              {{ $t('sdl.identity.label.submit') }}
            </button>
          </div>
          <!-- </form> -->
        </div>

        <!--//Contents Area -->
      </div>
    </section>

    <!-- Footer -->
    <footer class="ui--footer-container">
      <div class="ui--footer-in">
        <span>&copy; Samsung</span>
      </div>
    </footer>
  </div>
</template>

<script>
import axios from 'axios';
import { SDLUtil, StringUtil } from '@/utils';

export default {
  data() {
    return {
      userInfo: {},
      passwordCheck: false,
      password2: '',
      emailId: '',
      emailDomain: '',
      emailDomainSelect: '',
      userIdDupCheck: false,
      emailList: ['samsung.com', 'gmail.com'],
      emailDupCheck: false,
    };
  },
  created() {
    if (document.querySelector('body').classList.contains('ui--login-wrap')) document.querySelector('body').classList.remove('ui--login-wrap');
    if (document.querySelector('body').classList.contains('sdl-wrap')) document.querySelector('body').classList.remove('sdl-wrap');
    document.querySelector('body').classList.add('register-wrap');
    this.userInfo = {
      userName: '',
      companyName: '',
      description: '', // project name
      userId: '',
      password: '',
      email: '',
      mobile: '',
    };
  },
  methods: {
    checkId() {
      if (this.userInfo.userId === '') {
        SDLUtil.alert('sdl.identity.message.emptyId');
        return;
      }

      SDLUtil.showLoadingBar(true);
      axios
        .get(`${SDLUtil.API_URL}/auth/noauth/${this.userInfo.userId}/dup-check`)
        .then(({ data }) => {
          if (data) {
            SDLUtil.alert('sdl.identity.message.inuseAlreadyID');
            this.userIdDupCheck = false;
          } else {
            SDLUtil.alert('sdl.identity.message.availableID');
            this.userIdDupCheck = true;
          }
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
    },
    checkEmail() {
      if (this.emailId === '' || this.emailDomain === '') {
        SDLUtil.alert('sdl.identity.message.emptyEmail');
        return;
      }

      SDLUtil.showLoadingBar(true);
      axios
        .get(`${SDLUtil.API_URL}/auth/noauth/email/dup-check`, {
          params: {
            email: `${this.emailId}@${this.emailDomain}`,
          },
        })
        .then(({ data }) => {
          if (data) {
            SDLUtil.alert('sdl.identity.message.inuseAlreadyEmail');
            this.emailDupCheck = false;
          } else {
            SDLUtil.alert('sdl.identity.message.availableEmail');
            this.emailDupCheck = true;
          }
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
    },
    confirm() {
      // console.info('회원가입', this.userInfo);
      // validation
      if (SDLUtil.onSubmitValidation()) return;

      if (this.userInfo.userName === '' || this.userInfo.companyName === '' || this.userInfo.description === '' || this.userInfo.userId === '' || this.userInfo.password === '') {
        SDLUtil.alert('sdl.department.message.requiredValue');
        return;
      }

      if (this.userInfo.password !== this.password2) {
        SDLUtil.alert('sdl.identity.message.invalidPassword.notMatch');
        return;
      }

      if (this.userIdDupCheck === false) {
        SDLUtil.alert('sdl.identity.message.requireDupID');
        return;
      }

      if (this.emailDupCheck === false) {
        SDLUtil.alert('sdl.identity.message.requireDupEmail');
        return;
      }

      const params = {
        ...this.userInfo,
        email: `${this.emailId}@${this.emailDomain}`,
      };

      SDLUtil.showLoadingBar(true);

      const formData = new FormData();
      formData.append('id', this.userInfo.userId);
      formData.append('password1', this.userInfo.password);

      // 비밀번호 체크
      axios
        .post(`${SDLUtil.API_URL}/auth/noauth/passwd/rule-check`, formData)
        .then(() => {
          // 사용자 등록
          this.userReg(params);
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
    },
    userReg(params) {
      axios
        .post(`${SDLUtil.API_URL}/auth/noauth/user-reg?${StringUtil.queryStringfy(params)}`)
        .then(() => {
          SDLUtil.showLoadingBar(false);

          SDLUtil.alert({
            msg: 'sdl.login.success',
            onOkEvt: () => {
              this.$router.push({ name: 'login', query: { userId: this.userInfo.userId } });
            },
          });
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
    },
  },
};
</script>

<style scoped></style>
