<template>
  <div class="component-upload-file-preview">
    <el-upload
      multiple
      :disabled="disabled"
      :action="uploadFileUrl"
      list-type="picture-card"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :data="data"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      ref="fileUpload"
      :before-remove="handleDelete"
      :show-file-list="false"
      :headers="headers"
      :class="{ hide: fileList.length >= limit }"
    >
      <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>

    <!-- 自定义文件列表 -->
    <div class="file-list-container">
      <div
        v-for="(file, index) in fileList"
        :key="index"
        class="file-item"
        @click="handlePreview(file)"
      >
        <!-- 图片缩略图 -->
        <div v-if="getFileType(file.name) === 'image'" class="file-preview">
          <img :src="file.url" alt="" />
        </div>

        <!-- 视频缩略图 -->
        <div v-else-if="getFileType(file.name) === 'video'" class="file-preview video-preview">
          <video :src="file.url" style="width: 100%; height: 100%; object-fit: cover;"></video>
          <div class="file-type-overlay">
            <el-icon :size="40"><VideoPlay /></el-icon>
          </div>
        </div>

        <!-- 文档缩略图 -->
        <div v-else class="file-preview doc-preview">
          <div class="doc-icon">
            <el-icon :size="50" v-if="getDocIcon(file.name) === 'pdf'"><Document /></el-icon>
            <el-icon :size="50" v-else-if="getDocIcon(file.name) === 'word'"><Memo /></el-icon>
            <el-icon :size="50" v-else-if="getDocIcon(file.name) === 'excel'"><Tickets /></el-icon>
            <el-icon :size="50" v-else-if="getDocIcon(file.name) === 'ppt'"><Notebook /></el-icon>
            <el-icon :size="50" v-else><Document /></el-icon>
          </div>
          <div class="doc-ext">{{ getFileExt(file.name) }}</div>
        </div>

        <!-- 删除按钮 -->
        <div class="file-actions" v-if="!disabled">
          <el-icon class="delete-icon" @click.stop="handleRemove(index)"><Delete /></el-icon>
        </div>

        <!-- 文件名 -->
        <div class="file-name" :title="getFileName(file.name)">{{ getFileName(file.name) }}</div>
      </div>
    </div>

    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip && !disabled">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
      </template>
      的文件
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="previewTitle"
      width="800px"
      append-to-body
    >
      <!-- 图片预览 -->
      <img
        v-if="previewType === 'image'"
        :src="dialogFileUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />

      <!-- 视频预览 -->
      <video
        v-else-if="previewType === 'video'"
        :src="dialogFileUrl"
        controls
        style="display: block; max-width: 100%; margin: 0 auto"
      ></video>

      <!-- 文档预览（提供下载链接） -->
      <div v-else-if="previewType === 'document'" style="text-align: center; padding: 40px;">
        <el-icon :size="60" color="#909399"><Document /></el-icon>
        <p style="margin-top: 20px; color: #606266;">{{ previewFileName }}</p>
        <el-button type="primary" @click="downloadFile" style="margin-top: 20px;">
          <el-icon><Download /></el-icon>
          下载文件
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth"
import { isExternal } from "@/utils/validate"
import Sortable from 'sortablejs'
import { Plus, Document, Download, VideoPlay, Delete, Memo, Tickets, Notebook } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: [String, Object, Array],
  // 上传接口地址
  action: {
    type: String,
    default: "/common/upload"
  },
  // 上传携带的参数
  data: {
    type: Object
  },
  // 数量限制
  limit: {
    type: Number,
    default: 10
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 50
  },
  // 文件类型
  fileType: {
    type: Array,
    default: () => ["jpg", "jpeg", "png", "gif", "bmp", "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "mp4", "avi", "mov", "wmv", "flv", "mkv"]
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  // 禁用组件（仅查看）
  disabled: {
    type: Boolean,
    default: false
  },
  // 拖动排序
  drag: {
    type: Boolean,
    default: true
  }
})

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const number = ref(0)
const uploadList = ref([])
const dialogFileUrl = ref("")
const dialogVisible = ref(false)
const previewType = ref("")
const previewTitle = ref("预览")
const previewFileName = ref("")
const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + props.action)
const headers = ref({ Authorization: "Bearer " + getToken() })
const fileList = ref([])
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
)

// 图片扩展名
const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']
// 视频扩展名
const videoExts = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm']
// 文档扩展名
const documentExts = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']

// 获取文件类型
function getFileType(fileName) {
  const ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
  if (imageExts.includes(ext)) return 'image'
  if (videoExts.includes(ext)) return 'video'
  if (documentExts.includes(ext)) return 'document'
  return 'unknown'
}

// 获取文档图标类型
function getDocIcon(fileName) {
  const ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
  if (ext === 'pdf') return 'pdf'
  if (['doc', 'docx'].includes(ext)) return 'word'
  if (['xls', 'xlsx'].includes(ext)) return 'excel'
  if (['ppt', 'pptx'].includes(ext)) return 'ppt'
  return 'document'
}

// 获取文件扩展名
function getFileExt(fileName) {
  return fileName.substring(fileName.lastIndexOf('.') + 1).toUpperCase()
}

// 获取文件名
function getFileName(name) {
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1)
  } else {
    return name
  }
}

// 获取文件图标
function getFileIcon(fileName) {
  const type = getFileType(fileName)
  if (type === 'image') return null // 图片显示缩略图
  if (type === 'video') return 'video-play'
  if (type === 'document') {
    const ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
    if (ext === 'pdf') return 'document'
    if (['doc', 'docx'].includes(ext)) return 'document'
    if (['xls', 'xlsx'].includes(ext)) return 'tickets'
    if (['ppt', 'pptx'].includes(ext)) return 'notebook'
    return 'document'
  }
  return 'document'
}

watch(() => props.modelValue, val => {
  if (val) {
    const list = Array.isArray(val) ? val : props.modelValue.split(",")
    fileList.value = list.map(item => {
      let fileObj = {}
      if (typeof item === "string") {
        const url = item.indexOf(baseUrl) === -1 && !isExternal(item) ? baseUrl + item : item
        fileObj = { name: item, url: url }

        // 为非图片文件设置自定义图标
        const type = getFileType(item)
        if (type !== 'image') {
          fileObj.url = url // 保留实际URL用于下载
          // 这里可以设置一个占位图标URL，或者通过CSS处理
        }
      } else {
        fileObj = item
      }
      return fileObj
    })
  } else {
    fileList.value = []
  }
}, { deep: true, immediate: true })

// 上传前校验
function handleBeforeUpload(file) {
  // 校验文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.')
    const fileExt = fileName[fileName.length - 1].toLowerCase()
    const isTypeOk = props.fileType.includes(fileExt)
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确，请上传${props.fileType.join("/")}格式文件!`)
      return false
    }
  }

  // 校验文件名
  if (file.name.includes(',')) {
    proxy.$modal.msgError('文件名不正确，不能包含英文逗号!')
    return false
  }

  // 校验文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`)
      return false
    }
  }

  proxy.$modal.loading("正在上传文件，请稍候...")
  number.value++
  return true
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`)
}

// 上传成功
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    uploadList.value.push({ name: res.fileName, url: res.fileName })
    uploadedSuccessfully()
  } else {
    number.value--
    proxy.$modal.closeLoading()
    proxy.$modal.msgError(res.msg)
    proxy.$refs.fileUpload.handleRemove(file)
    uploadedSuccessfully()
  }
}

// 删除文件
function handleDelete(file) {
  const findex = fileList.value.map(f => f.name).indexOf(file.name)
  if (findex > -1 && uploadList.value.length === number.value) {
    fileList.value.splice(findex, 1)
    emit("update:modelValue", listToString(fileList.value))
    return false
  }
}

// 移除文件（通过索引）
function handleRemove(index) {
  fileList.value.splice(index, 1)
  emit("update:modelValue", listToString(fileList.value))
}

// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value)
    uploadList.value = []
    number.value = 0
    emit("update:modelValue", listToString(fileList.value))
    proxy.$modal.closeLoading()
  }
}

// 上传失败
function handleUploadError() {
  proxy.$modal.msgError("上传文件失败")
  proxy.$modal.closeLoading()
}

// 预览文件
function handlePreview(file) {
  const fileName = file.name || file.url
  const type = getFileType(fileName)

  previewType.value = type
  previewFileName.value = fileName.substring(fileName.lastIndexOf('/') + 1)

  if (type === 'image') {
    previewTitle.value = "图片预览"
    dialogFileUrl.value = file.url
  } else if (type === 'video') {
    previewTitle.value = "视频预览"
    dialogFileUrl.value = file.url
  } else {
    previewTitle.value = "文件信息"
    dialogFileUrl.value = file.url
  }

  dialogVisible.value = true
}

// 下载文件
function downloadFile() {
  window.open(dialogFileUrl.value, '_blank')
}

// 对象转字符串
function listToString(list, separator) {
  let strs = ""
  separator = separator || ","
  for (let i in list) {
    if (list[i].url && list[i].url.indexOf("blob:") !== 0) {
      strs += list[i].url.replace(baseUrl, "") + separator
    }
  }
  return strs !== "" ? strs.substr(0, strs.length - 1) : ""
}

// 初始化拖拽排序
onMounted(() => {
  if (props.drag && !props.disabled) {
    nextTick(() => {
      const element = proxy.$refs.fileUpload?.$el?.querySelector('.el-upload-list')
      if (element) {
        Sortable.create(element, {
          onEnd: (evt) => {
            const movedItem = fileList.value.splice(evt.oldIndex, 1)[0]
            fileList.value.splice(evt.newIndex, 0, movedItem)
            emit('update:modelValue', listToString(fileList.value))
          }
        })
      }
    })
  }
})
</script>

<style scoped lang="scss">
.component-upload-file-preview {
    width: 100%;
  // 隐藏上传按钮
  :deep(.hide .el-upload--picture-card) {
    display: none;
  }

  // 禁用时隐藏上传按钮
  :deep(.el-upload.el-upload--picture-card.is-disabled) {
    display: none !important;
  }

  :deep(.el-upload.el-upload--picture-card) {
    float: left;
    margin-top: 8px;
    margin-right: 8px;
  }


  // 文件列表容器
  .file-list-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 8px;
  }

  // 文件项
  .file-item {
    position: relative;
    width: 148px;
    height: 148px;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    flex-direction: column;

    &:hover {
      border-color: #409eff;
      transform: scale(1.02);

      .file-actions {
        opacity: 1;
      }
    }

    // 文件预览区
    .file-preview {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f7fa;
      position: relative;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      // 视频预览
      &.video-preview {
        position: relative;

        .file-type-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.3);
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
        }
      }

      // 文档预览
      &.doc-preview {
        flex-direction: column;
        padding: 10px;

        .doc-icon {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #909399;
        }

        .doc-ext {
          font-size: 12px;
          color: #606266;
          font-weight: 500;
          margin-top: 5px;
        }
      }
    }

    // 文件名
    .file-name {
      padding: 5px 8px;
      font-size: 12px;
      color: #606266;
      background: #fff;
      border-top: 1px solid #c0ccda;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      text-align: center;
    }

    // 操作按钮
    .file-actions {
      position: absolute;
      top: 5px;
      right: 5px;
      opacity: 0;
      transition: opacity 0.3s;
      z-index: 10;

      .delete-icon {
        width: 24px;
        height: 24px;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        cursor: pointer;

        &:hover {
          background: #f56c6c;
        }
      }
    }
  }
}
</style>
