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

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

// 导入API
import {
  addAsset,
  getAssetDetail,
  updateAsset,
} from '#/api/system/asset/asset';

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

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;
    }
    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 loadArchivesDetail(id);
    }
  } catch (error) {
    console.error('打开抽屉失败:', error);
  } finally {
    drawerApi.drawerLoading(false);
  }
}

/**
 * 加载资产档案详情数据
 * @param id 资产档案ID
 */
async function loadArchivesDetail(id: number | string) {
  try {
    const res = await getAssetDetail(id.toString());

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

    // 构建表单数据
    const formData = buildFormData(detailData);

    // 设置表单值
    await formApi.setValues(formData);
  } catch (error) {
    console.error('获取资产档案详情失败:', error);
  }
}

/**
 * 构建表单数据
 * @param detailData 详情数据
 * @returns 格式化后的表单数据
 */
function buildFormData(detailData: any) {
  if (!detailData.alertType) {
    detailData.alertType = '日';
  }
  if (detailData.typeId) {
    detailData.typeId = detailData.typeId.toString();
  }

  return {
    ...detailData,
    // 保持 attachments 为字符串格式，逗号隔开
    attachments: detailData.attachments || '',
    // 处理 attachmentsUrl 字段，确保为数组格式
    attachmentsUrl: formatAttachmentsUrl(detailData),
  };
}

/**
 * 格式化附件路径
 * @param detailData 详情数据
 * @returns 格式化后的数组
 */
function formatAttachmentsUrl(detailData: any) {
  if (!detailData.attachmentsUrl) {
    return [];
  }

  // 处理数组格式
  if (Array.isArray(detailData.attachmentsUrl)) {
    return detailData.attachmentsUrl.map((url: string, index: number) => ({
      name: detailData.attachments?.split(',')[index] || `文件${index + 1}`,
      url,
      status: 'success',
      uid: Date.now() + index,
    }));
  }

  // 处理字符串格式
  if (typeof detailData.attachmentsUrl === 'string') {
    return [
      {
        name: detailData.attachmentsUrl.split('/').pop() || '未知文件',
        url: detailData.attachmentsUrl,
        status: 'success',
        uid: Date.now(),
      },
    ];
  }

  return [];
}

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

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

    // 处理数据
    const processedData = processFormData(data);
    delete processedData.attachmentsUrl;
    console.log('提交数据:', processedData);

    // 提交请求
    await (isUpdateRef.value
      ? updateAsset(processedData)
      : addAsset(processedData));

    // 触发重载事件并关闭抽屉
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error('保存资产档案信息失败:', error);
  } finally {
    drawerApi.drawerLoading(false);
  }
}

/**
 * 处理表单数据
 * @param data 表单数据
 * @returns 处理后的数据
 */
function processFormData(data: any) {
  // 处理附件
  if (
    Array.isArray(data.attachmentsUrl) &&
    data.attachmentsUrl.length > 0 && // 检查是否有上传响应数据
    data.attachmentsUrl[0].response
  ) {
    data.attachments = data.attachmentsUrl
      .map((item: any) => item.response.data.fileName)
      .join(',');
  }

  return data;
}
</script>

<template>
  <Drawer :title="isUpdateRef ? '编辑资产档案' : '新增资产档案'">
    <Form />
  </Drawer>
</template>
