<script setup lang="ts">
import type { AccountEntity } from '@vben/types';

import type { VbenFormSchema } from '#/adapter/form';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { ElMessage } from 'element-plus';
import { md5 } from 'js-md5';

import { useVbenForm, z } from '#/adapter/form';
import { editAccountApi } from '#/api/account';

const emit = defineEmits(['finish']);
const data = ref<{ row: Partial<AccountEntity> }>({ row: {} });

const schema: VbenFormSchema[] = [
  {
    component: 'Input',
    fieldName: 'accountpwd',
    label: '新密码',
    rules: z.string().min(1, '请输入新密码'),
    componentProps: {
      type: 'password',
      placeholder: '请输入新密码',
      showPassword: true,
    },
  },
  {
    component: 'Input',
    fieldName: 'confirmPassword',
    label: '确认密码',
    rules: z.string().min(1, '请再次输入新密码'),
    componentProps: {
      type: 'password',
      placeholder: '请再次输入新密码',
      showPassword: true,
      onBlur: () => {
        baseFormApi.validateField('accountpwd');
      },
    },
  },
];

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    labelWidth: 130,
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema,
});

const [Modal, modalApi] = useVbenModal({
  class: 'w-1/3',
  title: '修改密码',
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    // 校验输入的数据
    const validate = await baseFormApi.validate();
    if (!validate.valid) {
      return;
    }

    const values = await baseFormApi.getValues();
    if (values.accountpwd !== values.confirmPassword) {
      ElMessage.error('两次输入的密码不一致');
      return;
    }

    try {
      await editAccountApi({
        accountid: data.value.row.accountid,
        accountpwd: md5(values.accountpwd),
      } as AccountEntity);

      ElMessage.success('密码修改成功!');
      emit('finish');
      modalApi.close();
    } catch {}
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      data.value = modalApi.getData();
      baseFormApi.setValues({
        accountpwd: '',
        confirmPassword: '',
      });
    }
  },
});

function openModal(rowData: any) {
  modalApi.setData({ row: rowData });
  modalApi.open();
}

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

<template>
  <Modal>
    <BaseForm />
  </Modal>
</template>
