<script setup lang="ts">
import { ref } from 'vue';

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

import dayjs from 'dayjs';

import {
  createFilter,
  getFilterDetail,
  updateFilter,
} from '#/api/oilstation/filter/filter';

import { drawerFormSchema } from './filter-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 { id, isUpdate } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate && id) {
        const resp: any = await getFilterDetail(id);
        if (resp.stationId) {
          resp.stationId = Number(resp.stationId);
        }
        if (resp.nextReplacementDate) {
          resp.nextReplacementDate = dayjs(resp.nextReplacementDate).format(
            'YYYY-MM-DD HH:mm:ss',
          );
        }
        await formApi.setValues(resp);
      }
    } 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();
      await (isUpdateRef.value ? updateFilter(data) : createFilter(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>
