<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="getTitle" :width="1024" @ok="handleSubmit">
    <BasicForm @register="registerForm" name="OroqenCultureContentForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../OroqenCultureContent.data';
  import { saveOrUpdate } from '../OroqenCultureContent.api';
  

  // Emits
  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  const rowId = ref('');

  // 表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
    autoSubmitOnEnter: true,
  });

  // 表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    // 重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      // 表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }

    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });
  });

  // 表单标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  /**
   * 上传blob文件
   * @param filePath 文件路径或blob URL
   * @param fieldName 字段名
   * @returns 上传后的文件路径
   */
  async function uploadBlobFile(filePath, fieldName) {
    try {
      console.log('处理文件:', filePath, '字段:', fieldName);
      
      let file;
      let fileName;
      
      if (filePath.startsWith('blob:')) {
        // 从blob URL获取文件
        console.log('从blob URL获取文件');
        const response = await fetch(filePath);
        const blob = await response.blob();
        fileName = `${fieldName}_${Date.now()}.${blob.type.split('/')[1] || 'jpg'}`;
        file = new File([blob], fileName, { type: blob.type });
        
        console.log('从blob URL创建的文件:', file);
      } else {
        console.log('非blob URL，可能是已存在的文件路径');
        return filePath; // 返回原路径，可能是已存在的文件
      }
      
      if (!file) {
        throw new Error('无法获取文件对象');
      }
      
      // 确定业务路径
      let bizPath = 'culture/temp';
      if (fieldName === 'coverImage') {
        bizPath = 'culture/cover';
      }
      
      // 上传文件参数
      const uploadParams = {
        file: file,
        name: 'file',
        filename: fileName,
        data: { 
          biz: bizPath 
        }
      };
      
      console.log('上传参数:', uploadParams);
      
      // 上传文件
      const uploadResult = await defHttp.uploadFile(
        { 
          url: '/sys/common/upload',
          timeout: 30000
        },
        uploadParams,
        { 
          isReturnResponse: true
        }
      );
      
      console.log('上传结果完整信息:', uploadResult);
      
      // 处理可能的undefined情况
      if (!uploadResult) {
        console.error('上传结果为空或undefined');
        throw new Error('上传失败：服务器未返回结果');
      }
      
      // 检查上传结果 - 兼容不同的返回格式
      const isSuccess = uploadResult && (
        uploadResult.success === true || 
        uploadResult.code === 0 || 
        uploadResult.code === 200
      );
      
      if (isSuccess) {
        const filePath = uploadResult.message || uploadResult.result || uploadResult.data;
        console.log('上传成功，文件路径:', filePath);
        return filePath;
      } else {
        console.error('上传失败详细信息:', uploadResult);
        throw new Error(uploadResult?.message || uploadResult?.error || '上传失败，请检查网络连接或联系管理员');
      }
    } catch (error) {
      console.error('上传文件失败:', error);
      throw error;
    }
  }

  /**
   * 提交表单
   */
  async function handleSubmit() {
    try {
      setModalProps({ confirmLoading: true });
      const values = await validate();
      
      // 处理封面图片上传
      if (values.coverImage && typeof values.coverImage === 'string' && values.coverImage.startsWith('blob:')) {
        try {
          const uploadResult = await uploadBlobFile(values.coverImage, 'coverImage');
          values.coverImage = uploadResult;
        } catch (error) {
          console.error('封面图片上传失败:', error);
          throw new Error('封面图片上传失败');
        }
      }
      
      await saveOrUpdate(values, values.id);
      emit('success');
    } catch (error) {
      console.error('表单提交失败:', error);
      createMessage.error(error.message || '操作失败');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  /**
   * 处理文件上传
   */
  async function handleFileUploads(values) {
    // 处理封面图片上传
    if (values.coverImage && typeof values.coverImage === 'string' && values.coverImage.startsWith('blob:')) {
      try {
        const uploadResult = await uploadBlobFile(values.coverImage, 'culture/cover');
        values.coverImage = uploadResult;
      } catch (error) {
        console.error('封面图片上传失败:', error);
        throw new Error('封面图片上传失败');
      }
    }
  }
</script>