<template>
  <div>
    <div class="filter-bar">
      <a-date-picker v-model="upload_date" placeholder="上传日期" @change="selfSearch" />
      <a-select
        style="width: 200px"
        v-model="fusetype"
        :options="fusetypes"
        placeholder="分类"
        @change="selfSearch"
        allow-clear
      />
      <a-button type="primary" @click="selfSearch">查询</a-button>
    </div>
    <a-list bordered>
      <a-list-item v-for="item in files" :key="item.days">
        <div class="file-group">
          <h4>{{ item.days }}</h4>
          <div class="file-items">
            <div v-for="file in item.arrays" :key="file.id" class="file-card">
              <img
                :src="getFileUrl(file.f_downloadpath)"
                class="file-image"
                v-if="file.f_filetype.includes('jpg') || file.f_filetype.includes('png')"
                @click="openPreview(file.f_downloadpath)"
                @error="(e) => handleImageError(e, file.f_downloadpath)"
                style="cursor: pointer"
              />
              <p>上传时间: {{ file.f_uploaddate }}</p>
              <p>操作员: {{ file.f_username }}</p>
              <p>分类: {{ file.fusetype }}</p>
              <p>说明: {{ file.fremarks }}</p>
              <a :href="getFileUrl(file.f_downloadpath)" target="_blank">预览</a>
              <a-button v-if="isDelete === '1'" @click="delet(file.id)">删除</a-button>
            </div>
          </div>
        </div>
      </a-list-item>
    </a-list>
    <ImagePreview :src="previewImg" :original-path="previewOriginalPath" :visible="previewVisible" @close="previewVisible = false" @src-updated="handleSrcUpdated" />
  </div>
</template>

<script>
import { post } from '@vue2-client/services/api'
import { del } from '@vue2-client/services/api/restTools'
import ImagePreview from './ImagePreview.vue'
export default {
  props: {
    currUserInfo: {
      type: Object,
      default: () => undefined
    }
  },
  components: { ImagePreview },
  data() {
    return {
      upload_date: null,
      fusetype: null,
      files: [],
      fusetypes: [],
      isDelete: '0',
      previewVisible: false,
      previewImg: '',
      previewOriginalPath: ''
    }
  },
  methods: {
    async getfusetypes() {
      this.fusetypes = [{ label: '全部', value: '' }]
      const res = await post('/api/af-revenue/logic/getFileUseType', {})
      this.fusetypes.push(...res.map(item => ({ label: item.fusetype, value: item.fusetype })))
    },
    async getFiles() {
      if (!this.currUserInfo) return
      this.files = []
      let condition = `f_blobid = '${this.currUserInfo.f_userinfo_id}'`
      if (this.upload_date) {
        condition += ` and CONVERT(VARCHAR(100), f_uploaddate, 23) = '${this.upload_date}'`
      }
      if (this.fusetype) {
        condition += ` and fusetype = '${this.fusetype}'`
      }
      const res = await post('/api/af-revenue/logic/getAllFiles', { data: { condition } })
      this.files = res.days.map(day => ({
        days: day.uploadday,
        arrays: res.array.filter(file => file.uploadday === day.uploadday)
      }))
    },
    async delet(fileId) {
      await del('api/af-revenue/entity/save/t_files', { id: fileId }, { resolveMsg: '删除成功', rejectMsg: '删除失败' })
      this.getFiles()
    },
    selfSearch() {
      this.getFiles()
    },
    openPreview(src) {
      this.previewOriginalPath = src
      this.previewImg = this.getFileUrl(src)
      this.previewVisible = true
    },
    handleImageError(event, path) {
      if (!path || !event.target) return
      const currentSrc = event.target.src || ''
      console.log('列表图片error - currentSrc:', currentSrc, 'path:', path)
      
      if (currentSrc.includes('/files/')) {
        console.log('列表图片: 已经是新格式，不再处理')
        return
      }
      if (!currentSrc.includes('/rs/image/file/')) {
        console.log('列表图片: 不是旧格式，不再处理')
        return
      }
      const baseUrl = `${window.location.protocol}//${window.location.host}`
      // 如果是本地文件路径，尝试新格式（保留目录结构）
      if (path.match(/^[A-Za-z]:[/\\]/)) {
        const normalizedPath = path.replace(/\\/g, '/')
        const filesIndex = normalizedPath.toLowerCase().indexOf('/files/')
        if (filesIndex !== -1) {
          const relativePath = normalizedPath.substring(filesIndex + 1)
          const newUrl = `${baseUrl}/${relativePath}`
          console.log('列表图片: 切换到新格式URL:', newUrl)
          event.target.src = newUrl
        }
      }
    },
    handleSrcUpdated(newUrl) {
      console.log('ImagePreview通知更新路径:', newUrl)
      this.previewImg = newUrl
    },
    getFileUrl(path) {
      if (!path) return ''
      console.log('原始路径:', path)
      // 获取当前域名和端口
      const baseUrl = `${window.location.protocol}//${window.location.host}`
      // 如果是本地文件路径，优先使用新格式（/files/...保留目录结构）
      if (path.match(/^[A-Za-z]:[/\\]/)) {
        const normalizedPath = path.replace(/\\/g, '/')
        const filesIndex = normalizedPath.toLowerCase().indexOf('/files/')
        if (filesIndex !== -1) {
          // 找到 /files/ 位置，使用新格式（保留目录结构）
          const relativePath = normalizedPath.substring(filesIndex + 1)
          const newUrl = `${baseUrl}/${relativePath}`
          console.log('使用新格式路径:', newUrl)
          return newUrl
        } else {
          // 如果路径中没有 /files/，使用旧格式
          const fileName = normalizedPath.split('/').pop()
          const newUrl = `${baseUrl}/rs/image/file/${encodeURIComponent(fileName)}`
          console.log('使用旧格式路径:', newUrl)
          return newUrl
        }
      }
      // 如果已经是HTTP路径，直接返回
      if (path.startsWith('http')) {
        console.log('HTTP路径，直接返回:', path)
        return path
      }
      // 如果是相对路径，添加域名前缀
      if (path.startsWith('/resource/')) {
        const newUrl = `${baseUrl}${path}`
        console.log('相对路径转换:', newUrl)
        return newUrl
      }
      // 如果已经是 /files/ 开头的相对路径，直接添加域名前缀
      if (path.startsWith('/files/')) {
        const newUrl = `${baseUrl}${path}`
        console.log('files相对路径转换:', newUrl)
        return newUrl
      }
      console.log('其他路径，直接返回:', path)
      return path
    }
  },
  mounted() {
    if (this.$login.r.includes('上传附件删除')) {
      this.isDelete = '1'
    }
    this.getFiles()
    this.getfusetypes()
  }
}
</script>

<style scoped>
.filter-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}
.file-group {
  margin-bottom: 15px;
}
.file-items {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.file-card {
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 5px;
  width: 200px;
}
.file-image {
  width: 100%; /* 让图片填充整个容器 */
  height: 150px; /* 调整高度 */
  object-fit: cover; /* 保持图片比例，填充整个区域 */
  border-radius: 5px; /* 圆角边框 */
}
</style>
