<template>
  <el-row style="padding-top: 45px;">
    <el-col :span="11" :offset="1">
      <img class="TT-logo" src="../../../../static/img/register/logo_register.png" alt="">
    </el-col>
    <el-col :span="8" :offset="1">
      <h3 class="title">
        <span>注册</span>
        <span>/Sign up</span>
      </h3>
      <el-form
        :model="dataForm"
        status-icon
        :rules="rules"
        ref="dataForm"
        label-width="0"
        class="demo-ruleForm">
        <el-form-item prop="tel">
          <el-input v-model="dataForm.tel" auto-complete="off" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <el-row :gutter="20">
            <el-col :span="17">
              <el-input v-model="dataForm.captcha" placeholder="图形验证码">
              </el-input>
            </el-col>
            <el-col :span="7" class="login-captcha">
              <img :src="captchaPath" @click="getCaptcha()" alt="">
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="smscode" class="code">
          <el-input v-model="dataForm.smscode" placeholder="验证码"></el-input>
          <el-button type="primary" :disabled='isDisabled' @click="sendCode('dataForm')">{{ buttonText }}</el-button>
        </el-form-item>
        <el-form-item prop="pass">
          <el-input type="password" v-model="dataForm.pass" auto-complete="off" placeholder="输入密码"></el-input>
        </el-form-item>
        <el-form-item prop="checkPass">
          <el-input type="password" v-model="dataForm.checkPass" auto-complete="off" placeholder="确认密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('dataForm')"
                     style="width:100%;background: #332C2B;color: #00EEFF;border: none;">注册
          </el-button>
          <p class="login" @click="gotoLogin">已有账号？立即登录</p>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<script>
import { isMobile, isSmscode } from '@/utils/validate'
import { getUUID } from '@/utils'

export default {
  name: 'Register',
  data () {
    // 验证手机号是否合法
    let checkTel = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码'))
      } else if (!isMobile(value)) {
        callback(new Error('手机号码不合法'))
      } else {
        callback()
      }
    }
    //  验证码是否为空
    let checkSmscode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机验证码'))
      } else if (!isSmscode(value)) {
        callback(new Error('验证码不合法'))
      } else {
        callback()
      }
    }
    // 验证密码
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.dataForm.checkPass !== '') {
          this.$refs.dataForm.validateField('checkPass')
        }
        callback()
      }
    }
    // 二次验证密码
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.dataForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      dataForm: {
        uuid: '',
        captcha: '',
        pass: '',
        checkPass: '',
        tel: '',
        smscode: ''
      },
      rules: {
        pass: [{ validator: validatePass, trigger: 'change' }],
        checkPass: [{ validator: validatePass2, trigger: 'change' }],
        tel: [{ validator: checkTel, trigger: 'change' }],
        smscode: [{ validator: checkSmscode, trigger: 'change' }],
        captcha: [{ required: true, message: '请输入图形验证码', trigger: 'blur' }]
      },
      timer: null,
      numCount: 60,
      buttonText: '发送验证码',
      isDisabled: false, // 是否禁止点击发送验证码按钮
      captchaPath: ''
    }
  },
  created () {
    this.getCaptcha()
  },
  methods: {
    // 获取图形验证码
    getCaptcha () {
      this.dataForm.uuid = getUUID()
      this.captchaPath = this.$http.adornUrl(`/api/captcha?uuid=${this.dataForm.uuid}`)
    },
    funCutDown () {
      let numCount = this.numCount
      clearInterval(this.timer)
      this.timer = setInterval(() => {
        if (numCount === 0) {
          clearInterval(this.timer)
          this.numCount = 0
          this.buttonText = '重新获取'
          this.isDisabled = false
          return
        }
        numCount--
        this.numCount = numCount
        this.buttonText = this.numCount + ' 秒'
      }, 1000)
    },
    // 发送验证码
    sendCode (dataForm) {
      const { tel, captcha } = this.dataForm
      let errList = []
      this.$refs[dataForm].validateField(['tel', 'captcha'], (valid) => {
        if (valid) {
          errList.push(valid)
        }
      })
      if (errList.length) {
        return
      }
      if (this.isDisabled) {
        return
      }
      this.isDisabled = true
      this.buttonText = '已发送'
      this.funCutDown()
      this.$http({
        url: this.$http.adornUrl('/sendMsg'),
        method: 'GET',
        params: this.$http.adornParams({
          'cellphone': tel,
          'type': 0,
          'captcha': captcha
        })
      }).then(({ data }) => {
        if (data.status) {
          this.$message.success('发送成功')
          return
        }
        this.$message.error(data.msg)
      }).catch(() => {
        this.getCaptcha()
        clearInterval(this.timer)
        this.numCount = 0
        this.buttonText = '重新获取'
        this.isDisabled = false
      })
    },
    // 提交注册
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/user/register'),
            method: 'post',
            data: this.$http.adornData({
              'cellphone': this.dataForm.tel,
              'password': this.dataForm.pass,
              'repeatPassword': this.dataForm.checkPass,
              'code': this.dataForm.smscode,
              'uuid': this.dataForm.uuid
            })
          }).then(({ data }) => {
            if (data.status) {
              this.$message.success(data.msg)
              this.$router.replace({ name: 'login' })
              return
            }
            this.$message.error(data.msg)
          }).catch(() => {
            this.getCaptcha()
          })
        }
      })
    },
    // 进入登录页
    gotoLogin () {
      this.$router.push({
        path: '/login'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.TT-logo {
  display: block;
  width: 508px;
  height: 399px;
}

.title {
  text-align: right;
  padding-right: 66px;
  margin-bottom: 37px;

  span {
    &:nth-of-type(1) {
      line-height: 30px;
      font-size: 22px;
      color: #332C2B;
    }

    &:nth-of-type(2) {
      line-height: 26px;
      font-size: 18px;
      font-weight: 400;
      color: #DCDFE6;
    }
  }
}

.el-form {
  width: 100%;
  margin: 0 auto;
}

.login {
  margin-top: 10px;
  font-size: 14px;
  line-height: 22px;
  color: #1ab2ff;
  cursor: pointer;
  text-align: left;
  text-indent: 8px;
  width: 160px;
}

.login-captcha {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  overflow: hidden;

  > img {
    height: 36px;
    cursor: pointer;
  }
}

.code {
  /deep/ .el-form-item__content {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  button {
    margin-left: 20px;
    width: 140px;
    text-align: center;
    background: #332C2B;
    color: #00EEFF;
    border: none;

    &.el-button--primary:focus {
      background: #332C2B;
      color: #00EEFF;
    }
  }
}
</style>
