<!-- loginModal -->
<template>
<b-modal id="loginModal" title="登 陆">
    <template v-slot:modal-title>
    <div class="align-center"><i class="fa fa-id-card" aria-hidden="true"></i> Login</div>
    </template>
    <b-form @submit.prevent="submitLogin()">
        <b-form-group label="账号：" label-for="input-2"  label-cols-sm="2">
        <b-form-input
        id="input-user"
        v-model="login.account"
        required
        placeholder="Enter account"
        >
        </b-form-input>
    </b-form-group>

    <b-form-group label="密码：" label-for="input-password" label-cols-sm="2" >
        <b-form-input
        id="input-password"
        v-model="login.password"
        type="password"
        required
        placeholder="Enter password"
        ></b-form-input>
        <b-form-invalid-feedback :state="login.isRight">
        <b-icon icon="x-octagon-fill"></b-icon>&nbsp;{{login.errorMessage}}
        </b-form-invalid-feedback>
    </b-form-group>
    <div class="text-center">
        <b-button type="reset" variant="danger" >重置</b-button>
        <b-button type="submit" variant="primary">提交</b-button>
    </div>
    </b-form>
        <template v-slot:modal-footer>
    <b-button type="reset" variant="secondary" @click="$bvModal.hide('loginModal')">关闭</b-button>
    </template>
</b-modal>
</template>

<script>
import cookie from '../../../static/js/cookieJS'

export default {
  name: 'LoginCard',

  data: () => ({
    // 登陆表单
    login: {
      account: '',
      password: '',
      isRight: true,
      errorMessage: '账号或密码输入错误'
    }
  }),

  methods: {
    /**
    * @description: loginModel提交(submit)事件
    * @returns {void}
     */
    submitLogin: function (e) {
      var that = this
      this.postLoginForm()
        .then(res => {
          if (res) {
            // 登陆成功，设置登陆状态
            that.$store.commit('userLogin', {
              name: res.name,
              uid: res.uid
            })

            // 设置token到cookie
            cookie.setCookie(res.token, 0.5, 'token')

            // 隐藏modal
            that.$bvModal.hide('loginModal')
          } else {
            that.login.isRight = false
          }
        })
    },
    /**
     * @description:向后端提交登陆表单
     * @returns {void}
     */
    postLoginForm: async function () {
      var response

      await this.$axios
        .post('admin/login', {
          form: {
            account: this.login.account,
            password: this.login.password
          }
        })
        .then(res => {
          response = res.data
        })
      return response
    }
  }
}
</script>

<style scoped>
.loginModal{
  position: absolute;
  left: 50%;
}
</style>
