<template>
  <a-modal
    v-model:visible="visible"
    title-align="start"
    title="修改密码"
    :mask-closable="false"
    :esc-to-close="false"
  >
    <a-form ref="formRef" :model="formData" :rules="rules">
      <a-form-item field="oldPassword" label="旧密码" auto-label-width>
        <a-input-password
          v-model.trim="formData.oldPassword"
          placeholder="请输入旧密码"
          allow-clear
        >
        </a-input-password>
      </a-form-item>
      <a-form-item field="password" label="新密码">
        <a-input-password
          v-model.trim="formData.password"
          placeholder="请输入新密码"
          allow-clear
        >
        </a-input-password>
      </a-form-item>
      <a-form-item field="rePassword" label="再次密码">
        <a-input-password
          v-model.trim="formData.rePassword"
          placeholder="请再次输入新密码"
          allow-clear
        >
        </a-input-password>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button @click="close">取消</a-button>
      <a-button type="primary" :disabled="loading" @click="confirm"
        >确认</a-button
      >
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import { reactive, ref } from 'vue';
  import type { FormInstance, FieldRule } from '@arco-design/web-vue/es/form';
  import { password, strictPassword } from '@/utils/formRules';
  import useLoading from '@/hooks/loading';
  import { updatePwd } from '@/api/user';
  import { Message } from '@arco-design/web-vue';
  import { getBase64 } from '@/utils/crypto';
  import { useUserStore } from '@/store';
  import useModal from '@/hooks/modal';

  defineOptions({
    name: 'ResetPwd',
  });

  /* modal */
  const { visible, open, close } = useModal();
  defineExpose({ open, close });

  const emit = defineEmits(['modified']);

  const userStore = useUserStore();
  const defaultFormData = {
    oldPassword: '',
    password: '',
    rePassword: '',
  };
  type FormDataType = typeof defaultFormData;

  const formRef = ref<FormInstance>();
  const formData = reactive<FormDataType>({ ...defaultFormData });
  const passwordRule: FieldRule[] = [
    ...strictPassword,
    {
      validator: (value, callback) => {
        if (value === userStore.account) {
          return callback('禁止使用用户账户号作为密码');
        }
        return callback();
      },
    },
  ];
  const rules: Record<keyof FormDataType, FieldRule[]> = {
    oldPassword: password,
    password: [
      ...passwordRule,
      {
        validator: (value, callback) => {
          if (value === formData.oldPassword) {
            callback('新旧密码不可以相同');
          } else {
            callback();
          }
        },
      },
    ],
    rePassword: [
      ...passwordRule,
      {
        validator: (value, callback) => {
          if (value !== formData.password) {
            callback('两次输入的密码不一致');
          } else {
            callback();
          }
        },
      },
    ],
  };

  /* confirm */
  const { loading, setLoading } = useLoading();
  async function confirm() {
    const err = await formRef.value?.validate();
    if (err) return;

    setLoading(true);
    const datas = {
      id: userStore.id as number,
      oldPassword: getBase64(formData.oldPassword),
      password: getBase64(formData.password),
    };
    const res = await updatePwd(datas).catch(() => false);
    setLoading(false);
    if (!res) return;
    Message.success('修改成功！');
    emit('modified', datas);
    close();
  }
</script>
