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

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

// 导入真实的 API 函数
import { getConnectDetail } from '#/api/oilstation/connect/connect';

import { drawerFormSchema } from './connect-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 = await getConnectDetail(id);
        await formApi.setValues(resp);
      }
    } catch (error) {
      console.error('获取连接详情失败:', error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },

  async onConfirm() {
    try {
      drawerApi.confirmLoading(true);
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues();
      // 真实提交数据
      console.log('提交连接数据:', data);
      await (isUpdateRef.value ? updateConnect(data) : addConnect(data));
      // 成功后操作
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存连接信息失败:', error);
    } finally {
      drawerApi.confirmLoading(false);
    }
  },

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

<template>
  <Drawer :title="isUpdateRef ? '编辑交接记录' : '新增交接记录'">
    <Form />
  </Drawer>
</template>
