<template>
    <el-form class="form" ref="form" :model="form" label-position="top">
        <div class="item">
            <el-input :class="{'is-error': serverError.email}" v-model="form.email" placeholder="用户名"></el-input>
            <div class="error-message" v-show="serverError.email">
                {{ serverError.email }}
            </div>
        </div>
        <div class="item">
            <el-input :class="{'is-error': serverError.password}" type="password" v-model="form.password" placeholder="密码"></el-input>
            <div class="error-message" v-show="serverError.password">
                {{ serverError.password }}
            </div>
        </div>
        <el-form-item>
            <el-button type="primary" @click="onSubmit" style="width: 100%;">登录</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
import MenuMixin from '../mixins/menu'
import { mapMutations } from 'vuex'
import authAPI from '../api/auth'

export default {
    mixins: [
        MenuMixin
    ],
    watch: {
        'form.email' (newVal) {
            if (newVal) {
                this.serverError.email = ''
            }
        },
        'form.password' (newVal) {
            if (newVal) {
                this.serverError.password = ''
            }
        } 
    },
    data () {
        return {
            form: {
                email: '',
                password: ''
            },
            serverError: {
                email: '',
                password: ''
            }
        }
    },
    methods: {
        ...mapMutations('basics', [
            'setToken'
        ]),
        onSubmit () {
            let error = false
            if (!this.form.email) {
                this.serverError.email = '请输入邮箱！'
                error = true
            }
            if (!this.form.password) {
                this.serverError.password = '请输入密码！'
                error = true
            }
            if (error) {
                return false
            }
            authAPI.login(this.form, data => {
                const { token, redirect } = data
                this.setToken(token)
                if (this.$route.query.redirect) {
                    this.$router.push(this.$route.query.redirect)
                } else {
                    this.$router.push(redirect)
                }
            }, error => {
                if (error.message) {
                    this.serverError.email = error.message
                }
            })
        }
    }
}
</script>

<style lang="less" scoped>
.form {
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
    width: 320px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -230px;
    margin-top: -163px;
    .item {
        margin: 20px 0;
    }
    .error-message {
        color: #F56C6C;
        font-size: 12px;
        line-height: 1;
        padding-top: 4px;
    }
}
</style>