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

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

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

const emit = defineEmits(['Confirm']);

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 data = drawerApi.getData();
      console.log(data);
      
      isUpdateRef.value = data.isUpdate;
      if (data.isUpdate && data.id) {
        await formApi.setValues(data);
      }
    } 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);
      
      // 模拟提交数据
      console.log('提交数据:', data);
      emit('Confirm', data);
    } catch (error) {
      console.error('保存检查表单信息失败:', error);
    } finally {
      this.confirmLoading = false;
    }
  },

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

<template>
  <Drawer :title="isUpdateRef ? '编辑检查表单' : '新增检查表单'">
    <Form />
  </Drawer>
</template>
