<template>
  <div class="main">
    <a-form-model
      ref="ruleForm"
      class="user-layout-login"
      :model="form"
      :rules="rules"
      @submit.prevent="handleSubmit"
    >
      <a-form-model-item>
        <a-select v-model="form.roleCode" placeholder="请选择">
          <a-select-option value="student">学员</a-select-option>
          <a-select-option value="platform_manager">管理员</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item>
        <a-input size="large" v-model="form.username" placeholder="请输入用户名">
          <a-icon slot="prefix" type="user" style="color:rgba(0,0,0,.25)" />
        </a-input>
      </a-form-model-item>
      <a-form-model-item>
        <a-input-password size="large" v-model="form.password" placeholder="请输入密码">
          <a-icon slot="prefix" type="lock" style="color:rgba(0,0,0,.25)" />
        </a-input-password>
      </a-form-model-item>
      <a-form-model-item>
        <a-button block type="primary" size="large" html-type="submit" :loading="loading">
          登录
        </a-button>
      </a-form-model-item>
      <a-form-model-item style="text-align: center;">
        <a-button @click="handlerRegister" type="link">
          注册
        </a-button>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'

export default {
  data () {
    return {
      form: {
        username: '',
        password: '',
        roleCode: 'student'
      },
      rules: {
        username: [{ required: true, message: '请输入用户名' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        roleCode: [{ required: true, message: '请输入密码', trigger: 'change' }]
      },
      loading: false
    }
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    handleSubmit () {
      if (this.loading) {
        return false
      }
      this.loading = false
      this.$refs.ruleForm.validate(valid => {
        const { form } = this
        if (valid) {
          this.Login(form).then(
            () => {
              this.loginSuccess()
            },
            () => {
              this.requestFailed()
            }
          )
        } else {
          this.loading = false
          return false
        }
      })
    },
    handlerRegister () {
      this.$router.push({
        path: '/user/register'
      })
    },
    loginSuccess (res) {
      this.loading = false
      this.$router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
    },
    requestFailed () {
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped></style>
