<template>
  <!-- 修改密码 -->
  <div class="changePassword flex-col">
    <s-header :name="$t('changePassword.changePassword')" :noback="false"></s-header>
    <div class="changePasswordFormBox">
      <van-form @submit="changePasswordSubmit">
        <div>
          <!-- 手机号 -->
          <van-field v-model="phone" name="phone" type="tel" label="登录手机" :placeholder="$t('register.phonePlaceholder')"
            :rules="[{ required: true, pattern: /^1[3456789]\d{9}$/, message: $t('register.phoneRequired') }]" />
          <br />
          <!-- 短信验证码 -->
          <van-field v-model="code" name="code" :label="$t('register.codeLabel')"
            :placeholder="$t('register.codePlaceholder')"
            :rules="[{ required: true, message: $t('register.codeRequired') }]">
            <template #button>
              <van-button size="small" type="primary" @click="seedVerCode()"
                :disabled="time !== 0 || phone.length === 0" :loading=reqApi :loading-text="$t('register.sending')">{{
                  time === 0 ?
                    $t('register.seedVerCode') : time + $t('register.replaysInSeconds')
                }}
              </van-button>
            </template>
          </van-field>
        </div><br>
        <van-field v-model="password" name="password" type="password" :label="$t('changePassword.passwordLabel')"
          :placeholder="$t('changePassword.passwordPlaceholder')"
          :rules="[{ required: true, message: $t('changePassword.passwordRequired') }]" />
        <br>
        <van-field v-model="passwordCheck" name="passwordCheck" type="password"
          :label="$t('changePassword.passwordCheckLabel')" :placeholder="$t('changePassword.passwordCheckPlaceholder')"
          :rules="[{ required: true, message: $t('changePassword.passwordCheckRequired') }]" />
        <van-button round type="primary" class="register" native-type="submit">{{ $t('changePassword.registerButton') }}
        </van-button>
      </van-form>
    </div>
  </div>
</template>

<script>
import md5 from 'js-md5';
import { ref, toRefs, onMounted, reactive } from 'vue';
import { showToast, showFailToast } from 'vant';
import sHeader from "@/components/SimpleHeader";
import { useRouter, } from "vue-router";
import { updatePassword } from '@/service/user/change-password';
import { useI18n } from 'vue-i18n';
// import { getLoginUser } from "@/common/js/utils";
import { styleUrl } from '@/common/js/utils';
import { sentRegisterCode } from '@/service/login/register';
import { getLocal, setLocal } from '@/common/js/utils';



export default {
  setup() {
    // 引入语言
    const { t } = useI18n();
    const router = useRouter();
    const password = ref('');
    const passwordCheck = ref('');
    const phone = ref('');
    const code = ref('');

    const verCodeTime = reactive({
      time: 0
    });

    const reqApi = ref(false);

    // 发送验证码
    const seedVerCode = async () => {
      reqApi.value = true;
      try {
        const { data } = await sentRegisterCode({
          phone: phone.value,
        });
        if (data.code === '00000') {
          reqApi.value = false;
          showToast("发送成功");
          verCodeTime.time = 1 * 60; // 1分钟定时器，60s后可以更换验证方式
          verCodeTimeInterval();
        } else {
          reqApi.value = false;
          showFailToast(data.message);
        }
      } catch (error) {
        reqApi.value = false;
      }
    }
    // 验证码发送成功开始1分钟倒计时
    const verCodeTimeInterval = () => {
      const intervalId = setInterval(() => {
        verCodeTime.time--;
        setLocal('registerVerCodeTime', verCodeTime.time);
        if (verCodeTime.time === 0) {
          clearInterval(intervalId); // 清除定时器
        }
      }, 1000);
    }

    // 初始化页面获取验证码倒计时
    onMounted(async () => {
      // 加载样式
      styleUrl('changePassword');
      verCodeTime.time = getLocal('registerVerCodeTime');
      if (verCodeTime.time && verCodeTime.time !== '') {
        verCodeTime.time = parseInt(verCodeTime.time);
        if (verCodeTime.time > 0) {
          verCodeTimeInterval();
        }
      } else {
        verCodeTime.time = 0;
      }
    });

    // 验证-表单
    const changePasswordSubmit = async () => {
      if (password.value !== passwordCheck.value) {
        showFailToast(t('changePassword.inconsistentPasswords'));
        return false;
      }
      const { data } = await updatePassword({
        phone: phone.value,
        code: code.value,
        password: md5(password.value)
      });
      if (data.code === '00000') {
        showToast(t('changePassword.pwdEditSucess'));
        router.push({ path: '/login' });
      } else {
        showFailToast(data.message);
      }
    };
    return {
      password,
      passwordCheck,
      changePasswordSubmit,
      ...toRefs(verCodeTime),
      verCodeTime,
      verCodeTimeInterval,
      seedVerCode,
      phone,
      code,
      reqApi
    };
  },
  components: { sHeader },
};
</script>

<style lang="less" scoped>
@import "@/common/style/mixin";
</style>