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

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

import {
  addEmergencyInfo,
  getEmergencyInfoDetail,
  updateEmergencyInfo,
} from '#/api/system/infoEntry/emergencyInfo/emergencyInfo';
import { getDictOptions } from '#/utils/dict';

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

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

// 字典标识常量
const DICT_KEYS = {
  // 应急防护类型字典标识
  EMERGENCY_PROTECTION_TYPE: 'emergency_protection_type',
};

// 获取字典选项函数
const getDictOptionsByKey = (key: string) => getDictOptions(key);

const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});

// 获取初始数据，确保表单加载时有默认选项
onMounted(async () => {
  // 加载字典数据
  getDictOptionsByKey(DICT_KEYS.EMERGENCY_PROTECTION_TYPE);
});

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 res = await getEmergencyInfoDetail(id);
        console.log('获取应急防护用品详情数据:', res);
        // 确保从正确的响应结构中获取数据
        const detailData = res?.data || res;

        // 处理表单数据
        const formData = {
          ...detailData,
        };
        await formApi.setValues(formData);
      }
    } 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);
      await (isUpdateRef.value
        ? updateEmergencyInfo(data)
        : addEmergencyInfo(data));
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存应急防护用品信息失败:', error);
    } finally {
      this.confirmLoading = false;
    }
  },

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

<template>
  <Drawer :title="isUpdateRef ? '编辑应急防护用品' : '新增应急防护用品'">
    <Form>
      <!-- 自定义字段插槽可以在这里添加 -->
    </Form>
  </Drawer>
</template>

<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
