<template>
  <zpa-form class="LoginForm">
    <zpa-form-group title="登录信息">
      <zpa-text-input
          label="用户名"
          v-model="user.username"
      />
      <zpa-text-input
          label="密码"
          type="password"
          password
          v-model="user.password"
      />
      <p class="ErrorMessage" v-if="error">
        {{error}}
      </p>
      <Button
          :loading="loading"
          type="primary"
          long
          @click="doLogin"
      >登录</Button>
    </zpa-form-group>
  </zpa-form>
</template>

<script>
import { mapMutations } from 'vuex'
import { login } from '@centit/api-auth'

export default {
  name: 'LoginForm',

  data () {
    return {
      user: {},

      error: '',

      loading: false,
    }
  },

  computed: {
    lastRoute () {
      const defaultRoute = {
        name: 'Home',
      }
      if (this.$router.$lastRoute && this.$router.$lastRoute.name === 'Login') {
        return defaultRoute
      }
      return this.$router.$lastRoute || {
        name: 'Home',
      }
    },
  },

  methods: {
    ...mapMutations('core', [
      'setToken',
      'setLoginInfo',
    ]),

    checkForm () {
      const {
        username,
        password,
      } = this.user

      if (!username) {
        this.error = '用户名不能为空'
        return false
      } else if (!password) {
        this.error = '密码不能为空'
        return false
      } else {
        this.error = ''
      }

      return true
    },
    doLogin (e) {
      e.preventDefault()
      if (!this.checkForm()) return

      this.loading = true
      login(this.user)
        .then(({ accessToken, userInfo }) => this.afterLogin(accessToken, userInfo))
        .catch(e => {
          this.error = e.message
        })
        .finally(() => {
          this.loading = false
        })
    },
    afterLogin (token, info) {
      this.setToken(token)
      this.setLoginInfo(info)
      this.$router.replace(this.lastRoute)
        .then(() => {
          this.$router.$lastRoute = null
        })
    },
  },
}
</script>

<style scoped lang="less">
.LoginForm {
  width: 360px;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 16px 32px;
  margin: 0 auto;

  .ErrorMessage {
    width: 100%;
    height: 32px;
    line-height: 32px;
    padding: 0 4px;
    color: firebrick;
  }
}

</style>
