<template>
  <basicModal @register="modalRegister" ref="modalRef" @ok="formSubmit">
    <template #default>
      <div class="px-6 py-4">
        <BasicForm @register="register" @reset="handleReset" class="basicForm" />
      </div>
    </template>
  </basicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { basicModal, useModal } from '@/components/Modal';
  import { ElMessage } from 'element-plus';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { changePassword } from '@/api/system/user';

  const schemas: FormSchema[] = [
    {
      field: 'password',
      component: 'Input',
      type:'password',
      label: '旧密码',
      componentProps: {
        placeholder: '请输入旧密码',
      },
      rules: [{ required: true, message: '请输入旧密码', trigger: ['blur'] }],
    },
    {
      field: 'newPassword',
      component: 'Input',
      type:'password',
      label: '新密码',
      componentProps: {
        placeholder: '请输入新密码',
      },
      rules: [{ required: true, message: '请输入新密码', trigger: ['blur'] }],
    },
    {
      field: 'confirmPassword',
      component: 'Input',
      type:'password',
      label: '确认密码',
      componentProps: {
        placeholder: '请再次输入新密码',
      },
      rules: [{ required: true, message: '请再次输入新密码', trigger: ['blur'] }],
    },
  ];

  const modalRef: any = ref(null);

  const [register, { submit, getFieldsValue }] = useForm({
    collapsedRows: 3,
    labelWidth: 80,
    layout: 'horizontal',
    showActionButtonGroup: false,
    schemas,
  });

  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({
    title: '修改密码',
    subBtuText: '提交修改',
  });

  async function formSubmit() {
    const formRes = await submit();
    if (formRes) {
      try{
        await changePassword(getFieldsValue())
      closeModal();
      ElMessage.success('修改成功');
      } catch(e){
        setSubLoading(false);
      }

    } else {
      ElMessage.error('验证失败，请填写完整信息');
      setSubLoading(false);
    }
  }

  function showModal() {
    openModal();
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }

  defineExpose({
    showModal,
  });
</script>

<style lang="scss" scoped></style>
