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

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

import {
  addExtinguisher,
  getExtinguisherDetail,
  updateExtinguisher,
} from '#/api/oilstation/extinguisher/extinguisher';

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

const emit = defineEmits<{
  reload: [];
}>();

const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});

// 获取初始数据
onMounted(() => {
  // 初始化操作
});

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 res = await getExtinguisherDetail(id);
        console.log('获取灭火器详情数据:', res);
        // 确保从正确的响应结构中获取数据
        const detailData = res?.data || res;
        await formApi.setValues(detailData);
      }
    } 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();

      // 确保使用正确的字段名提交数据
      const submitData = {
        ...data
      };

      console.log('提交数据:', submitData);
      await (isUpdateRef.value
        ? updateExtinguisher(submitData)
        : addExtinguisher(submitData));
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存灭火器信息失败:', error);
    } finally {
      this.confirmLoading = false;
    }
  },

  onClosed() {
    formApi.resetForm();
  },
});
</script>

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