<script setup lang="ts">
// @ts-ignore

import { ref } from 'vue';

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

// @ts-ignore
// 这里需要替换为实际的API，如果没有可以先注释
import { handleJoinEmergency } from '#/api/task';

// @ts-ignore
import { drawerFormSchema } from './config-data';

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

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

// 初始化任务参数
const taskParams = ref({
  taskId: '',
  taskName: '',
  taskList: '',
  subFormType: '',
});

// 初始化抽屉组件
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { taskId, taskName, taskList, subFormType } = drawerApi.getData();
      taskParams.value.taskId = taskId;
      taskParams.value.taskName = taskName;
      taskParams.value.taskList = taskList;
      taskParams.value.subFormType = subFormType;

      // 如果有任务数据，填充表单
      if (taskList && taskList.length > 0) {
        formApi.setValues(taskList[0]);
      } else {
        formApi.resetForm();
      }
    } catch (error) {
      console.error(error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
  onClosed() {
    formApi.resetForm();
  },
  async onConfirm() {
    try {
      this.confirmLoading = true;

      // 验证表单
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }

      // 获取表单数据
      const values = await formApi.getValues();

      // 构建提交数据
      const params = {
        id: drawerApi.getData().taskId,
        ...values,
      };

      // 调用API提交数据
      // if (taskParams.value.subFormType === 'participate_emergency_wy') {
      //   await handleJoinEmergency(params);
      // } else if (
      //   taskParams.value.subFormType === 'participate_oil_station_meeting'
      // ) {
      //   await handleAttendanceMeeting(params);
      // }
      await handleJoinEmergency(params);

      // 触发刷新事件
      emit('reload');
      // 关闭抽屉
      drawerApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
});
</script>

<template>
  <Drawer :title="taskParams.taskName">
    <Form />
  </Drawer>
</template>

<style scoped lang="scss">
:deep(.el-input-number) {
  width: 100%;
}
</style>
