<script setup lang="ts">
import type { configAlarmApi } from '#/api';

import { onMounted, ref } from 'vue';

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

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

import { useVbenForm } from '#/adapter/form';
import { createAlarmConfig } from '#/api';
import { $t } from '#/locales';

import { useCreateSchema } from '../data';

const props = defineProps<{
  data: { orgId: string; type: string };
}>();
const emit = defineEmits(['success']);
const formData = ref<configAlarmApi.Alarm>();
const [Form, formApi] = useVbenForm({
  layout: 'vertical',
  schema: useCreateSchema(),
  showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();
      const data = await formApi.getValues();
      try {
        await createAlarmConfig({
          org_id: data.orgId,
          list: [{ key: data.key, value: data.value }],
          type: data.type,
        });
        modalApi.close();
        emit('success');
      } finally {
        // modalApi.close();
        modalApi.lock(false);
      }
    }
  },
});
onMounted(() => {
  formApi.setValues(props.data);
});
function resetForm() {
  formApi.resetForm();
  formApi.setValues(formData.value || {});
}
</script>
<template>
  <Modal>
    <Form>
      <template #prepend-footer>
        <div class="flex-auto">
          <Button type="primary" danger @click="resetForm">
            {{ $t('common.reset') }}
          </Button>
        </div>
      </template>
    </Form>
  </Modal>
</template>

<style scoped></style>
