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

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

import { drawerFormSchema } from './emergency-data';
import { addEmergencyMaterial, getEmergencyMaterialDetail, updateEmergencyMaterial } from '#/api/oilstation/emergency/emergency';

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 response = await getEmergencyMaterialDetail(id.toString());
        const detailData = response?.data || response;
        
        // 处理数据格式，确保与表单字段匹配
        const formData = {
          id: detailData.id,
          remark: detailData.remark || '',
          stationId: detailData.stationId?.toString() || '',
          protectionId: detailData.protectionId?.toString() || '',
          quantity: detailData.quantity || 0,
        };
        await formApi.setValues(formData);
      }
    } catch (error) {
      console.error('获取应急防护详情失败:', error);
      ElMessage.error('获取应急防护详情失败');
    } finally {
      drawerApi.drawerLoading(false);
    }
  },

  async onConfirm() {
    try {
      this.confirmLoading = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues();
      
      // 处理提交数据格式
      const submitData = {
        id: data.id,
        remark: data.remark || '',
        stationId: Number(data.stationId),
        protectionId: Number(data.protectionId),
        quantity: data.quantity,
      };
      
      await (isUpdateRef.value
        ? updateEmergencyMaterial(submitData)
        : addEmergencyMaterial(submitData));
      
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存应急防护信息失败:', error);
      ElMessage.error('保存应急防护信息失败');
    } finally {
      this.confirmLoading = false;
    }
  },

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

<template>
  <Drawer :title="isUpdateRef ? '编辑应急防护' : '新增应急防护'">
    <Form />
  </Drawer>
</template>
