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

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

import { addSecurityAlert, getSecurityAlertDetail, handleSecurityAlert, updateSecurityAlert } from '#/api/aiAnalysis/aiAnalysis';
import { drawerFormSchema } from './warning-data';

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

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

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

// 初始化抽屉
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 { alertId, isUpdate, isProcess } = drawerApi.getData();
    isUpdateRef.value = isUpdate;
    isProcessRef.value = isProcess;

    // 处理编辑或处理模式的数据回显
    if ((isUpdate || isProcess) && alertId) {
      await loadWarningDetail(alertId);
    }
  } catch (error) {
    console.error('打开抽屉失败:', error);
  } finally {
    drawerApi.drawerLoading(false);
  }
}

/**
 * 加载预警详情数据
 * @param alertId 预警ID
 */
async function loadWarningDetail(alertId: number | string) {
  try {
    const res = await getSecurityAlertDetail(alertId);

    // 确保从正确的响应结构中获取数据
    const detailData = res?.data || res;

    // 设置表单值
    await formApi.setValues(detailData);
  } catch (error) {
    console.error('获取预警详情失败:', error);
  }
}

/**
 * 处理表单提交
 */
async function handleFormSubmit() {
  try {
    // 验证表单
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }

    // 获取表单数据
    const data = await formApi.getValues();
    console.log('表单数据:', data);

    // 提交请求
    if (isProcessRef.value) {
      // 处理预警
      await handleSecurityAlert({
        alertId: drawerApi.getData().alertId,
        handleAction: data.handleAction,
        handleContent: data.handleContent,
      });
    } else {
      // 新增或编辑预警
      await (isUpdateRef.value
        ? updateSecurityAlert({ ...data, alertId: drawerApi.getData().alertId })
        : addSecurityAlert(data));
    }

    // 触发重载事件并关闭抽屉
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error('保存预警信息失败:', error);
  }
}
</script>

<template>
  <Drawer :title="isProcessRef ? '处理预警' : (isUpdateRef ? '编辑预警' : '新增预警')">
    <Form />
  </Drawer>
</template>

<style scoped>
:deep(.vben-drawer-content) {
  padding: 20px;
}
</style>
