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

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

import { addSecurityCamera, getSecurityCameraDetail, updateSecurityCamera } from '#/api/aiAnalysis/aiAnalysis';
import { drawerFormSchema } from './camera-data';

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

// 响应式变量
const isUpdateRef = 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 { cameraId, isUpdate } = drawerApi.getData();
    isUpdateRef.value = isUpdate;

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

/**
 * 加载摄像头详情数据
 * @param cameraId 摄像头ID
 */
async function loadCameraDetail(cameraId: number | string) {
  try {
    const res = await getSecurityCameraDetail(cameraId);

    // 确保从正确的响应结构中获取数据
    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);

    // 提交请求
    await (isUpdateRef.value
      ? updateSecurityCamera({ ...data, cameraId: drawerApi.getData().cameraId })
      : addSecurityCamera(data));

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

<template>
  <Drawer :title="isUpdateRef ? '编辑摄像头' : '新增摄像头'">
    <Form />
  </Drawer>
</template>

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