<template>
  <el-row type="flex" justify="center">
    <el-col :xs="24" :sm="18" :md="12" :lg="9" :xl="6">
      <el-form ref="setAccountform" :model="setAccount" :rules="accountRules">
        <el-form-item prop="user">
          <el-input class="self-input" v-model="setAccount.user" type="text" placeholder="手机号" @keyup.enter.native="onSubmitSetAccount">
          </el-input>
        </el-form-item>
        <el-form-item prop="pwd">
          <el-input v-model="setAccount.pwd" :disabled="isSendDisable" type="text" placeholder="短信验证码" @keyup.enter.native="onSubmitSetAccount">
            <el-button slot="suffix" size="mini" :disabled="isSendDisable || isSendCode" @click="sendCode">{{sendBtnText}}</el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="onSubmitSetAccount">登录</el-button>
        </el-form-item>
        <div class="text">
          <span class="code-login">
            <template v-if="query.rd">
              <router-link class="router-link-class" active-class="router-link-active-class" :to="{ path: '/login/index?rd=' + query.rd }">密码登录</router-link>
            </template>
            <template v-else>
              <router-link class="router-link-class" active-class="router-link-active-class" :to="{ name: 'normalLogin' }">密码登录</router-link>
            </template>
          </span>
          <span class="forget-pwd">
            <template v-if="query.rd">
              <router-link class="router-link-class" active-class="router-link-active-class" :to="{ path: '/login/forget?rd=' + query.rd }">忘记密码</router-link>
            </template>
            <template v-else>
              <router-link class="router-link-class" active-class="router-link-active-class" :to="{ name: 'forgetPwd' }">忘记密码</router-link>
            </template>
          </span>
        </div>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import { request } from '@actions'

export default {
  props: {
    params: { type: Object, required: false, default: {} },
    query: { type: Object, required: false, default: {} }
  },
  data () {
    /* 账号输入正确时，才能获取验证码 */
    let checkAccount = (rule, value, callback) => {
      /* 手机格式 */
      if (/^1[3-9]\d{9}$/.test(value)) {
        this.isSendDisable = false
        callback()
      } else {
        this.isSendDisable = true
        callback(new Error('请输入正确格式的手机号'))
      }
    }
    return {
      isSendDisable: true, // 是否可以发送
      isSendCode: false, // 是否已发送验证码
      timeInterval: null, // 定时器，倒计时
      sendBtnText: '发送验证码', // 按钮 文字
      setAccount: {},
      accountRules: {
        'user': [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkAccount, trigger: 'change' }
        ],
        'pwd': [
          { required: true, message: '请输入短信验证码', trigger: 'blur' }
        ]
      }
    }
  },
  beforeDestroy () { /* 清空倒计时 */ this.clearTime() },
  methods: {
    /* 发送验证码 */
    sendCode () {
      if (!this.isSendCode) {
        // const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
        request({
          component: this,
          actionName: 'loginAction',
          functionName: 'sendCode',
          data: {
            mobile: this.setAccount.user
          },
          thenCallback: res => {
            if (res.status === 200) {
              /* 发送验证码不管是否成功，都开始倒计时 */
              let time = 60
              this.isSendCode = true
              this.sendBtnText = '60s后重发'
              this.timeInterval = setInterval(() => {
                if (time-- > 0) {
                  this.sendBtnText = time + 's后重发'
                } else {
                  this.isSendCode = false
                  this.sendBtnText = '发送验证码'
                  clearInterval(this.timeInterval)
                }
              }, 1000)
            } else {
              return new Error(JSON.stringify(res))
            }
          },
          catchCallback: e => {},
          finallyCallback: () => {}
        })
      }
    },
    /* 清空倒计时 */
    clearTime () {
      this.isSendCode = true
      this.sendBtnText = '发送验证码'
      clearInterval(this.timeInterval)
    },
    onSubmitSetAccount () {
      this.$refs['setAccountform'].validate((valid) => {
        if (valid) {
          request({
            component: this,
            actionName: 'loginAction',
            functionName: 'codeLogin',
            data: {
              mobile: this.setAccount.user,
              code: this.setAccount.pwd
            },
            thenCallback: data => {
              /* 查询上次跳转信息，并跳转回去 */
              if (this.query.rd) {
                this.$router.push({ path: decodeURIComponent(this.query.rd) })
              } else {
                this.$router.push({ path: '/app/my-learn/course' })
              }
            },
            catchCallback: e => {},
            finallyCallback: () => {}
          })
        } else {
          this.$message.error('请根据输入框提示，检查输入项。')
          return false
        }
      })
    }
  }
}
</script>
