<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 isUpdate = ref(false);

const formSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'id',
    label: 'id',
  },
  {
    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>();
    isUpdate.value = !!data?.id;
    if (isUpdate.value) {
      await formApi.setValues(data);
    } 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 (isUpdate.value ? apiUpdate(data) : apiAdd(data));
      drawerApi.close();
      emit('success');
    } finally {
      drawerApi.unlock();
    }
  }
}

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

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