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

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

import {
  addGasGun,
  getGasGunDetail,
  updateGasGun,
} from '#/api/oilstation/gasgun/gasgun';

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

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

// 响应式变量
const isUpdateRef = ref<boolean>(false);

// 初始化表单
const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});

// 初始化抽屉
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    await handleDrawerOpen();
  },

  async onConfirm() {
    await handleFormSubmit();
  },

  onClosed() {
    formApi.resetForm();
  },
});

/**
 * 处理抽屉打开逻辑
 */
async function handleDrawerOpen() {
  try {
    drawerApi.drawerLoading(true);
    const { id, isUpdate } = drawerApi.getData();
    isUpdateRef.value = isUpdate;
    
    // 处理编辑模式的数据回显
    if (isUpdate && id) {
      await loadGasGunDetail(id);
    }
  } catch (error) {
    console.error('打开抽屉失败:', error);
  } finally {
    drawerApi.drawerLoading(false);
  }
}

/**
 * 加载油枪详情数据
 * @param id 油枪ID
 */
async function loadGasGunDetail(id: string | number) {
  try {
    const res = await getGasGunDetail(id.toString());
    
    // 确保从正确的响应结构中获取数据
    const detailData = res?.data || res;
    
    // 设置表单值
    await formApi.setValues(detailData);
  } catch (error) {
    console.error('获取油枪详情失败:', error);
  }
}

/**
 * 处理表单提交
 */
async function handleFormSubmit() {
  try {
    // 验证表单
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    
    // 获取表单数据
    const data = await formApi.getValues();
    
    // 提交请求
    await (isUpdateRef.value ? updateGasGun(data) : addGasGun(data));
    
    // 触发重载事件并关闭抽屉
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error('保存油枪信息失败:', error);
  }
}
</script>

<template>
  <Drawer :title="isUpdateRef ? '编辑油枪' : '新增油枪'">
    <Form />
  </Drawer>
</template>
