<template>
  <div style="width: 400px; height: 300px; text-align: center">
    <!-- 참조: https://bootstrap-vue.org/docs/reference/validation#form-validation , npm install vee-validate@3 필요 -->
    <validation-observer ref="observer" v-slot="{ handleSubmit }">
      <b-form @submit.stop.prevent="handleSubmit(onSubmit)" class="sm">
        <validation-provider
          :name="field.email.label"
          :rules="field.email.rules"
          v-slot="validationContext"
        >
          <b-input-group>
            <label class="input-group-text">{{ field.email.label }}</label>
            <b-form-input
              :name="field.email.key"
              :type="field.email.type"
              v-model="form.email"
              :state="getValidationState(validationContext)"
              :placeholder="field.email.placeholder"
            ></b-form-input>
            <b-form-invalid-feedback>{{
              validationContext.errors[0]
            }}</b-form-invalid-feedback>
          </b-input-group>
        </validation-provider>
        <validation-provider
          :name="field.password.label"
          :rules="field.password.rules"
          v-slot="validationContext"
        >
          <b-input-group>
            <label class="input-group-text">{{ field.password.label }}</label>
            <b-form-input
              :name="field.password.key"
              :type="field.password.type"
              v-model="form.password"
              :state="getValidationState(validationContext)"
              :placeholder="field.password.placeholder"
            ></b-form-input>
            <b-form-invalid-feedback>{{
              validationContext.errors[0]
            }}</b-form-invalid-feedback>
          </b-input-group>
        </validation-provider>
        <b-button type="submit" variant="primary">Login</b-button>
        <b-button type="reset" variant="danger" @click="onReset()"
          >Reset</b-button
        >
      </b-form>
    </validation-observer>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      form: {
        email: null,
        password: null
      },
      field: {
        email: {
          key: 'email',
          type: 'email',
          label: '로그인 메일',
          placeholder: 'sample@test.com',
          rules: { required: true, email: true }
        },
        password: {
          key: 'password',
          type: 'password',
          label: '로그인 암호',
          placeholder: 'password',
          rules: { required: true, min: 4, max: 20 }
        }
      }
    }
  },
  methods: {
    getValidationState({ dirty, validated, valid = null }) {
      return dirty || validated ? valid : null
    },
    async onSubmit() {
      const result = await this.callAPI('/auth/login', {
        email: this.form.email,
        password: this.form.password
      })
      console.log(result)
      if (!result) {
        console.log(result)
        sessionStorage.removeItem(process.env.VUE_APP_SESSIONSTORAGE_JWT_NAME)
        alert('로그인 실패...')
        //this.$router.back()
      } else {
        // localStorage를 사용하면, 브라우저에 key-value 값을 Storage에 저장할 수 있습니다
        sessionStorage.setItem(
          process.env.VUE_APP_SESSIONSTORAGE_JWT_NAME,
          result
        )
        alert('로그인 성공...')
        //저장된 redirect path를 이용 이동시킴
        this.$router.replace(
          sessionStorage.getItem(
            process.env.VUE_APP_SESSIONSTORAGE_REDIRECT_NAME
          ) || '/'
        )
        //저장된 정보 CLear
        this.onReset()
      }
    },
    onReset() {
      // Reset our form values
      this.form.email = ''
      this.form.pasword = ''
      //저장된 redirect path Clear
      sessionStorage.removeItem(
        process.env.VUE_APP_SESSIONSTORAGE_REDIRECT_NAME
      )
      // Trick to reset/clear native browser form validation state
      // this.$nextTick(() => {
      //   this.$refs.observer.reset()
      // })
    },
    async callAPI(url, params) {
      console.log('CallAPI..', [url, params])
      axios.defaults.baseURL = process.env.VUE_APP_AUTH_HOST
      //전송 Header에 추가
      const headers = {
        Authorization:
          'Bearer ' +
          sessionStorage.getItem(process.env.VUE_APP_SESSIONSTORAGE_JWT_NAME)
      }
      return await axios
        .post(url, params, headers)
        .then((response) => {
          // console.log(response)
          return response.status === 201 ? response.data : null
        })
        .catch((err) => {
          console.log(err)
          return null
        })
    }
  }
}
</script>
