<script setup lang="ts">
import { ref } from 'vue';
import { useVbenDrawer, useVbenForm } from '@vben/common-ui';
import { addTaskEventReport, updateTaskEventReport, getTaskEventReportDetail } from '#/api/archive/HSSE/HSSE';
import { drawerFormSchema, processFormData } from './eventReport-data';

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

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

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

// 初始化抽屉
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 loadEventReportDetail(id);
    } else {
      // 重置表单
      formApi.resetForm();
    }
  } catch (error) {
    console.error('打开抽屉失败:', error);
  } finally {
    drawerApi.drawerLoading(false);
  }
}

/**
 * 加载事件报告详情数据
 * @param id 事件报告ID
 */
async function loadEventReportDetail(id: string | number) {
  try {
    const detail = await getTaskEventReportDetail(id);
    console.log('获取事件报告详情数据:', detail);
    
    // 构建表单数据
    const formData = buildFormData(detail);
    
    // 设置表单值
    await formApi.setValues(formData);
  } catch (error) {
    console.error('获取事件报告详情失败:', error);
  }
}

/**
 * 构建表单数据
 * @param detailData 详情数据
 * @returns 格式化后的表单数据
 */
function buildFormData(detailData: any) {
  return {
    ...detailData,
    isSubmitted: detailData.processStage === 1,
    images: detailData.images || '',
    imagesUrl: formatImagesUrl(detailData),
  };
}
function formatImagesUrl(detailData: any) {
  if (!detailData.imagesUrl) {
    return [];  
  }
  
  // 处理数组格式
  if (Array.isArray(detailData.imagesUrl)) {
    return detailData.imagesUrl.map((url: string, index: number) => ({
      name: detailData.images?.split(',')[index] || `文件${index + 1}`,
      url,
      status: 'success',
      uid: Date.now() + index,
    }));
  }
  
  // 处理字符串格式
  if (typeof detailData.imagesUrl === 'string') {
    return [{
      name: detailData.imagesUrl.split('/').pop() || '未知文件',
      url: detailData.imagesUrl,
      status: 'success',
      uid: Date.now(),
    }];
  }
  
  return [];
}

/**
 * 处理表单提交
 */
async function handleFormSubmit() {
  try {
    // 验证表单
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    
    // 获取表单数据
    const data = await formApi.getValues();
    console.log('表单数据:', data);
    
    // 处理数据
    const processedData = processFormData(data);
    
    // 提交请求
    if (isUpdateRef.value) {
      await updateTaskEventReport(processedData);
    } else {
      await addTaskEventReport(processedData);
    }
    
    // 触发重载事件并关闭抽屉
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error('保存事件报告失败:', error);
  }
}
</script>
<template>
  <Drawer :title="isUpdateRef ? '编辑事件报告' : '新增事件报告'">
    <Form />
  </Drawer>
</template>
