<template>
  <div class="loginView w-screen h-screen overflow-hidden flex">
    <div class="w-[32rem] bg-white m-auto border-t-8 border-blue-400 shadow-xl rounded-md pl-9 pr-9">
      <h2 class="text-xl text-center pt-4 font-bold">注册</h2>
      <el-form class="pt-4" ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <el-form-item class="pt-1" prop="companyName">
          <el-input type="text" size="large" v-model="ruleForm.companyName" autocomplete="off" placeholder="公司名"
            clearable :prefix-icon="HomeFilled"></el-input>
        </el-form-item>
        <el-form-item class="pt-1" prop="name">
          <el-input type="text" size="large" v-model="ruleForm.name" autocomplete="off" placeholder="姓名" clearable
            :prefix-icon="UserFilled"></el-input>
        </el-form-item>
        <el-form-item class="pt-1" prop="phone">
          <el-input type="text" size="large" v-model="ruleForm.phone" autocomplete="off" placeholder="手机号" clearable
            :prefix-icon="Iphone"></el-input>
        </el-form-item>
        <el-form-item class="pt-1" prop="vcode">
          <el-input type="text" size="large" v-model="ruleForm.vcode" autocomplete="off" placeholder="验证码" clearable
            :prefix-icon="Tickets">
            <template #append>
              <el-button @click="sendVcode()" :disabled="ruleForm.phone == '' || showTimer">发送验证码<span
                  v-if="showTimer">({{ countNum }})</span></el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item class="pt-1" prop="password">
          <el-input type="password" size="large" v-model="ruleForm.password" autocomplete="off"
            placeholder="设置密码,长度不低于6位" clearable :prefix-icon="Lock">
          </el-input>
        </el-form-item>
        <el-form-item class="pt-1" prop="repwd">
          <el-input type="password" size="large" v-model="ruleForm.repwd" autocomplete="off" placeholder="重复密码"
            clearable :prefix-icon="Lock">
          </el-input>
        </el-form-item>
        <div class="pt-4 mb-5">
          <el-button type="primary" size="large" class="w-full" :loading="registerLoading"
            @click="register(ruleFormRef)">注册</el-button>
        </div>
      </el-form>
      <div class="text-right mb-5 cursor-pointer text-blue-400 hover:text-blue-300" @click="router.push('/login')">
        已有账号？返回登录
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { inject, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { HomeFilled, UserFilled, Lock, Iphone, Tickets } from '@element-plus/icons-vue'
import { ElNotification, ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { isValueEmpty } from "@/utils/tools";
import { post } from "@/utils/request";
import { REGISTER, SENDVCODE } from "./api";
const globalPopup = inject<GlobalPopup>('globalPopup')
const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  companyName: "",
  name: "",
  phone: "",
  vcode: "",
  password: "",
  repwd: ""
});
const rules = reactive<FormRules<typeof ruleForm>>({
  companyName: [{ required: true, message: '请输入公司名', trigger: 'blur' },],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' },],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' },
  ],
  vcode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请设置密码，长度不低于6位', trigger: 'blur' },
    { min: 6, message: '密码长度不少于6位', trigger: 'blur' },
  ],
  repwd: [
    { required: true, message: '请重复输入密码', trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (value !== ruleForm.value.password) {
          callback(new Error('两次密码不一致'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ]
})

const registerLoading = ref(false);
const showTimer = ref(false);
const countNum = ref(10);
const countDown = () => {
  if (countNum.value > 0) {
    setTimeout(() => {
      countNum.value -= 1;
      countDown()
    }, 1000)
  } else {
    showTimer.value = false;
    countNum.value = 10;
  }
}
const sendVcode = () => {
  showTimer.value = true;
  countDown();
  if (ruleForm.value.phone.trim().length != 11) {
    ElMessage.error({
      message: "请输入正确的手机号",
      type: "error",
      duration: 2000,
    })
    return
  }
  post(SENDVCODE, {
    mobile: ruleForm.value.phone
  }).then(res => {
    if (res.code == "ok") {
      ElMessage.success({
        message: "发送成功",
        type: "success",
        duration: 2000,
      })
      showTimer.value = true;
      countDown();
    }
  })
}
const register = (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return
  }

  formEl.validate((valid: boolean) => {
    if (!valid) {
      return false as any;
    }
    registerLoading.value = true;
    let params = {
      ...ruleForm.value,
    }
    /* 如果地址栏有参数，就带上 */
    if (!isValueEmpty(route.query)) {
      params = {
        ...params,
        ...route.query
      }
    }
    post(REGISTER, params).then(res => {
      if (res.code == "ok") {
        globalPopup?.showSuccess("注册成功")
        registerLoading.value = false;
        router.back()
      } else {
        globalPopup?.showError(res.message || res.msg || "注册失败")
        registerLoading.value = false;
      }
    }).catch(err => {
      globalPopup?.showError(err.msg || err.msg || "注册失败")
      registerLoading.value = false;
    })

  })

};

</script>

<style lang="scss" scoped>
.loginView {
  background: #f0f2f5 url("../assets/login/background.png") no-repeat;
}
</style>