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

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

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 mockDetail = {
          id,
          stationName: `油站${(id % 3) + 1}`,
          filterNo: `FL-2025000${id}`,
          filterModel: `F-Model-00${(id % 3) + 1}`,
          dispenserModel: `D-Model-00${(id % 3) + 1}`,
          relatedGun: `${id}#`,
          relatedOil: `${['92#汽油', '95#汽油', '0#柴油'][id % 3]}`,
          totalFilteredLiters: 10000 + id * 1000,
          nextReplaceDate: `2025-12-${String(15 + id).padStart(2, '0')}`,
        };
        await formApi.setValues(mockDetail);
      }
    } 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();
      // 模拟提交数据
      console.log('提交过滤器数据:', 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>
