<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useVbenDrawer, useVbenForm } from '@vben/common-ui';
import { addCustomerComplaint, updateCustomerComplaint, getCustomerComplaintDetail } from '#/api/archive/operationsManagement/operationsManagement';
import { drawerFormSchema, formatAttachmentImages } from './config-data';

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

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

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

// 初始化抽屉
const [Drawer, drawerApi] = useVbenDrawer({
  showFooter: true,
  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 loadCustomerComplaintDetail(id);
    }
  } catch (error) {
    console.error('打开抽屉失败:', error);
  } finally {
    drawerApi.drawerLoading(false);
  }
}

/**
 * 加载客户投诉详情数据
 * @param id 客户投诉ID
 */
async function loadCustomerComplaintDetail(id: string | number) {
  try {
    const res = await getCustomerComplaintDetail(id);
    console.log('获取客户投诉详情数据:', res);
    
    // 确保从正确的响应结构中获取数据
    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) {
  return {
    ...detailData,
    // 保持 attachmentImages 为字符串格式，逗号隔开
    attachmentImages: detailData.attachmentImages || '',
    // 处理 attachmentImagesUrl 字段，确保为数组格式
    attachmentImagesUrl: formatAttachmentImages(detailData),
  };
}

/**
 * 处理表单提交
 */
async function handleFormSubmit() {
  try {
    // 验证表单
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    
    // 获取表单数据
    const data = await formApi.getValues();
    console.log('表单数据:', data);
    
    // 处理数据
    const processedData = processFormData(data);
    
    // 提交请求
    await (isUpdateRef.value ? updateCustomerComplaint(processedData) : addCustomerComplaint(processedData));
    
    // 触发重载事件并关闭抽屉
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error('保存客户投诉信息失败:', error);
  }
}

/**
 * 处理表单数据
 * @param data 表单数据
 * @returns 处理后的数据
 */
function processFormData(data: any) {
  // 处理图片数据
  let attachmentImages = data.attachmentImages || '';
  
  // 如果有 attachmentImagesUrl，优先使用其中的 name 构建 attachmentImages
  if (Array.isArray(data.attachmentImagesUrl) && data.attachmentImagesUrl.length > 0) {
    // 检查是否有上传响应数据
    if (data.attachmentImagesUrl[0].response) {
      attachmentImages = data.attachmentImagesUrl
        .map((item: any) => item.response.data.fileName)
        .join(',');
    } else if (data.attachmentImagesUrl[0].name) {
      // 检查是否有 name 属性
      attachmentImages = data.attachmentImagesUrl
        .map((item: any) => item.name)
        .join(',');
    }
  }
  
  // 构建返回数据，排除 attachmentImagesUrl 字段
  const { attachmentImagesUrl, ...restData } = data;
  
  return {
    ...restData,
    attachmentImages: attachmentImages || '',
  };
}

// 初始化组件
onMounted(() => {
  // 组件挂载时的初始化逻辑
});
</script>
<template>
  <Drawer :title="isUpdateRef ? '编辑客户投诉' : '新增客户投诉'">
    <Form />
  </Drawer>
</template>
