<template>
  <t-form
    ref="form"
    class="form-container"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >
    <div class="title-box">
      <span class="span1">{{ $t('login.RegisterAccount') }}</span>
    </div>
    <t-form-item name="email">
      <t-input
        v-model="formData.email"
        size="large"
        :placeholder="$t('login.placeholderEmail')"
      >
        <template #prefix-icon>
          <t-icon name="mail" />
        </template>
      </t-input>
    </t-form-item>
    <t-form-item name="password">
      <t-input
        v-model="formData.password"
        size="large"
        :type="showPsw ? 'text' : 'password'"
        clearable
        :placeholder="$t('login.placeholderPassword')"
      >
        <template #prefix-icon>
          <t-icon name="lock-on" />
        </template>
        <template #suffix-icon>
          <t-icon
            :name="showPsw ? 'browse' : 'browse-off'"
            @click="showPsw = !showPsw"
          />
        </template>
      </t-input>
    </t-form-item>
    <t-form-item name="password2">
      <t-input
        v-model="formData.password2"
        size="large"
        :type="showPsw2 ? 'text' : 'password'"
        clearable
        :placeholder="$t('login.placeholderPassword2')"
      >
        <template #prefix-icon>
          <t-icon name="lock-on" />
        </template>
        <template #suffix-icon>
          <t-icon
            :name="showPsw2 ? 'browse' : 'browse-off'"
            @click="showPsw2 = !showPsw2"
          />
        </template>
      </t-input>
    </t-form-item>
    <t-form-item class="code">
      <t-input :placeholder="$t('login.enterCode')" v-model="formData.code">
        <template #prefix-icon>
          <t-icon name="lock-on" />
        </template>
      </t-input>
      <t-button
        @click="sendCode"
        class="send-code custom_button_back_border"
        :disabled="countDown > 0"
        >{{
          countDown == 0
            ? $t('login.SendVerificationCode')
            : `${countDown}秒后可重发`
        }}</t-button
      >
    </t-form-item>
    <t-form-item name="invite_code">
      <t-input
        v-model="formData.invite_code"
        size="large"
        type="text"
        clearable
        :placeholder="$t('login.enterInvitationCode')"
      >
        <template #prefix-icon>
          <t-icon name="lock-on" />
        </template>
        <template #suffix-icon>
          <t-icon
            :name="showPsw2 ? 'browse' : 'browse-off'"
            @click="showPsw2 = !showPsw2"
          />
        </template>
      </t-input>
    </t-form-item>

    <t-form-item class="check-container" name="checked">
      <t-checkbox v-model="formData.checked"
        >{{ $t('login.haveRead') }}
      </t-checkbox>
      <span class="link">{{ $t('login.UserPrivacy') }}</span>
    </t-form-item>
    <t-form-item class="submit">
      <t-button
        block
        size="large"
        type="submit"
        class="custom_button_back_border"
      >
        {{ $t('login.registerBtn') }}
      </t-button>
    </t-form-item>

    <div class="go-login" @click="goLogin">
      {{ $t('login.haveAccount') }},
      <span class="go-login-span">{{ $t('login.goLogin') }}</span>
    </div>
  </t-form>
</template>

<script setup lang="ts">
import { MessagePlugin, LoadingPlugin } from 'tdesign-vue-next';
import request from '@/utils/request';
import md5 from 'md5';
import { useCounter } from '@/hooks';
const [countDown, handleCounter] = useCounter();
const props = defineProps({
  InvitCode: String,
});
onMounted(() => {
  if (props.InvitCode) {
    formData.value.invite_code = props.InvitCode;
  }
});
const INITIAL_DATA = {
  email: '',
  password: '',
  code: '',
  password2: '',
  checked: false,
  invite_code: '',
};

const formData = ref({ ...INITIAL_DATA });
const showPsw = ref(false);
const showPsw2 = ref(false);
const form = ref(null);
const emit = defineEmits(['go']);
// 数据校验
const repasswordValidator = (value) => {
  if (formData.value.password === value) {
    return { result: true };
  } else {
    return { result: false, message: '两次密码输入不一致', type: 'error' };
  }
};
// 发送验证码
const sendCode = () => {
  try {
    if (!formData.value.email) {
      return;
    }
    if (countDown.value > 0) {
      return;
    }
    // 邮箱正则
    let reg =
      /[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/;
    if (!reg.test(formData.value.email)) {
      MessagePlugin.closeAll();
      MessagePlugin.warning('请输入正确的邮箱');
      return;
    }
    handleCounter();
    request
      .post('api/send/email', {
        email: formData.value.email,
        scenes: 'reg',
      })
      .then((res: any) => {
        if (res.msg === 'success') {
          MessagePlugin.success('验证码发送成功,请注意查收');
        } else {
          MessagePlugin.warning('发送失败，请稍后再试');
        }
      });
  } catch (e) {
    console.log(e);
  }
};
const FORM_RULES = {
  email: [
    { required: true, message: 'email required', type: 'error' },
    { email: true, message: 'email error', type: 'error' },
  ],
  password: [
    { required: true, message: 'password required', type: 'error' },
    // { min: 6, message: '至少需要6位', type: 'error' },
  ],
  password2: [
    { required: true, message: 'confirm password required', type: 'error' },
    { validator: repasswordValidator },
  ],
};
const onSubmit = async ({ validateResult }) => {
  if (validateResult === true) {
    if (!formData.value.checked) {
      MessagePlugin.error('请同意用户隐私政策');
      return;
    }
    try {
      LoadingPlugin(true);
      const data: any = await request.post('/api/auth/register', {
        email: formData.value.email,
        code: formData.value.code,
        password: md5(formData.value.password),
        invite_code: formData.value.invite_code,
      });
      if (data.status) {
        MessagePlugin.success('注册成功');
        emit('go', 'login');
      } else {
        MessagePlugin.warning(data.msg);
      }
    } catch (e) {
      console.log(e);
    } finally {
      LoadingPlugin(false);
    }
  }
};

const goLogin = (val) => {
  emit('go', 'login');
};
</script>

<style scoped lang="less">
.form-container {
  .code {
    .t-input__wrap {
      flex: 1;
    }
    .t-button {
      margin-left: 8px;
      border: none;
      height: 30px;
    }
  }
  .title-box {
    width: 70%;
    line-height: 80px;
    span {
      display: block;
      color: rgb(95, 95, 95);
      font-size: 38px;
      font-weight: bold;
    }
  }
  .go-login {
    cursor: pointer;
    color: var(--td--main-btn-color-1);
  }
}
</style>
