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

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

import {
  addAidKitInfo,
  getAidKitInfoDetail,
  updateAidKitInfo,
} from '#/api/system/infoEntry/aidKitInfo/aidKitInfo';

import { drawerFormSchema } from './aidKitInfo-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 res = await getAidKitInfoDetail(id);
        console.log('获取急救箱用品详情数据:', res);
        // 确保从正确的响应结构中获取数据
        const detailData = res?.data || res;

        // 处理表单数据
        const formData = {
          ...detailData,
        };
        await formApi.setValues(formData);
      }
    } 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);
      await (isUpdateRef.value
        ? updateAidKitInfo(data)
        : addAidKitInfo(data));
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存急救箱用品信息失败:', error);
    } finally {
      this.confirmLoading = false;
    }
  },

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

<template>
  <Drawer :title="isUpdateRef ? '编辑急救箱用品' : '新增急救箱用品'">
    <Form>
      <!-- 自定义字段插槽可以在这里添加 -->
    </Form>
  </Drawer>
</template>

<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>