<template>
  <div class="wrapper">
    <div class="register">
      <div class="title">
        <div class="text">
          账号注册
          <el-tooltip
            class="item"
            effect="dark"
            content="提示：若您已经使用微信账号在小程序平台登陆过后，系统将自动为您注册账号，初始密码为您的手机号，请直接登录"
            placement="top-start"
          >
            <i class="el-icon-question tips"></i>
          </el-tooltip>
        </div>
        <div class="close" @click="handleCloseLogin">×</div>
      </div>
      <el-form
        :model="form"
        status-icon
        :rules="rules"
        ref="registerForm"
        label-width="80px"
        class="register-form"
      >
        <el-form-item label="账号" prop="username">
          <el-input
            v-model="form.username"
            autocomplete="off"
            clearable
            placeholder="账号长度4-20个字符，只能包括字母、数字、下划线"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="form.phone"
            autocomplete="off"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input
            v-model="form.nickName"
            autocomplete="off"
            clearable
            placeholder="2~10个字符，只能包含中英文、数字及下划线，不能以下划线开头或结尾"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="form.password"
            autocomplete="off"
            clearable
            placeholder="至少8位，至少含数字、大写字母、小写字母、特殊符其中三种"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input
            type="password"
            v-model="form.checkPass"
            autocomplete="off"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item class="submit-buttons">
          <el-button @click.native="resetForm('registerForm')" v-if="!loading"
            >重置</el-button
          >
          <el-button
            :loading="loading"
            type="primary"
            @click.native="submitForm"
            class="submit"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { register } from "@/api/user";
import { checkUserName, checkPhone } from "@/utils/validate";

export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        var pattern =
          /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{8,30}$/;
        if (!pattern.test(value)) {
          callback(
            new Error(
              "密码长度至少8位，至少含数字,大写字母,小写字母,特殊符其中三种"
            )
          );
        }
        if (this.form.checkPass !== "") {
          this.$refs.registerForm.validateField("checkPass");
        }
        callback();
      }
    };

    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validateUserName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else {
        var pattern = /^[0-9a-zA-Z|_]{4,20}$/g;
        if (!pattern.test(value)) {
          callback(new Error("账号长度4-20个字符，只能包括字母、数字、下划线"));
        } else {
          const formData = new FormData();
          formData.append("userName", value);
          checkUserName(formData)
            .then((res) => {
              if (res.code == "0") {
                callback();
              } else {
                callback(res.msg);
              }
            })
            .catch((err) => {
              console.error(err);
            });
        }
      }
    };

    var validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else {
        var pattern = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
        if (!pattern.test(value)) {
          callback(new Error("请输入合法手机号/电话号"));
        } else {
          const formData = new FormData();
          formData.append("phone", value);
          checkPhone(formData)
            .then((res) => {
              console.log(res);
              if (res.code == "0") {
                callback();
              } else {
                callback(res.msg);
              }
            })
            .catch((err) => {
              console.error(err);
            });
        }
      }
    };

    return {
      form: {
        username: "",
        password: "",
        checkPass: "",
        nickName: "",
      },
      isDisabled: true,
      second: 60,
      rules: {
        username: [
          { validator: validateUserName, trigger: "blur", required: true },
        ],
        phone: [{ validator: validatePhone, trigger: "blur", required: true }],
        nickName: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            pattern: /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
            message:
              "昵称长度2~10位，只能包含中文、英文大小写、数字及下划线，不能以下划线开头或结尾",
            trigger: "blur",
          },
        ],
        password: [
          { validator: validatePass, trigger: "blur", required: true },
        ],
        checkPass: [
          { validator: validatePass2, trigger: "blur", required: true },
        ],
      },
      loading: false,
    };
  },
  methods: {
    submitForm() {
      // debugger
      // console.log(123);
      this.$refs["registerForm"].validate((valid) => {
        // debugger
        if (valid) {
          this.loading = true;
          const { username, password, phone, nickName } = this.form;
          let params = {
            username,
            password,
            phone,
            nickName,
            status: 1,
          };
          register(params)
            .then((res) => {
              if (res.code == "0") {
                this.$confirm("注册成功, 是否去登录?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "success",
                })
                  .then(() => {
                    this.$store.commit("app/OPEN_LOGIN_DIALOG", true);
                  })
                  .catch(() => {
                    console.log("取消操作");
                  });
              }
              this.loading = false;
            })
            .catch((err) => {
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleCloseLogin() {
      if (window.history.length <= 1) {
        this.$router.push({ path: "/" });
        return false;
      } else {
        this.$router.go(-1);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
  width: 100%;
  background-image: url("@/assets/imgs/home/display-bg.png");
  background-repeat: no-repeat;
  background-size: 100%;
  background-position: center;
  padding: 60px 0 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  flex-direction: column;
  .register {
    width: 580px;
    background-color: #fff;
    // border-radius: 16px;
    padding: 48px 32px;
    box-shadow: 0 4px 8px 0 rgb(7 17 27 / 10%);
    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30px;
      .text {
        // font-weight: bold;
        font-size: 36px;
        color: #666;
        font-family: "KaiTi";
        .tips {
          font-size: 24px;
        }
      }
      .close {
        font-size: 34px;
        cursor: pointer;
        color: #ccc;
      }
    }
  }
}

::v-deep .el-input__inner {
  background: #e8f0fe;
  border: none;
}

::v-deep .submit-buttons {
  .el-form-item__content {
    display: flex;
    justify-content: flex-end;
    .el-button {
      border-radius: 0px;
      &:last-child {
        width: 160px;
        background-color: #2069c4;
        &:hover {
          filter: brightness(0.9);
        }
      }
    }
  }
}
</style>