<!-- src/components/search-form/fields/UploadField.vue -->
<template>
  <el-upload
    :file-list="innerFileList"
    :action="action"
    :headers="headers"
    :multiple="multiple"
    :limit="limit"
    :accept="accept"
    :list-type="listType"
    :disabled="disabled"
    :auto-upload="true"
    :show-file-list="showFileList"
    :on-exceed="handleExceed"
    :before-upload="beforeUpload"
    :on-success="handleSuccess"
    :on-error="handleError"
    :on-remove="handleRemove"
  >
    <el-icon v-if="uploadType === 'image'" class="iconStyle" :size="20">
      <Upload />
    </el-icon>
    <el-button v-else size="small" type="primary" :link="link" :disabled="disabled">
      点击上传文件
    </el-button>
    <template #tip v-if="maxSize || accept">
      <div class="el-upload__tip">
        <span v-if="maxSize">大小不超过 {{ formatFileSize(maxSize) }}</span>
        <span v-if="accept">支持格式：{{ accept }}</span>
      </div>
    </template>
  </el-upload>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import { deepEqual } from '@/utils/csf-deepEqual'
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  action: String,
  headers: Object,
  multiple: Boolean,
  limit: Number,
  accept: String,
  listType: { type: String, default: 'text' },
  disabled: Boolean,
  showFileList: Boolean,
  uploadType: String,
  link: Boolean,
  maxSize: Number
})

const emit = defineEmits(['update:modelValue'])

// 内部状态：不能直接改 props.modelValue
const innerFileList = ref([...props.modelValue])

// 监听外部 modelValue 变化（如重置表单）
watch(
  () => props.modelValue,
  (newVal, oldVal) => {
    if (!deepEqual(newVal, oldVal)) {
      innerFileList.value = [...(newVal || [])]
    }
  },
  { deep: true }
)

// 格式化文件大小
function formatFileSize(bytes) {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 文件上传前校验
function beforeUpload(file) {
  if (props.maxSize && file.size > props.maxSize) {
    ElMessage.error(`文件 ${file.name} 超出大小限制（最大 ${formatFileSize(props.maxSize)}）`)
    return false
  }
  if (props.accept) {
    const allowed = props.accept.split(',').map(ext => ext.trim().toLowerCase())
    const fileExt = '.' + file.name.split('.').pop().toLowerCase()
    if (!allowed.includes(fileExt)) {
      ElMessage.error(`文件类型不支持，仅支持：${props.accept}`)
      return false
    }
  }
  return true
}

// 上传成功
function handleSuccess(response, file) {
  const data = response.data || response
  const url = data.url || data.fileUrl || data.path
  const name = data.name || data.fileName || file.name

  if (!url) {
    ElMessage.error('上传成功但未返回文件地址')
    return
  }

  // 找到当前文件并更新 url 和 name
  const target = innerFileList.value.find(f => f.uid === file.uid)
  if (target) {
    target.url = url
    target.name = name
  }

  // 同步回父组件
  emit('update:modelValue', [...innerFileList.value])
  ElMessage.success(`文件 ${file.name} 上传成功`)
}

// 超出数量限制
function handleExceed() {
  ElMessage.warning('超出文件数量限制')
}

// 上传失败
function handleError(err, file) {
  ElMessage.error(`文件 ${file.name} 上传失败`)
  console.error('Upload error:', err)
}

// 删除文件
function handleRemove(file) {
  emit('update:modelValue', [...innerFileList.value])
}

// 暴露内部 fileList（可选，用于高级控制）
defineExpose({
  fileList: innerFileList
})
</script>

<style scoped>
.iconStyle {
  color: #409eff;
}
</style>