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

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

import { drawerFormSchema } from './connectInfo-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 mockDetail = {
          id,
          station: `油站${id}`,
          supervisor: `监交人${id}`,
          startDate: '2024-01-01',
          onlineDuration: 7,
          followUpDuration: 30,
          link: `环节${id}`,
          personInCharge: `负责人${id}`,
          needSupervisor: '是',
          taskName: `事项${id}`,
          needCompare: '是',
          guidance: `要求指引${id}`,
          needPhoto: '是',
          needAttachment: '是',
        };
        await formApi.setValues(mockDetail);
      }
    } 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);
      // 模拟成功
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存交接事项信息失败:', error);
    } finally {
      this.confirmLoading = false;
    }
  },

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

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