<template>
  <el-row class="login content">
    <div class="logo">
      <img src="../../static/images/logo1.png" height="46" alt="">
      <h1>运维管理系统</h1>
    </div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="line-height: 36px;font-size:20px;">登录</span>
        <!-- <el-button style="float: right;" type="text">注册</el-button> -->
      </div>
      <el-form 
        ref="loginForm" 
        :model="loginForm" 
        :rules="rules" 
        label-width="120px">
        <el-form-item label="账户：" prop="name">
          <el-input v-model="loginForm.name" placeholder="输入登录用户名" autofocus @change="handleInputChange"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input type="password" 
          v-model="loginForm.password" 
          placeholder="请输入密码" 
          @keyup.native.enter="onSubmit('loginForm')"
          @change="handleInputChange"></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-checkbox label="记住账户" v-model="loginForm.remember"></el-checkbox>
        </el-form-item>
        <el-form-item class="buttons">
          <el-button 
            type="primary" 
            size="large" 
            class="submitBtn" 
            :loading="loginForm.loading" 
            @click="onSubmit('loginForm')" >
            {{ loginForm.submitText }}
          </el-button>
          <el-button type="text" @click="resetFields('loginForm')">重置</el-button>
        </el-form-item>
        <el-form-item v-if="loginForm.isSubmit" style="margin-bottom: 0;">
          <el-alert type="error" :title="loginForm.errorText" :closable="true" style="line-height: 1.2;" @close="loginForm.isSubmit = false"></el-alert>
        </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>

<script>
import Api from '../api/index.js'
import base64 from 'base-64'

export default {
  data() {
    return {
      loginForm: {
        name: '',
        password: '',
        remember: false,
        loading: false,
        isSubmit: false,
        errorText: '用户名或密码错误',
        submitText: '登录'
      },
      rules: {
        name: [
          {required: true, message: '请输入账户名称', trigger: 'change'}/* ,
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' } */
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'change'}/* ,
          { min: 3, max: 18, message: '长度在 3 到 18 个字符', trigger: 'blur' } */
        ]
      }
    }
  },
  mounted() {
    // this.$Progress.finish()
    const storage = window.localStorage

    if (storage.rememberNameOp) { // 本地存储登录用户名
      this.loginForm.remember = true
      this.loginForm.name = storage.rememberNameOp
    }

    if (storage.gisopUserInfo) { // 本地用户信息有存储信息
      let gisopUserInfo = JSON.parse(storage.gisopUserInfo),
          time = parseInt(gisopUserInfo.time),
          date = parseInt(gisopUserInfo.date)
      // console.log(time + date, Math.round(new Date().getTime()/1000))

      if ((time + date) >= Math.round(new Date().getTime() / 1000)) { // 判断是否过期
        this.$router.replace('/')
      }
    }
  },
  methods: {
    handleInputChange () {
      this.loginForm.isSubmit = false
    },
    onSubmit (formName) {
      // console.log(formName)
      this.$refs[formName].validate((valid) => {
        this.loginForm.isSubmit = false
        if (valid) {
          this.loginForm.loading = true

          let psw = base64.encode(this.loginForm.password),
              uName = this.loginForm.name.replace(/\s/g, '')
          // console.log('base64 Password: ', pws)

          Api.getLoginApi(uName, psw).then(data => {
            this.loginForm.loading = false
            let datas = data.data
            if (data.status === 0) {
              let userLocal = {
                name: uName,
                token: datas.result.token,
                info: datas.result.userInfo,
                date: Math.round(new Date().getTime() / 1000),
                time: 3600 * 24 * 1 // 存储时间秒*时*天
              }
              // 本地存储
              localStorage.setItem('gisopUserInfo', JSON.stringify(userLocal))
              localStorage.removeItem('rememberNameOp')
              if (this.loginForm.remember) {
                localStorage.setItem('rememberNameOp', uName)
              }
              // vuex store
              let userState = datas.result.userInfo

              this.$store.dispatch('setGisopUser', userState)

              // notify
              let message = '欢迎您，' + userState.username
              this.$notify({
                title: '登录成功',
                message: message,
                type: 'success'
              })

              this.$router.replace('/')
            } else {
              console.error(data)
              this.loginForm.errorText = '用户名或密码错误'
              this.loginForm.isSubmit = true
            }
          }).catch(res => {
            this.loginForm.loading = false
            this.loginForm.isSubmit = true
            this.loginForm.errorText = '提交失败，服务有误'
            console.error(res)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetFields(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss">
  .login {
    width: 100%;
    height: 100%;
    background-image: linear-gradient(180deg, rgba(255, 255, 255, 0) 60%, #f9f9f9), linear-gradient(70deg, #f6f9ed 32%, #e4f7f6);
    background-color: #e4f7f6;

    .logo {
      margin-top: 100px;
      text-align: center;

      img {
        vertical-align: middle;
      }

      h1 {
        display: inline-block;
        margin-left: 20px;
        font-size: 30px;
        color: #424857;
        font-weight: 400;
        vertical-align: middle;
        line-height: 46px;
      }
    }

    .box-card {
      width: 520px;
      /* height: 360px; */
      margin: 40px auto;

      .el-form {
        margin: 25px 25px 10px 0;

        .buttons {        
          margin-top: 10px;
        }
        .submitBtn {
          width: 180px;
          margin-right: 15px;
        }
      }
    }
  }
</style>
