<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">航汇-支付宝授权平台</h3>
      </div>

      <el-form-item prop="username">
        <i class="iconfont icon-user form-left-container" />
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="账号"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <i class="iconfont icon-password form-left-container" />
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <i :class="`iconfont icon-${passwordType === 'password' ? 'eye' : 'eye-open'} form-right-container`" @click="showPwd" />
      </el-form-item>
      <template v-if="isAdmin">
        <el-form-item prop="phone">
          <i class="iconfont icon-phone form-left-container" />
          <el-input
            ref="phone"
            v-model="loginForm.phone"
            placeholder="手机号"
            name="phone"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>

        <div style="display: flex;align-items: center">
          <el-form-item prop="code" style="flex: 1">
            <i class="iconfont icon-captcha form-left-container" />
            <el-input
              ref="code"
              v-model="loginForm.code"
              placeholder="验证码"
              name="code"
              type="text"
              tabindex="1"
              auto-complete="on"
            />
          </el-form-item>
          <el-button class="code_btn" type="primary" :disabled="isSending" :loading="submitLoading" @click="sendCode">
            {{ isSending ? `${countdown}s后重试` : "发送验证码" }}
          </el-button>
        </div>
      </template>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登 录</el-button>
    </el-form>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import store from '@/store'
import { getCode } from '@/api/user'

export default {
  name: 'Login',
  data() {
    const validatePassword = (rule, value, callback) => {
      if (!value || value.length < 6) {
        callback(new Error('密码不能少于6位'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      const phoneReg = /^1[3-9]\d{9}$/
      if (!value || !phoneReg.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }

    return {
      loginForm: {
        username: null,
        password: null,
        phone: null,
        code: ''
      },
      loginRules: {
        username: [{
          required: true,
          whitespace: true,
          message: '请输入你的账号',
          trigger: ['change', 'blur'] }],
        password: [{ required: true, trigger: ['change', 'blur'], validator: validatePassword }],
        phone: [{ required: true, trigger: ['change', 'blur'], validator: validatePhone }],
        code: [{
          required: true,
          whitespace: true,
          message: '请输入验证码',
          trigger: ['change', 'blur'] }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,

      /** 验证码开始 **/
      isSending: false,
      submitLoading: false,
      countdown: 60,
      timer: null
      /** 验证码结束 **/
    }
  },
  computed: {
    isAdmin() {
      return this.loginForm.username == 'admin'
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      console.log(this.loginForm)
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (!this.isAdmin) {
            this.loginForm.phone = ''
            this.loginForm.code = ''
          }
          this.$store.dispatch('user/login', this.loginForm).then(async() => {
            await this.$store.dispatch('user/getAuthAccountQuery')
            this.$router.push({ path: this.redirect || '/' })
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('登录错误!!')
          return false
        }
      })
    },
    // 发送验证码
    sendCode() {
      this.$refs.loginForm.validateField(['phone'], (valid) => {
        console.log('发送验证码校验', valid)
        // 字段校验成功则返回空串
        if (!valid) {
          const _this = this
          _this.submitLoading = true
          getCode({
            username: _this.loginForm.username,
            phone: _this.loginForm.phone
          }).then(res => {
            this.$message({
              type: 'success',
              message: '发送验证码成功！'
            })
            _this.isSending = true
            _this.countdown = 60
            // 模拟请求后端发送验证码
            console.log('验证码已发送至手机号:', _this.loginForm.phone)

            _this.timer = setInterval(() => {
              if (_this.countdown > 0) {
                _this.countdown -= 1
              } else {
                clearInterval(_this.timer)
                _this.isSending = false
              }
            }, 1000)
          }).finally(() => {
            _this.submitLoading = false
          })
        } else {
          return
        }
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 46px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 46px;
      line-height: 46px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
    height: 46px;
    line-height: 46px;
    //overflow: hidden;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .form-left-container {
    height: 46px;
    width: 30px;
    text-align: right;
    color: $dark_gray;
    vertical-align: middle;
    display: inline-block;
  }

  .form-right-container {
    height: 46px;
    width: 30px;
    text-align: center;
    color: $dark_gray;
    vertical-align: middle;
    display: inline-block;
    cursor: pointer;
  }

  .icon-eye {
    font-size: 14px;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .code_btn {
    margin-bottom: 22px;
    width: 115px;
    height: 46px;
    margin-left: 10px;
    font-size: 14px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
}
</style>
