<template>
  <!-- 修改密码 -->
  <div class="changePassword flex-col">
    <s-header :name="$t('changePassword.changePassword')" :noback="false"></s-header>
    <div class="changePasswordFormBox">
      <van-form @submit="changePasswordSubmit">
        <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 } from 'vue';
import { showToast, showFailToast } from 'vant';
import sHeader from "@/components/SimpleHeader";
import { useRouter, useRoute } from "vue-router";
// import { useRouter } from "vue-router";
import { updatePassword } from '@/service/changePassword';
import { useI18n } from 'vue-i18n';
import { getLoginUser } from "@/common/js/utils";
import { styleUrl } from '../common/js/utils';

export default {
  setup() {
    // 引入语言
    const { t } = useI18n();
    const router = useRouter();
    const route = useRoute();
    const user = getLoginUser();
    const password = ref('');
    const passwordCheck = ref('');
    // 加载样式
    styleUrl('changePassword');
    // 验证-表单
    const changePasswordSubmit = async () => {
      if (password.value !== passwordCheck.value) {
        showFailToast(t('changePassword.inconsistentPasswords'));
        return false;
      }
      const { data } = await updatePassword({
        username: route.query.name || user.username,
        // username: user.username,
        password: md5(password.value)
      });
      if (data.code === '00000') {
        showToast(t('changePassword.pwdEditSucess'));
        router.push({ path: '/login' });
      } else {
        showFailToast(data.message);
      }
    };
    return {
      password,
      passwordCheck,
      changePasswordSubmit
    };
  },
  components: { sHeader },
};
</script>

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