<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { SysConfigApi } from '#/api/system/sysConfig';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';

import { useVbenForm } from '#/adapter/form';
import { apiAdd, apiUpdate } from '#/api/system/sysConfig';
import { getDictOptions } from '#/utils/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

const emit = defineEmits<{
  success: [];
}>();
const formData = ref<SysConfigApi.Config>();

const formSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    fieldName: 'configName',
    label: '参数名称',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'configKey',
    label: '参数键名',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'configValue',
    label: '参数键值',
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      options: getDictOptions(DictEnum.SYS_YES_NO),
      optionType: 'button',
    },
    defaultValue: 'N',
    fieldName: 'configType',
    label: '是否内置',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'remark',
    label: '备注',
    // rules: 'required',
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 90,
  },
  schema: formSchema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [Drawer, drawerApi] = useVbenDrawer({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: onSubmit,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    const data = drawerApi.getData<SysConfigApi.Config>();
    if (data) {
      formData.value = data;
      await formApi.setValues(formData.value);
    } else {
      formApi.resetForm();
    }
    await markInitialized();
  },
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    const data = await formApi.getValues<SysConfigApi.Config>();
    try {
      await (formData.value?.id
        ? apiUpdate({ id: formData.value.id, ...data })
        : apiAdd(data));
      drawerApi.close();
      emit('success');
    } finally {
      drawerApi.unlock();
    }
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

const getDrawerTitle = computed(() =>
  formData.value?.id ? '修改参数配置' : '新增参数配置',
);
</script>
<template>
  <Drawer class="w-[600px]" :title="getDrawerTitle">
    <BasicForm class="mx-4" />
  </Drawer>
</template>
