<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import { REG_PWD } from '@/constants/reg';
import { fetchUpdateUserPassword } from '@/service/api';
import { useForm, useFormRules } from '@/hooks/common/form';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';
import { $t } from '@/locales';

defineOptions({ name: 'UserResetPasswordDialog' });

interface Props {
  userId?: number | null;
  username?: string | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate } = useForm();
const { createRequiredRule, createConfirmPwdRule } = useFormRules();

const submitting = ref(false);

const title = computed(() => $t('page.system.user.resetPassword'));
const displayUsername = computed(() => props.username?.trim() || $t('common.noData'));

const model = ref({
  password: '',
  confirmPassword: ''
});

const rules = computed<Record<'password' | 'confirmPassword', App.Global.FormRule[]>>(() => ({
  password: [
    createRequiredRule($t('page.system.user.form.newPassword')),
    { pattern: REG_PWD, message: $t('form.pwd.invalid') }
  ],
  confirmPassword: createConfirmPwdRule(model.value.password)
}));

function initModel() {
  model.value.password = '';
  model.value.confirmPassword = '';
}

function closeDialog() {
  visible.value = false;
}

async function handleSubmit() {
  if (!props.userId) {
    return;
  }

  await validate();

  submitting.value = true;

  const { error } = await fetchUpdateUserPassword({
    id: props.userId,
    password: model.value.password.trim()
  });

  submitting.value = false;

  if (error) {
    return;
  }

  window.$message?.success($t('common.updateSuccess'));
  closeDialog();
  emit('submitted');
}

watch(visible, async value => {
  if (!value) {
    return;
  }

  initModel();
  await nextTick();
  formRef.value?.clearValidate();
});
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    :title="title"
    preset="sm"
    :confirm-loading="submitting"
    :scrollbar="false"
    @confirm="handleSubmit"
  >
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <ElRow :gutter="16">
        <ElCol :span="24">
          <ElFormItem :label="$t('page.system.user.userName')">
            <ElInput :model-value="displayUsername" disabled />
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem :label="$t('page.system.user.newPassword')" prop="password">
            <ElInput v-model="model.password" show-password :placeholder="$t('page.system.user.form.newPassword')" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem :label="$t('page.system.user.confirmPassword')" prop="confirmPassword">
            <ElInput
              v-model="model.confirmPassword"
              show-password
              :placeholder="$t('page.system.user.form.confirmPassword')"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
  </BusinessFormDialog>
</template>
