<template>
  <div class="register" style="text-align: center; margin: 0 auto">
    <el-card class="box-card" style="text-align: center; margin: 60px auto">
      <!-- 弹出一个警告框 -->

      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        style="text-align: center; margin: 0 auto"
      >
        <el-form-item>
          <!-- 弹出一个警告框 -->
          <el-alert
            title="这个用户名已经被使用！"
            type="warning"
            v-if="register_error"
          >
          </el-alert>
          <!-- 成功注册！ -->

          <el-alert title="欢迎！！！" type="success" v-if="register_success">
          </el-alert>
          <p style="font-size: 30px">注册</p>
          <el-avatar
            src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
          ></el-avatar>
          <!-- <svg
          class="icon"
          aria-hidden="true"
        >
          <use xlink:href="#iconshejitouxiangai"></use>
        </svg> -->
        </el-form-item>

        <el-form-item label="账号" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="pass">
          <el-input
            type="password"
            v-model="ruleForm.pass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认" prop="checkPass">
          <el-input
            type="password"
            v-model="ruleForm.checkPass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >注册</el-button
          >
          <el-button @click="resetForm('ruleForm')">清空</el-button>
        </el-form-item>
        <el-form-item>
          <el-link target="_blank" @click="$router.push({ path: '/login' })"
            >已有账号？</el-link
          >
          <el-link type="primary" @click="$router.push({ path: '/login' })"
            >去登录</el-link
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "Register",
  data() {
    const checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("账号不能为空"));
      }
      setTimeout(() => {
        // if (!Number.isInteger(value)) {
        //   callback(new Error('请输入密码'));
        // } if {
        if (value.length < 2) {
          callback(new Error("名字至少两位"));
        } else {
          callback();
        }
      }, 1000);
    };
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      register_success: false,
      register_error: false,
      // baseurl: "http://127.0.0.1/",
      baseurl: "/api/",
      // baseurl: 'http://yongma16.xyz/',
      ruleForm: {
        pass: "",
        checkPass: "",
        name: "",
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
        name: [{ validator: checkName, trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        const that = this;
        if (valid) {
          // 提交数据
          console.log(this.ruleForm.name, this.ruleForm.pass);
          // alert("yes submit!");
          that.register_success = false; // 初始化register的状态
          that.register_error = false;
          axios
            .post(that.baseurl + "user/register/", {
              // 传递的名字和密码
              name: that.ruleForm.name,
              password: that.ruleForm.pass,
            })
            .then(function (res) {
              console.log("成功post", res);
              console.log(res.data.code);
              if (res.data.code === 0) {
                console.log("重名");
                console.log(that.$cookies.get("user_session")); // 取出cookies的user_session
                console.log(that.$cookies); // 存在
                document.cookie = `user=${that.ruleForm.name}`;
                that.register_error = true;
                that.$message({
                  message: "名称重复" + that.ruleForm.name + "!",
                  type: "error",
                });
                // console.log(this.$cookies)
              } else {
                that.register_success = true;
                console.log("时间节点");
                that.$message({
                  message: "注册成功，欢迎您，" + that.ruleForm.name + "!",
                  type: "success",
                });
                // let token={'user':res.data.name};//传递主码用户名即可
                // this.$cookie.set('token',token,1);//设置token

                // console.log('token设置');
                // let token=this.$cookie.get('token');
                // console.log(token);

                // console.log('设置token成功！');
              }
            })
            .catch(function (res) {
              // 获取res中的name
              that.$message({
                message: "注册失败" + that.ruleForm.name + "!",
                type: "error",
              });
              alert("后端的问题！");
              console.log("失败post", res);
            });
        } else {
          // alert("no submit!");
          console.log("前端的问题！");
          that.$message({
            message: "注册失败" + that.ruleForm.name + "!",
            type: "error",
          });
          // console.log(this.$cookies);
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped>
.text {
  align-content: center;
  display: flex;
  margin: 0 auto;
  font-size: 14px;
}

.item {
  display: flex;
  margin: 0 auto;
  /* width: 50%; */
}

.box-card {
  align-self: center;
  align-content: center;
  display: flex;
  width: 450px;
  /* padding-left:25%; */
  margin: 0 25%;
  opacity: 1;
  margin-top: 80px;
  background-color: #ffffff;
}
</style>
