<template>
  <div class="register">
    <h1>注册新账号</h1>
    <div class="hr"></div>
    <el-form
      v-if="usePhone"
      :model="ruleFormPhone"
      :rules="rulesPhone"
      ref="ruleFormPhone"
      label-width="100px"
      class="demo-ruleForm"
      label-position="top"
      :hide-required-asterisk="true"
    >
      <el-form-item label="手机号" prop="mobile">
        <input-area @change="chengeMobile"></input-area>
      </el-form-item>
      <el-form-item label="验证码" prop="ver">
        <input-ver @click="getVerMobile" @change="chengeVerMobile"></input-ver>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="ruleFormPhone.nickname" placeholder="请输入昵称"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pwd">
        <el-input
          :type="pwdShow ? 'text' : 'password'"
          v-model="ruleFormPhone.pwd"
          placeholder="请输入密码，至少包含6位字符"
        >
          <i class="el-icon-view switch-passowrd" @click="pwdShow = !pwdShow" slot="suffix"></i>
        </el-input>
      </el-form-item>
    </el-form>
    <el-form
      v-else
      :model="ruleFormEmail"
      :rules="rulesEmail"
      ref="ruleFormEmail"
      label-width="100px"
      class="demo-ruleForm"
      label-position="top"
      :hide-required-asterisk="true"
    >
      <el-form-item label="邮箱" prop="email">
        <el-input placeholder="请输入邮箱" v-model="ruleFormEmail.email"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="ver">
        <input-ver-img @change="chengeVerEmail"></input-ver-img>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input placeholder="请输入昵称" v-model="ruleFormEmail.nickname"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pwd">
        <el-input
          :type="pwdShow ? 'text' : 'password'"
          placeholder="请输入密码，至少包含6位字符"
          v-model="ruleFormEmail.pwd"
        >
          <i class="el-icon-view switch-passowrd" @click="pwdShow = !pwdShow" slot="suffix"></i>
        </el-input>
      </el-form-item>
    </el-form>
    <p class="remind">
      点击注册表示你已阅读并同意
      <a href="/outsource/agreement?from=register" target="_blank">《程序员客栈服务协议》</a>
    </p>
    <el-button type="primary" @click="doRegist">注册</el-button>
    <div class="checks">
      <span @click="doSwitch">{{usePhone ? '邮箱' : '手机'}}注册</span>
      <span @click="goLogin($event, true)">直接登录</span>
    </div>
    <div class="logos">
      <a
        href="https://github.com/login/oauth/authorize?client_id=65396ecb78f8cb000768&redirect_uri=https%3A%2F%2Fwww.proginn.com%2Fuser%2Flogingithub&scope=user%3Aemail"
      >
        <img src="~@/assets/img/user/github_logo.png" alt="github">
      </a>
      <a
        href="https://api.weibo.com/oauth2/authorize?client_id=2749593033&redirect_uri=https%3A%2F%2Fwww.proginn.com%2Fuser%2Floginweibo&response_type=code&forcelogin=true"
      >
        <img src="~@/assets/img/user/sina_logo.png" alt="sina">
      </a>
      <a
        href="https://open.weixin.qq.com/connect/qrconnect?appid=wx0f62bbdc948d0f23&redirect_uri=https%3A%2F%2Fwww.proginn.com%2Fuser%2Floginweixin&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect"
      >
        <img src="~@/assets/img/user/wechat_logo.png" alt="wechat">
      </a>
    </div>
    <agreement :visible.sync="agreeShow"></agreement>
  </div>
</template>

<script>
import InputVer from '@/components/input/ver'
import InputVerImg from '@/components/input/ver_img'
import InputArea from '@/components/input/area'
import Agreement from '@/components/agreement'

export default {
  components: {
    InputVer,
    InputVerImg,
    InputArea,
    Agreement,
  },
  data() {
    let validateEmail = (rule, value, callback) => {
      if(!value.trim()) {
        callback(new Error('请输入邮箱'))
      } else {
        if(value.match(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/)) {
          callback()
        } else {
          callback(new Error('邮箱格式不正确！'))
        }
      }
    }
    return {
      pwdShow: false,
      agreeShow: false,
      usePhone: true,
      ruleFormPhone: {
        mobile: '',
        ver: '',
        nickname: '',
        pwd: '',
      },
      rulesPhone: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 14, max: 16, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        ver: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码至少为6位字符', trigger: 'blur' },
        ],
      },
      ruleFormEmail: {
        email: '',
        ver: '',
        nickname: '',
        pwd: '',
      },
      rulesEmail: {
        email: [
          { validator: validateEmail, message: '请输入正确的邮箱', trigger: 'blur' },
        ],
        ver: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码至少为6位字符', trigger: 'blur' },
        ],
      }
    }
  },
  mounted() {
    if(this.$store.getters.isLogin) {
      this.$message('你已有注册的账号')
      setTimeout(() => {
        location.href = '/'
      }, 1000)
    }
  },
  methods: {
    chengeVerMobile(val) {
      this.ruleFormPhone.ver = val
    },
    chengeVerEmail(val) {
      this.ruleFormEmail.ver = val
    },
    chengeMobile(val) {
      this.ruleFormPhone.mobile = val
    },
    /**
     * 点击注册
     */
    doRegist() {
      let mobile = encodeURIComponent(this.ruleFormPhone.mobile)
      let register = async body => {
        let res = await this.$post('/api/passport/register', body)
        if(res) {
          this.$message(res.info)
          setTimeout(() => {
            location.href = "/user/success"
          }, 1000)
        }
      }
      if(this.usePhone) {
        this.$refs.ruleFormPhone.validate((valid) => {
          if(valid) {
            let body = {
              auth_code: this.ruleFormPhone.ver,
              login_name: mobile,
              mobile,
              nickname: this.ruleFormPhone.nickname,
              password: this.ruleFormPhone.pwd,
            }
            register(body)
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs.ruleFormEmail.validate((valid) => {
          if(valid) {
            let body = {
              captcha: this.ruleFormEmail.ver,
              email: this.ruleFormEmail.email,
              nickname: this.ruleFormEmail.nickname,
              password: this.ruleFormEmail.pwd,
            }
            register(body)
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    /**
     * 获取手机验证码
     * @params {function} run 闭包函数，用来启动验证码内部脚本
     */
    async getVerMobile(run) {
      // let checkRes = await this.$post('')
      let mobile = this.ruleFormPhone.mobile.split('-')[1] || ''
      if(!mobile.match(/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/)) {
        this.$message({
          message: '请输入正确手机号',
          type: 'error'
        })
        return
      }
      let res = await this.$post('/api/passport/check_registered', {
        mobile,
      })
      // console.log(res)
      if(res) {
        if(res.data.registered) {
          this.$message({
            message: '手机号已注册',
            type: 'error'
          })
        } else {
          let res = await this.$post('/api/user/sendMobileAuthCode', {
            mobile,
          })
          if(res) {
            run()
            this.$message(res.info)
          }
        }
      }
    },
    /**
     * 点击切换注册模式
     */
    doSwitch() {
      this.usePhone = !this.usePhone
      let clearValidate
      if(!this.usePhone) clearValidate = this.$refs.ruleFormPhone.clearValidate
      else clearValidate = this.$refs.ruleFormEmail.clearValidate
      // setTimeout(clearValidate, 200)
      this.$nextTick(clearValidate)
    }
  }
}
</script>

<style scoped>
@import "@/assets/css/h1_line.css";

.register {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 1000px;
  background: white;
}
.el-button,
.el-input {
  width: 320px;
}
.remind {
  margin: 14px 0 22px;
  font-size: 12px;
  color: #919aa7;
}
.checks {
  color: #666;
  margin: 14px 0 30px;
  white-space: nowrap;
}
.checks span {
  padding: 0 20px;
  cursor: pointer;
}
.checks span:first-child {
  border-right: 1px solid #666;
}
.logos {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 154px;
}
.logos img {
  width: 34px;
  height: 34px;
  margin-bottom: 50px;
}
.switch-passowrd {
  margin-right: 8px;
  cursor: pointer;
}
</style>
