<template>
  <div id="login-box">
    <div class="header">登录</div>
    <div class="main">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="用户名/邮箱/手机号"
            class="cuborder-radius"
            maxlength="11"
            @keyup.enter.native="onSubmit('form')"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="form.password"
              type="password"
              placeholder="密码"
              class="cuborder-radius"
              @keyup.enter.native="onSubmit('form')"
          />
        </el-form-item>
        <el-form-item prop="captchaCode">
          <el-row>
            <el-col :span=12>
              <el-input
                  v-model="form.captchaCode"
                  placeholder="图形验证码"
                  class="cuborder-radius"
                  maxlength="11"
                  @keyup.enter.native="onSubmit('form')"
              />
            </el-col>
            <el-col :span=12>
              <img :src="captchaCode" alt="图形验证码" title="点击刷新" style="cursor:pointer;" @click="getCaptcha">
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="submit-btn"
            :loading="registerLoading"
            @click="onSubmit('form')"
          >
            登录
          </el-button>
        </el-form-item>
        <el-form-item>
          <div class="links">
            <el-link
              type="primary"
              :underline="false"
              @click="toLink('/sso/forget')"
            >
              找回密码
            </el-link>
            <el-link
              type="primary"
              :underline="false"
              @click="toLink('/sso/register')"
            >没有账号？
            </el-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ServeCaptcha, ServeRegister, ServeSendVerifyCode } from '@/api/auth'
import { isMobile } from '@/utils/validate'
import SmsLock from '@/utils/sms-lock'

export default {
  data() {
    let validateMobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('手机号不能为空！'))
        return
      }

      if (!isMobile(value)) {
        callback(new Error('手机号格式不正确！'))
      } else {
        callback()
      }
    }

    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    return {
      captchaCode: '',
      registerLoading: false,
      form: {
        username: '',
        password: '',
        mobile: '',
        smsCode: '',
        captchaCode: '',
        plat: ''
      },
      rules: {
        username: [
          {
            required: true,
            message: '用户名不能为空!',
            trigger: 'blur',
          },
        ],
        mobile: [
          {
            validator: validateMobile,
            trigger: 'blur',
          },
        ],
        smsCode: [
          {
            required: true,
            message: '短信验证码不能为空!',
            trigger: 'blur',
          },
        ],
      },
      smsLock: false,
      smsLockObj: null,
    }
  },
  created() {
    this.getCaptcha()
    this.smsLockObj = new SmsLock('REGISTER_SMS', 60)
  },
  destroyed() {
    this.smsLockObj.clearInterval()
  },
  methods: {
    getCaptcha() {
      ServeCaptcha().then(res => {
        if (res.code === 0) {
          this.captchaCode = res.data
        } else {
          this.$notify.info({
            title: '提示',
            message: '获取 Captcha 失败, 请重新刷新页面...',
          })
        }
      }).finally(() => {
      })
    },
    randomString(len) {
      len = len || 16
      var t = '012345678ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz'
      var a = t.length
      var res = ''
      for (var i = 0; i < len; i++) res += t.charAt(Math.floor(Math.random() * a))
      return res
    },
    resetFields() {
      if (!this.model) {
        console.warn('[Element Warn][Form]model is required for resetFields to work.');
        return;
      }
      this.fields.forEach(field => {
        field.resetField();
      });
    },
    toLink(url) {
      this.$router.push({
        path: url,
      })
    },

    onSubmit(formName) {
      if (this.registerLoading) return false

      this.$refs[formName].validate(valid => {
        if (!valid) return false
        this.registerLoading = true
        this.register()
      })
    },
    register() {
      ServeRegister(
          this.form
      ).then(res => {
          if (res.code === 0) {
            this.$notify({
              title: '成功',
              message: '注册成功,快去登录吧...',
              type: 'success',
            })

            this.$refs.form.resetFields()
            setTimeout(() => {
              this.toLink('/sso/login')
            }, 1500)
          } else {
            this.$notify.info({
              title: '提示',
              message: res.message,
            })
          }
        }).catch((e) => {
          console.log(e)
          this.$notify({
            message: '网络错误,请稍后再试...',
          })
        }).finally(() => {
          this.registerLoading = false
        })
    },
    // 点击发送验证码
    sendSms() {
      if (this.smsLock) return false

      if (!isMobile(this.form.mobile)) {
        this.$refs.form.validateField('mobile', (val) => {
          return !val;
        })
      }

      this.smsLock = true
      ServeSendVerifyCode({
        receiver: this.form.mobile,
        channel: 'register',
      }).then(res => {
          if (res.code === 0) {
            this.$notify({
              title: '成功',
              message: '验证码发送成功...',
              type: 'success',
            })

            this.smsLockObj.start()
            /*if (res.data.is_debug) {
              setTimeout(() => {
                this.$notify({
                  title: '提示',
                  message: '已自动填充验证码',
                })

                this.form.sms_code = res.data.sms_code
              }, 500)
            }*/
          } else {
            this.$notify({
              title: '提示',
              message: res.message,
              customClass: 'cus-notifyclass',
            })
          }
        }).finally(() => {
          this.smsLock = false
        })
    },
  },
}
</script>
<style lang="scss">
@import '~@/assets/css/login-auth.scss';
</style>
