<script lang="ts" setup>
import { onMounted, ref, unref } from 'vue';

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

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { UserApi } from '#/api';
import { encrypt } from '#/utils';

import { formOptions } from '../data.config';

defineOptions({
  name: 'UserEdit',
});
const emit = defineEmits(['success']);
const modelRef = ref<Record<string, any>>({});
const isUpdate = ref(true);

const [Form, { validate, setValues, getValues, updateSchema }] = useVbenForm({
  showDefaultActions: false,
  ...formOptions,
});

const [Modal, { close, setState, getData }] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    close();
  },
  onConfirm: async () => {
    try {
      const { valid } = await validate();
      if (valid) {
        const values = await getValues();
        setState({ confirmLoading: true });
        const postParams = unref(modelRef);
        const data: any = {};
        if (values.password) {
          data.password = encrypt(values.password);
        }
        Object.assign(postParams, values, { ...data });
        await (unref(isUpdate)
          ? UserApi.editDetail(postParams as UserApi.RecordItem)
          : UserApi.addDetail(postParams as UserApi.BasicRecordItem));
        message.success('操作成功');

        close();
        emit('success');
      }
    } catch {
      message.error('操作失败');
    } finally {
      setState({ confirmLoading: false });
    }
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      setState({ loading: true });
      const data = getData<Record<string, any>>();
      isUpdate.value = !!data.isUpdate;
      modelRef.value = { ...data.baseData };
      setState({ title: unref(isUpdate) ? '编辑用户' : '新增用户' });

      if (unref(isUpdate)) {
        const entity = await UserApi.getDetail(data.baseData.id);
        modelRef.value = { ...entity };
        setValues(entity);
        updateSchema([
          { fieldName: 'password', componentProps: { disabled: true } },
        ]);
      } else {
        updateSchema([
          { fieldName: 'password', componentProps: { disabled: false } },
        ]);
      }

      setState({ loading: false });
    }
  },
  title: '新增用户',
});

onMounted(async () => {});
</script>
<template>
  <Modal class="w-[1000px]">
    <Form />
  </Modal>
</template>
