<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 id="getCode"></div>
  </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
  },
  head() {
    return {
      script: [
        { src: "https://cdn.dingxiang-inc.com/ctu-group/captcha-ui/index.js" }
      ]
    };
  },
  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 {
      isRegistering: false,
      pwdShow: false,
      agreeShow: false,
      usePhone: true,
      ruleFormPhone: {
        mobile: "",
        ver: "",
        nickname: "",
        pwd: ""
      },
      rulesPhone: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 7, 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 = this.ruleFormPhone.mobile;
      let register = async body => {
        if (this.isRegistering) {
          console.log('防抖中。。。')
          return
        }
        this.isRegistering = true
        setTimeout(()=>{
          this.isRegistering = false
        }, 1500)
        let res = await this.$axios.$post("/api/passport/register", body);
        if (res && res.data) {
          this.$message.success(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 {
            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 {
            return false;
          }
        });
      }
    },
    /**
     * 获取手机验证码
     * @params {function} run 闭包函数，用来启动验证码内部脚本
     */
    async getVerMobile(run) {
      // let checkRes = await this.$axios.$post('')
      let mobileSplit = this.ruleFormPhone.mobile.split("-");
      let area = mobileSplit[0] || "";
      let mobile = mobileSplit[1] || "";
      if (
        area.match(/\+86/) &&
        !mobile.match(
          /^[0-9]{11}$/
        )
      ) {
        this.$message({
          message: "请输入正确格式的手机号",
          type: "error"
        });
        return;
      }
      const that = this;
      const myCaptcha = _dx.Captcha(document.getElementById("getCode"), {
        appId: "2db960e4ca0eaeee12ef63db7e5b3918", //appId，在控制台中“应用管理”或“应用配置”模块获取
        style: "popup",
        success: async function(token) {
          let res = await that.$axios.$post("/api/user/sendMobileAuthCode", {
            mobile: area + "-" + mobile,
            token,
            type: 1 // 注册1，忘记密码2，提现3
          });
          if (res) {
            run();
            myCaptcha.hide();
          }
        }
      });
      myCaptcha.show();
    },
    /**
     * 点击切换注册模式
     */
    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>
