<template>
  <div id="auth-card-body">
    <h2 id="auth-card-title">完善手机号</h2>
    <el-form id="auth-card-form" ref="cardFormRef" :model="cardForm" :rules="cardFormRule" @keyup.enter="onSubmit">
      <el-form-item class="auth-card-form-item" prop="username">
        <el-input v-model="cardForm.username" clearable placeholder="请输入用户名或学号">
          <template #prefix>
            <el-icon class="el-input__icon">
              <avatar/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item class="auth-card-form-item" prop="phone">
        <el-input v-model="cardForm.phone" autofocus clearable placeholder="请输入手机号">
          <template #prefix>
            <el-icon class="el-input__icon">
              <phone/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <div id="auth-card-code-verifier">
        <el-form-item prop="identifyCode">
          <el-input v-model="cardForm.identifyCode" placeholder="请输入验证码">
            <template #prefix>
              <el-icon class="el-input__icon">
                <key/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-button id="auth-card-code-verifier-button" :disabled="cardButtonDisabled" @click="handleSendMessage">
          {{ cardButtonText }}
        </el-button>
      </div>

      <el-form-item class="auth-card-form-item">
        <el-button id="auth-card-submit-button" type="primary" @click="onSubmit">完善手机号</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
import {Avatar, Phone, Key} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";

export default {
  name: "CompletePhoneCard",
  components: {
    Phone,
    Avatar,
    Key,
  },
  data() {
    const inputNumberValidator = (rule, value, callback) => {
      if (!(/(^[1-9]\d*$)/.test(value))) {
        callback(new Error("请勿输入非数字"));
      } else {
        callback();
      }
    };
    const phoneValidator = async (rule, value, callback) => {
      if (/^(13\d|14\d|15\d|166|18\d|19[6,9]|17\d)\d{8}$/i.test(value) === false) {
        callback(new Error("请输入正确格式的手机号"));
      } else {
        callback();
      }
    };
    const identifyCodeValidator = (rule, value, callback) => {
      if (value.length !== 6) {
        this.shakeElem("auth-card-code-verifier");
        callback(new Error("请正确输入短信验证码"));
      } else {
        this.cardVerified = true;
        callback();
      }
    };
    return {
      cardButtonDisabled: false,
      cardButtonText: "获取验证码",
      cardVerified: false,
      cardForm: {
        phone: "",
        username: "",
        identifyCode: "",
      },
      cardFormRule: {
        phone: [
          {required: true, message: "请输入手机号", trigger: "blur"},
          {
            validator: phoneValidator,
            trigger: "blur"
          },
          {
            validator: inputNumberValidator,
            trigger: "change"
          }
        ],
        username: [
          {
            required: true,
            min: 1,
            max: 20,
            message: "请输入正确格式的用户名",
            trigger: "blur",
          }
        ],
        identifyCode: [
          {
            validator: identifyCodeValidator,
            trigger: "blur",
          },
          {
            validator: inputNumberValidator,
            trigger: "change",
          }
        ]
      },
    };
  },
  methods: {
    onSubmit() {
      this.$refs.cardFormRef.validate(async (valid) => {
        if (valid) {
          const res = (await this.$apis.completePhone(this.cardForm)).data;
          if(!res.code){
            ElMessage.success(data);
          }else{
            ElMessage.error(res);
          }
        }
      });
    },
    handleSendMessage() {
      const thatForm = this.$refs.cardFormRef;
      thatForm.validateField("phone", v1 => {
        if (!v1) {
          this.cardButtonDisabled = true;
          let time = 60;
          const myScroll = setInterval(() => {
            time--;
            if (time >= 0) {
              this.cardButtonText = time + "s后可重发";
            } else {
              this.cardButtonText = "获取验证码";
              this.cardButtonDisabled = false;
              clearTimeout(myScroll);
              time = 60;
            }
          }, 1000);
          const params = {
            phone: this.cardForm.phone
          };
          this.$apis.sendMessageAPI(params)
            .then((res) => {
              if (res.data.code === 0) {
                this.$message({
                  showClose: true,
                  message: "发送成功，请注意查收验证码",
                  type: "success"
                });
              } else {
                this.$message({
                  showClose: true,
                  message: res.data.message,
                  type: "warning"
                });
              }
            })
            .catch((e) => {
              this.$message({
                showClose: true,
                message: e,
                type: "error"
              });
            });
        }
      });
    },
    shakeElem(elemId) {
      let elem = document.getElementById(elemId);
      elem.classList.add("shake");
      setTimeout(() => {
        elem.classList.remove("shake");
      }, 800);
    },
  }
};
</script>

<style scoped src="./AuthCard.css"/>
