<script setup lang="ts">
import type { ConfigModel } from '#/api/system/config/model';

import { defineEmits, ref } from 'vue';

import { useVbenDrawer, useVbenForm } from '@vben/common-ui';

import {
  addConfig,
  configDetail,
  updateConfig,
} from '#/api/system/config/config';

import { drawerFormSchema } from './config-data';

const emit = defineEmits<{ reload: [] }>();
const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});
const isUpdateRef = ref<boolean>(false);
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { configId, isUpdate } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate) {
        const dictTypeData = await configDetail(configId);
        await formApi.setValues(dictTypeData);
      }
    } catch (error) {
      console.error(error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
  async onConfirm() {
    try {
      this.confirmLoading = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues<ConfigModel>();
      isUpdateRef.value ? await updateConfig(data) : await addConfig(data);
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
  onClosed() {
    formApi.resetForm();
  },
});
</script>

<template>
  <Drawer :title="isUpdateRef ? '编辑' : '新增'">
    <Form />
  </Drawer>
</template>
