<template>
  <div>
    <el-form :model="ruleForm" :rules="rules" ref="form" @submit.native.prevent>
      <el-form-item prop="account">
        <el-input
          v-model="ruleForm.account"
          :placeholder="$t('loginPwd.account.placeholder')"
          @keyup.enter.native="handleSubmit"
        >
          <i slot="prefix" class="el-input__icon el-icon-user"></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          type="password"
          v-model="ruleForm.password"
          :placeholder="$t('loginPwd.password.placeholder')"
          @keyup.enter.native="handleSubmit"
        >
          <i slot="prefix" class="el-input__icon el-icon-lock"></i>
        </el-input>
      </el-form-item>
      <el-checkbox v-model="ruleForm.RememberMe" style="margin-bottom: 10px">{{ $t('login.rememberMe') }}</el-checkbox>
      <el-button type="primary" class="submit-button" :loading="loading" @click="handleSubmit">
        {{ $t('login.submitText') }}
      </el-button>
    </el-form>
    <div class="login-footer">
      <router-link to="code">{{ $t('login.codeLogin') }}</router-link>
      <router-link to="../password">{{ $t('login.forgetPassword') }}</router-link>
    </div>
  </div>
</template>

<script>
import * as api from '@/api/account'

export default {
  name: 'LoginAccount',
  data() {
    return {
      ruleForm: { type: 1, account: '', password: '', RememberMe: false, service: 'https://h5.ezijing.com' },
      rules: {
        account: [{ required: true, message: this.$t('loginPwd.account.rule'), trigger: 'change' }],
        password: [{ required: true, message: this.$t('loginPwd.password.rule'), trigger: 'change' }]
      },
      loading: false
    }
  },
  computed: {
    // 重定向地址
    nextUrl() {
      const nextUrl = window.sessionStorage.getItem('next_url')
      return nextUrl ? decodeURIComponent(nextUrl) : ''
    }
  },
  methods: {
    // 提交
    handleSubmit() {
      this.$refs.form.validate().then(this.handleRequest)
    },
    // 接口请求
    handleRequest() {
      this.loading = true
      api.login(this.ruleForm).then(response => {
        response.code === 0 ? this.handleSuccess(response) : this.$message.error(response.msg)
        this.loading = false
      })
    },
    // 登录成功
    handleSuccess(response) {
      this.$message({ type: 'success', message: this.$t('loginPwd.successMessage') })
      if (this.nextUrl) {
        window.location.href = this.nextUrl
      } else {
        this.$emit('success', response)
      }
    }
  }
}
</script>
