<template>
  <a-form
    ref="formRef"
    :show-label="false"
    :show-require-mark="false"
    size="large"
    :model="formData"
    :rules="rules"
    class="register-form"
  >
    <a-form-item name="username">
      <a-input v-model:value="formData.username" placeholder="请输入用户名">
        <template #prefix>
          <UserOutlined style="color: #808695; font-size: 18px" />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item name="mobile">
      <a-input v-model:value="formData.mobile" placeholder="请输入手机号码">
        <template #prefix>
          <MobileOutlined style="color: #808695; font-size: 18px" />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item name="code">
      <a-input v-model:value.trim="formData.code" placeholder="验证码">
        <template #prefix>
          <SafetyCertificateOutlined style="color: #808695; font-size: 18px" />
        </template>
        <template #suffix>
          <a-button type="text" :disabled="isGetCode" @click="getCode">
            {{ codeMsg }}<span v-if="isGetCode">s</span>
          </a-button>
        </template>
      </a-input>
    </a-form-item>
    <a-form-item name="password">
      <a-input
        v-model:value="formData.password"
        type="password"
        show-password
        placeholder="请输入密码"
      >
        <template #prefix>
          <LockOutlined style="color: #808695; font-size: 18px" />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item name="retPassword">
      <a-input
        v-model:value="formData.retPassword"
        type="password"
        show-password
        placeholder="请再次输入密码"
      >
        <template #prefix>
          <LockOutlined style="color: #808695; font-size: 18px" />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item :show-label="false" class="mb-0">
      <a-button class="w-full" type="primary" @click="handleSubmit" size="large" :loading="loading">
        注册
      </a-button>
    </a-form-item>
    <a-form-item class="default-color" name="agreement">
      <div class="flex items-center justify-between">
        <div class="flex-initial">
          <a-checkbox v-model:checked="formData.agreement">我同意隐私协议</a-checkbox>
        </div>
      </div>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { message } from 'ant-design-vue';
  import type { Rule } from 'ant-design-vue/es/form';
  import { ResultEnum } from '@/enums/httpEnum';
  import { register } from '@/api/system/user';
  import {
    UserOutlined,
    MobileOutlined,
    SafetyCertificateOutlined,
    LockOutlined,
  } from '@ant-design/icons-vue';

  /**
   * 定义参数
   */
  const formRef = ref();
  const loading = ref(false);
  const codeMsg: any = ref('获取验证码');
  const isGetCode = ref(false);
  const emit = defineEmits(['backLogin']);

  /**
   * 定义表单参数
   */
  const formData = reactive({
    username: '',
    password: '',
    retPassword: '',
    mobile: '',
    code: '',
    agreement: false,
  });

  /**
   * 验证手机号
   * @param _rule 验证规则
   * @param value 参数值
   */
  const validatePhone = async (_rule: Rule, value: string) => {
    var isPhone = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
    if (!value) {
      return Promise.reject('请输入手机号');
    } else if (!isPhone.test(value)) {
      return Promise.reject('请输入合法手机号');
    } else {
      return Promise.resolve();
    }
  };

  /**
   * 验证规则定义
   */
  const rules = {
    username: { required: true, message: '请输入用户名', trigger: 'blur' },
    mobile: [{ required: true, validator: validatePhone, trigger: 'blur' }],
    code: { required: true, message: '请输入短信验证码', trigger: 'blur' },
    password: { required: true, message: '请输入密码', trigger: 'blur' },
    retPassword: { required: true, message: '请输入确认密码', trigger: 'blur' },
    agreement: {
      required: true,
      type: 'boolean',
      trigger: 'change',
      validator: async (_, value) => {
        if (!value) {
          return Promise.reject('请先勾选协议');
        } else {
          return Promise.resolve();
        }
      },
    },
  };

  /**
   * 执行提交表单
   */
  const handleSubmit = () => {
    formRef.value
      .validate()
      .then(async () => {
        loading.value = true;

        try {
          const { code, msg } = await register(formData);
          if (code == ResultEnum.SUCCESS) {
            message.success('注册成功，请登录');
            backLogin();
          } else {
            message.error(msg || '登录失败');
          }
        } finally {
          loading.value = false;
        }
      })
      .catch((error) => {
        console.log(error);
        message.error('请填写完整信息');
      });
  };

  /**
   * 执行去登录
   */
  const backLogin = () => {
    emit('backLogin', true);
  };

  /**
   * 获取验证码
   */
  function getCode() {
    if (!formData.mobile) {
      formRef.value.validateFields('mobile');
      return;
    }
    codeMsg.value = 60;
    isGetCode.value = true;
    let time = setInterval(() => {
      codeMsg.value--;
      if (codeMsg.value <= 0) {
        clearInterval(time);
        codeMsg.value = '获取验证码';
        isGetCode.value = false;
      }
    }, 1000);
  }
</script>
