<script setup lang="ts">
import type { DictData } from '#/api/system/dict/dict-data-model';

import { defineEmits, ref } from 'vue';

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

import {
  addDictData,
  dictDetailInfo,
  updateDictData,
} from '#/api/system/dict/dict-data';

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 { dictCode, dictType, isUpdate } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      await formApi.setFieldValue('dictType', dictType);
      if (isUpdate) {
        const dictData = await dictDetailInfo(dictCode);
        await formApi.setValues(dictData);
      }
    } 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<DictData>();
      isUpdateRef.value ? await updateDictData(data) : await addDictData(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>
<style scoped lang="scss">
:deep(.el-input-number) {
  width: 100%;
}
</style>
