<template>
  <div id="login-box">
    <div class="header">登录</div>
    <div class="main">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item prop="principal">
          <el-input
            v-model="form.principal"
            placeholder="手机号"
            class="cuborder-radius"
            @keyup.enter.native="onSubmit('form')"
          />
        </el-form-item>
        <el-form-item prop="credential">
          <el-input
            v-model="form.credential"
            placeholder="验证码"
            class="cuborder-radius"
            maxlength="6"
            style="width: 205px"
            @keyup.enter.native="onSubmit('form')"
          />
          <div v-if="smsLock" class="send-code-btn send-sms-disable">
            正在发送 ...
          </div>
          <div
            v-else-if="smsLock === false && smsLockObj.time === null"
            class="send-code-btn"
            @click="sendSms"
          >
            获取验证码
          </div>
          <div v-else class="send-code-btn send-sms-disable">
            重新发送({{ smsLockObj.time }}s)
          </div>
        </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="loginLoading"
            @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/login1')"
            >密码登录
            </el-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ServeCaptcha, ServeLogin, ServePubkey, ServeSendVerifyCode } from '@/api/account'
import { userMixin } from 'assets/js/mixin'
import { isMobile } from '@/utils/validate'
import SmsLock from '@/utils/sms-lock'
import { JSEncrypt } from 'jsencrypt'
import Vue from 'vue'

export default {
  mixins: [userMixin],
  data() {
    const validateMobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('登录手机号不能为空！'))
      } else {
        // isMobile(value) ? callback() : callback(new Error('登录手机号格式不正确！'))
        callback()
      }
    }
    return {
      loginLoading: false,
      form: {
        loginType: 1,
        plat: 1,
        principal: '',
        credential: '',
        captchaCode: ''
      },
      pubkey: {
        key: '',
        r: ''
      },
      captchaCode: '',
      rules: {
        principal: [
          {
            validator: validateMobile,
            trigger: 'blur'
          },
          {
            min: 1,
            max: 100,
            message: '手机号格式不正确!',
            trigger: 'blur'
          }
        ],
        credential: [
          {
            required: true,
            message: '登录密码不能为空!',
            trigger: 'blur'
          }
        ]
      },
      smsLock: false,
      smsLockObj: null
    }
  },
  created() {
    const userdata = Vue.$cookies.get('USERDATA')
    if (userdata !== null) {
      this.$router.push('/')
    } else {
      this.getPubkey()
      this.smsLockObj = new SmsLock('LOGIN_SMS', 60)
    }
  },
  destroyed() {
    this.smsLockObj.clearInterval()
  },
  methods: {
    onSubmit(formName) {
      if (this.loginLoading) return false

      this.$refs[formName].validate(valid => {
        if (!valid) return false
        this.loginLoading = true
        this.login()
      })
    },
    getCaptcha() {
      ServeCaptcha().then(res => {
        if (res.code === 0) {
          this.captchaCode = res.data
        } else {
          this.$notify.info({
            title: '提示',
            message: '获取 Captcha 失败, 请重新刷新页面...'
          })
        }
      }).finally(() => {
      })
    },
    getPubkey() {
      ServePubkey().then(res => {
        if (res.code === 0) {
          this.pubkey.key = res.data.pubkey
          this.pubkey.r = res.data.r

          this.getCaptcha()
        } else {
          this.$notify.info({
            title: '提示',
            message: '获取公钥失败, 请重新刷新页面...'
          })
        }
      }).finally(() => {
      })
    },
    encryptPassword(password) {
      var encryptor = new JSEncrypt()
      encryptor.setPublicKey(this.pubkey.key)
      return encryptor.encrypt(this.pubkey.r + password)
    },
    async login() {
      ServeLogin({
        loginType: this.form.loginType,
        plat: this.form.plat,
        principal: this.form.principal,
        credential: this.encryptPassword(this.form.credential),
        captchaCode: this.form.captchaCode
      }).then(res => {
        if (res.code === 0) {
          const resData = res.data
          /* const userInfo = resData.userInfo
            const userToken = resData.userToken
            setUserToken(userToken)
            this.$store.commit('UPDATE_USER_INFO', userInfo)*/
          this.$router.push('/')
        } else {
          this.$notify.info({
            title: '提示',
            message: res.msg
          })
        }
      }).finally(() => {
        this.loginLoading = false
      })
    },
    sendSms() {
      if (this.smsLock) return false
      if (!isMobile(this.form.username)) {
        this.$refs.form.validateField('username', (val) => {
          return !val
        })
      }

      this.smsLock = true
      ServeSendVerifyCode({
        receiver: this.form.principal,
        notifyType: 3
      }).then(res => {
        if (res.code === 0) {
          this.$notify({
            title: '成功',
            message: '验证码发送成功...',
            type: 'success'
          })
          this.smsLockObj.start()
        } else {
          this.$notify({
            title: '提示',
            message: res.message,
            customClass: 'cus-notifyclass'
          })
        }
      }).finally(() => {
        this.smsLock = false
      })
    },
    toLink(url) {
      this.$router.push({
        path: url
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import '~@/assets/css/login-auth.scss';
</style>
