<template>
  <div class="attachment-upload">
    <a-space direction="vertical" :size="16" style="width: 100%">
      <a-form :model="formData" ref="formRef">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="businessType" label="业务类型" required>
              <a-select v-model="formData.businessType" placeholder="请选择业务类型">
                <a-option v-for="type in businessTypes" :key="type.code" :value="type.code">{{ type.name }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="fileType" label="文件类型" required>
              <a-select v-model="formData.fileType" placeholder="请选择文件类型">
                <a-option value="image">图片</a-option>
                <a-option value="document">文档</a-option>
                <a-option value="video">视频</a-option>
                <a-option value="other">其他</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item field="remark" label="文件描述">
          <a-textarea
            v-model="formData.remark"
            placeholder="请输入文件描述"
            :auto-size="{ minRows: 2, maxRows: 5 }"
          />
        </a-form-item>

        <a-form-item field="userDefinedPath" label="自定义路径">
          <a-input
            v-model="formData.userDefinedPath"
            placeholder="请输入自定义路径（可选）"
            allow-clear
          />
        </a-form-item>

        <a-form-item field="files" label="附件上传" required>
          <a-upload
            :default-file-list="fileList"
            multiple
            :action="null"
            list-type="picture-card"
            :custom-request="customRequest"
            @change="handleChange"
          >
            <template #upload-button>
              <div class="upload-trigger">
                <div class="upload-trigger-box">
                  <div class="upload-trigger-text">
                    <IconPlus />
                    <div style="margin-top: 10px">上传文件</div>
                  </div>
                  <div class="upload-trigger-tip">
                    支持单个或批量上传，每个文件不超过100MB
                  </div>
                </div>
              </div>
            </template>
          </a-upload>
        </a-form-item>

        <div class="form-actions">
          <a-button type="primary" @click="handleSubmit" :loading="submitting">提交</a-button>
          <a-button style="margin-left: 10px" @click="resetForm">重置</a-button>
        </div>
      </a-form>
    </a-space>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import { getAttachBusinessTypes, batchAddAttachment } from '@/apis/attach-info'
import type { BusinessType } from '@/apis/attach-info/type'

defineOptions({ name: 'AttachmentUpload' })

const formRef = ref()
const fileList = ref([])
const submitting = ref(false)
const businessTypes = ref<BusinessType[]>([])

interface FileItem {
  file: File
  status: string
  uid: string | number
  name: string
}

const formData = reactive({
  businessType: '',
  fileType: '',
  remark: '',
  userDefinedPath: '',
  files: [] as FileItem[]
})

// 获取业务类型列表
const fetchBusinessTypes = async () => {
  try {
    const res = await getAttachBusinessTypes()
    console.log("res:",res);
    if (res.data) {
      res.data.forEach(item => {
        const key = Object.keys(item)[0];
        const value = item[key];
        businessTypes.value.push({
          name: value,
          code:key
        });
      });
    }
  } catch (error) {
    console.error('获取业务类型失败:', error)
    Message.error('获取业务类型失败')
  }
}

onMounted(() => {
  fetchBusinessTypes()
})

const customRequest = (options: any) => {
  const { file, onProgress, onSuccess, onError } = options
  
  // 保存文件以供后续上传
  const fileItem = {
    file,
    status: 'ready',
    uid: options.fileItem.uid,
    name: options.fileItem.name
  }
  formData.files.push(fileItem)
  
  // 模拟上传进度
  onProgress(0)
  let percent = 0
  const timer = setInterval(() => {
    percent += 10
    onProgress(percent > 100 ? 100 : percent)
    
    if (percent >= 100) {
      clearInterval(timer)
      onSuccess()
    }
  }, 300)
}

const handleChange = (fileList) => {
  console.log('文件列表变化:', fileList)
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    if (!formData.businessType) {
      Message.error('请选择业务类型')
      return
    }
    
    if (formData.files.length === 0) {
      Message.error('请选择要上传的文件')
      return
    }
    
    submitting.value = true
    
    const formDataToSend = new FormData()
    formData.files.forEach((item, index) => {
      formDataToSend.append(`files[${index}]`, item.file)
    })
    
    const params = {
      fileType: formData.fileType,
      remark: formData.remark,
      userDefinedPath: formData.userDefinedPath
    }
    
    const res = await batchAddAttachment(formData.businessType, formDataToSend, params)
    
    if (res) {
      Message.success('文件上传成功')
      resetForm()
    } else {
      Message.error('文件上传失败')
    }
  } catch (error: any) {
    console.error('上传失败:', error)
    Message.error('上传失败: ' + (error.msg || '未知错误'))
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  formRef.value.resetFields()
  fileList.value = []
  formData.files = []
}
</script>

<style scoped lang="scss">
.attachment-upload {
  width: 100%;

  .upload-trigger {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    
    &-box {
      text-align: center;
    }
    
    &-text {
      color: rgb(var(--primary-6));
      font-size: 14px;
    }
    
    &-tip {
      margin-top: 10px;
      color: rgb(var(--gray-6));
      font-size: 12px;
    }
  }

  .form-actions {
    margin-top: 24px;
    text-align: center;
  }
}
</style> 