<template>
  <div class="login-box-header">
    <div class="back" @click="goBack">
      <arrow-left-icon /><span>{{ $t('login.backBtn') }}</span>
    </div>
    <div class="title">{{ $t('login.PasswordReset') }}</div>
  </div>
  <t-form
    ref="form"
    :class="['form-container']"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >
    <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 class="verification-code" name="vcCode">
      <t-input
        v-model="formData.vcCode"
        size="large"
        :placeholder="$t('login.enterCode')"
      >
        <template #prefix-icon> <t-icon name="secured" /> </template>
        <template #suffix>
          <t-button
            :loading="btnLoading"
            class="send-verify"
            variant="text"
            :disabled="countDown > 0"
            @click="sendVerfiyCode"
          >
            {{
              countDown == 0
                ? $t('login.SendVerificationCode')
                : `${countDown}秒后可重发`
            }}
          </t-button>
        </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.enterNewPassword')"
      >
        <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.enterpasswordAgain')"
      >
        <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.readAndAgree') }}
      </t-checkbox>
      <span class="link" @click="goStatement">{{
        $t('login.UserPrivacy')
      }}</span>
    </t-form-item>
    <t-form-item class="submit">
      <t-button block size="large" type="submit">
        {{ $t('login.ConfirmReset') }}
      </t-button>
    </t-form-item>
  </t-form>
</template>

<script setup lang="ts">
import { MessagePlugin, LoadingPlugin } from 'tdesign-vue-next';
import { useCounter } from '@/hooks';
import { ArrowLeftIcon } from 'tdesign-icons-vue-next';
import request from '@/utils/request';
import md5 from 'md5';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
const INITIAL_DATA = {
  email: '',
  vcCode: '',
  password: '',
  password2: '',
  checked: false,
};

const formData = ref({ ...INITIAL_DATA });
const showPsw = ref(false);
const showPsw2 = ref(false);
const form = ref(null);
const router = useRouter();

//发送验证码
const btnLoading = ref(false);
const [countDown, handleCounter] = useCounter();
const sendVerfiyCode = async () => {
  const res = await form.value.validate({ fields: ['email'] });
  if (res !== true) {
    return;
  }
  if (countDown.value > 0) {
    return;
  }
  btnLoading.value = true;
  // 重置验证码
  request
    .post('/api/send/email', {
      email: formData.value.email,
      scenes: 'reset',
    })
    .then((data) => {
      handleCounter();
    })
    .catch((e) => {})
    .finally(() => {
      btnLoading.value = false;
    });
};

// 数据校验
const repasswordValidator = (value) => {
  if (formData.value.password === value) {
    return { result: true };
  } else {
    return { result: false, message: t('login.notMatch'), type: 'error' };
  }
};

const FORM_RULES = {
  email: [
    { required: true, message: t('login.EMailRequired'), type: 'error' },
    { email: true, message: t('login.entercorrectemail'), type: 'error' },
  ],
  vcCode: [
    { required: true, message: t('login.Verificatioquired'), type: 'error' },
    { min: 4, message: t('login.Captchaerror'), type: 'error' },
  ],
  password: [
    { required: true, message: t('login.PasswordRequired'), type: 'error' },
    { min: 6, message: t('login.Ateeded'), type: 'error' },
  ],
  password2: [
    {
      required: true,
      message: t('login.ConfirmPasswordRequired'),
      type: 'error',
    },
    { validator: repasswordValidator },
  ],
};

const emit = defineEmits(['go']);
const onSubmit = async ({ validateResult }) => {
  if (validateResult === true) {
    if (!formData.value.checked) {
      MessagePlugin.error('请同意用户隐私政策');
      return;
    }
    try {
      LoadingPlugin(true);
      const data: any = await request.post('/api/password/reset', {
        email: formData.value.email,
        code: formData.value.vcCode,
        password: md5(formData.value.password),
        password_confirmation: md5(formData.value.password2),
      });
      if (data.code == 0) {
        MessagePlugin.success(data.data);
      }
      emit('go', 'login');
    } catch (e) {
      console.log(e);
    } finally {
      LoadingPlugin(false);
    }
  }
};
const goBack = () => {
  emit('go', 'login');
};
const goStatement = () => {
  console.log(1);
};
</script>
<style lang="less" scoped>
@import '@/style/flex.less';
@import '@/style/variables.less';
.login-box-header {
  width: 360px;
  height: 60px;
  .dja();
  position: relative;
  .back {
    position: absolute;
    left: 0;
    bottom: 12px;
    .da();
    &:hover {
      cursor: pointer;
    }
  }
  .title {
    font-size: @font-size-xl;
    font-weight: bold;
  }
}
.form-container {
  width: 360px;
  white-space: nowrap;
  .send-verify {
    color: var(--td--main-btn-color-1);
  }
  .link {
    color: var(--td--main-btn-color-1);
    cursor: pointer;
  }
}
</style>
