<template>
  <n-modal v-model:show="showModal" :on-after-leave="handleCloseModal" :mask-closable="false" :bordered="false">
    <n-card title="重置密码" class="w-500px rounded-16px shadow-sm">
      <template #header-extra>
        <Icon icon="ic:sharp-close" class="text-size-22px cursor-pointer" @click="showModal = false" />
      </template>
      <div>
        <n-form ref="formRef" label-placement="left" :label-width="80" :model="modalForm" :rules="rules">
          <n-form-item label="用户密码" path="password">
            <n-input
              v-model:value="modalForm.password"
              type="password"
              show-password-on="mousedown"
              :clearable="true"
              placeholder="请输入用户密码"
            />
          </n-form-item>
        </n-form>
      </div>
      <template #footer>
        <div class="w-full flex justify-center">
          <NButton @click="showModal = false">取消</NButton>
          <NButton :loading="submitLoading" class="ml-4" type="primary" @click="handleSubmit">提交</NButton>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue';
import type { FormRules, FormInst } from 'naive-ui';
import { fetchResetUserPwd } from '@/service';

interface Props {
  curResetPwdUserId: number;
}
const props = defineProps<Props>();

const formRef = ref<FormInst | null>(null);
const showModal = ref(false);
const submitLoading = ref(false);
const modalForm = ref({
  password: ''
});

const rules = ref<FormRules>({
  password: { required: true, message: '用户密码不能为空', trigger: ['input', 'blur'] }
});
/** 打开弹窗 */
function handleShowModal() {
  showModal.value = true;
}
/** 关闭弹窗 */
function handleCloseModal() {
  showModal.value = false;
  modalForm.value = {
    password: ''
  };
}
/** 提交 */
function handleSubmit() {
  formRef.value?.validate(async errors => {
    if (!errors) {
      submitLoading.value = true;
      console.log(props.curResetPwdUserId);
      const { data } = await fetchResetUserPwd({
        userId: props.curResetPwdUserId,
        password: modalForm.value.password
      });
      if (data?.ok) {
        window.$message?.success('操作成功');
        handleCloseModal();
      }
    }
    submitLoading.value = false;
    return errors;
  });
}

defineExpose({
  handleShowModal
});
</script>
