<template>
  <a-card title="修改密码" class="general-card">
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      style="padding: 0 6rem"
    >
      <a-form-item field="oldPassword" label="现密码" required>
        <a-input-password v-model="formData.oldPassword" />
      </a-form-item>
      <a-form-item field="password" label="新密码" required>
        <a-input-password v-model="formData.password" />
      </a-form-item>
      <a-form-item field="confirmPassword" label="确认密码" required>
        <a-input-password v-model="formData.confirmPassword" />
      </a-form-item>
      <a-form-item
        field="totpCode"
        label="两步验证"
        tooltip="如果设置了就需要填写"
      >
        <a-verification-code v-model="formData.totpCode" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" long @click="onConform">确认</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script setup lang="ts">
import { changePassword } from '@/api/user';
import { FieldRule, FormInstance, Message } from '@arco-design/web-vue';
import { reactive, ref } from 'vue';

const formData = reactive({
  oldPassword: '',
  password: '',
  confirmPassword: '',
  totpCode: ''
});
const rules: Record<string, FieldRule<any> | FieldRule<any>[]> = {
  oldPassword: [{ required: true, message: '请输入现有密码' }],
  password: [{ required: true, message: '请输入新密码' }],
  confirmPassword: [
    { required: true, message: '请再次输入密码' },
    {
      validator: (value: string, cb) => {
        if (value !== formData.password) {
          cb('两次密码输入不一致');
        } else {
          cb();
        }
      }
    }
  ],
  totpCode: [{ match: /^\d{6}$/, message: '请输入正确的两步验证码(6位数字)' }]
};

const formRef = ref<FormInstance>();

const onConform = async () => {
  await formRef.value?.validate(async errors => {
    if (errors) return;
    await changePassword({
      oldPassword: formData.oldPassword,
      newPassword: formData.password,
      totpCode: formData.totpCode
    });
    Message.success('密码修改成功');
  });
};
</script>

<style lang="less" scoped>
.general-card {
  padding-bottom: 1rem;
}
</style>
