<template>
  <div class="container">
    <template v-if="!emailSent">
      <n-form ref="formRef" label-placement="left" :label-width="100" :model="form" :rules="rules" size="large" require-mark-placement="left">
        <n-form-item :label="t('common.register.email')+'：'" path="email">
          <n-input v-model:value="form.email" :placeholder="t('common.register.forgetPasswordPlaceholder')" />
        </n-form-item>
      </n-form>
      <n-button class="login-btn" attr-type="button" type="info" color="#18A058" :disabled="submitLoading" @click="handleSend">
        {{ submitLoading ? t('common.login.sending') : t('common.login.clickToSend') }}
      </n-button>
    </template>

    <template v-else>
      <p style="text-align: center">
        <n-icon size="30" color="#00C849" :component="MdCheckmarkCircle" />
      </p>
      <p class="tip">
        {{t('common.login.emailSendSuccess')}}
      </p>
      <n-button class="login-btn" attr-type="button" type="info" color="#18A058" @click="handleSure">
        {{t('common.login.confirm')}}
      </n-button>
    </template>
  </div>
</template>

<script lang="ts" setup>
import { useI18n } from "#imports";
import { createDiscreteApi } from "naive-ui";
import { MdCheckmarkCircle } from "@vicons/ionicons4";
import { ref, reactive } from "vue";
const { t, locale, setLocale } = useI18n();
const emit = defineEmits(["closeSginDialog"]);

const message = createDiscreteApi(["message"]);

const formRef = ref();
const submitLoading = ref(false);
const form = reactive<object>({
  email: "",
});

const rules: FormRules = {
  email: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: ["input", "blur"],
    },
    {
      required: true,
      validator: (rule: FormItemRule, value: string): boolean => {
        return value && isEmail(value);
      },
      message: "请输入正确格式邮箱",
      trigger: ["blur"],
    },
  ],
};

const emailSent = ref<boolean>(false);

const handleSend = () => {
  formRef.value?.validate(async (errors: any) => {
    if (!errors) {
      submitLoading.value = true;
      const { code } = await email_Api(form);
      if (code === 200) {
        message.message.success("发送成功");
        emailSent.value = true;
      }
      submitLoading.value = false;
    }
  });
};

const handleSure = () => {
  emit("closeSginDialog", "success");
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  padding: 30px 20px;

  .login-btn {
    display: block;
    width: 50%;
    height: 50px;
    color: #fff;
    font-size: 18px;
    border-radius: 8px;
    margin: 0 auto;

    :deep(.n-button__content) {
      display: block;
    }
  }

  .tip {
    font-size: 16px;
    line-height: 32px;
  }
}
</style>
