<template>
  <div>
    <v-row justify="center">
      <v-col cols="10">
        <v-text-field
          v-model="userLogin.username"
          placeholder="请输入手机号/邮箱"
          label="手机号/邮箱"
          :rules="[() => userLogin.username != null || '手机号/邮箱不能为空']"
          clearable
        />
      </v-col>
    </v-row>
    <v-row justify="center">
      <v-col cols="10">
        <v-row justify="center">
          <v-col cols="5">
            <v-text-field
              v-model="userLogin.password"
              placeholder="请输入验证码"
              label="验证码"
              :rules="[() => userLogin.password != null || '验证码不能为空']"
              clearable
            />
          </v-col>
          <v-col cols="5">
            <v-btn color="primary" @click="getVerifyCode">获取验证码</v-btn>
          </v-col>
        </v-row>
      </v-col>
    </v-row>
    <v-row justify="center">
      <v-col cols="5">
        <img :src="captchaUrl" alt="图形验证码" title="点击刷新" style="cursor:pointer;" @click="getCaptcha">
      </v-col>
      <v-col cols="5">
        <v-text-field
          v-model="userLogin.captchaCode"
          placeholder="图形验证码"
          label="图形验证码"
          :rules="[() => userLogin.captchaCode != null || '图形验证码不能为空']"
          clearable
        />
      </v-col>
    </v-row>
    <v-row justify="center">
      <v-btn color="primary" @click="submitLogin">登录/注册</v-btn>
    </v-row>
  </div>
</template>

<script>
import { randomString, getCaptchaUrl } from '@/utils'
import { getVerifyCode } from '@/api/user/account'
import { getPubkey } from '@/api/user/auth'

export default {
  name: 'Register',
  data() {
    return {
      captchaUrl: '',
      showMessage: false,
      userLogin: {
        accountType: 1,
        loginType: 2,
        username: null,
        password: null,
        captchaCode: null,
        r: null,
        plat: 'web'
      }
    }
  },
  created() {
    this.getCaptcha()
    this.fetchPubkey()
  },
  methods: {
    submitLogin() {
      // 将数据返回给父组件
      this.$emit('login', this.userLogin)
    },
    getCaptcha() {
      const randomStr = randomString(10)
      this.userLogin.r = randomStr
      // 图片上发送点击事件时，captchaUrl 的值发生变化，然后才去请求后端
      this.captchaUrl = getCaptchaUrl(randomStr)
    },
    fetchPubkey() {
      getPubkey().then(res => {
        if (res.code === 0) {
          this.pubkey = res.data.pubkey
          this.pubkeyR = res.data.r
        } else {
          alert(res.data)
        }
      }).catch(error => {
        console.error(error.message)
      })
    },
    getVerifyCode() {
      const verifyCodeReq = {}
      verifyCodeReq.receiver = this.userLogin.username
      verifyCodeReq.notifyType = 2
      getVerifyCode(verifyCodeReq)
        .then(res => {
          if (res.code === 0) {
            alert(res.msg)
          } else {
            console.error(res.msg)
          }
        })
        .catch(error => {
          console.error(error.message)
        })
    }
  }
}
</script>

<style>
</style>
