<template>
  <view class="event-info-page">
    <!-- 附件下载区 -->
    <view class="attachments-section" v-if="attachments.length > 0">
      <view class="section-title">
        <text class="title-icon">📎</text>
        <text class="title-text">相关附件</text>
      </view>
      <view class="attachments-list">
        <view class="attachment-item" v-for="(file, index) in attachments" :key="index" @click="downloadFile(file)">
          <view class="file-info">
            <text class="file-icon">{{ getFileIcon(file.fileType) }}</text>
            <view class="file-details">
              <text class="file-name">{{ file.fileName }}</text>
              <text class="file-size">{{ file.fileSize }}</text>
            </view>
          </view>
          <view class="download-btn">
            <text class="download-icon">⬇</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 信息列表 -->
    <view class="info-list">
      <view class="info-item" v-for="(item, index) in infoList" :key="index" @click="handleItemClick(item)">
        <view class="info-header">
          <view class="info-tag" :class="item.type">{{ item.typeText }}</view>
          <view class="info-time">{{ item.time }}</view>
        </view>
        <view class="info-title">{{ item.title }}</view>
        <view class="info-desc">{{ item.desc }}</view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="infoList.length === 0 && attachments.length === 0">
      <text class="empty-text">暂无信息发布</text>
    </view>
  </view>
</template>

<script>
import infoAPI from '@/api/info.js'
import competitionAPI from '@/api/competition.js'

export default {
  data() {
    return {
      eventId: '',
      infoList: [],
      attachments: []
    };
  },
  onLoad(options) {
    if (options.eventId) {
      this.eventId = options.eventId
      this.loadInfoList(options.eventId)
      this.loadAttachments(options.eventId)
    }
  },
  methods: {
    /**
     * 加载附件列表
     */
    async loadAttachments(eventId) {
      try {
        const res = await competitionAPI.getAttachments({
          competitionId: eventId,
          type: 'info'
        })

        let list = []
        if (res && Array.isArray(res)) {
          list = res
        } else if (res && res.records) {
          list = res.records
        } else if (res && res.data && Array.isArray(res.data)) {
          list = res.data
        }

        if (list.length > 0) {
          this.attachments = list.map(file => ({
            id: file.id,
            fileName: file.fileName || file.name,
            fileUrl: file.fileUrl || file.url,
            fileSize: this.formatFileSize(file.fileSize || file.size),
            fileType: file.fileType || this.getFileType(file.fileName || file.name)
          }))
        }
      } catch (err) {
        console.error('加载附件失败:', err)
      }
    },

    /**
     * 加载信息发布列表
     */
    async loadInfoList(eventId) {
      try {
        const res = await infoAPI.getInfoPublishList({ competitionId: eventId })

        let list = []
        if (res.records) {
          list = res.records
        } else if (Array.isArray(res)) {
          list = res
        }

        // 数据映射
        this.infoList = list.map(item => ({
          id: item.id,
          type: this.getInfoType(item.infoType || item.info_type || item.type),
          typeText: this.getInfoTypeText(item.infoType || item.info_type || item.type),
          title: item.title || item.infoTitle,
          desc: item.content || item.description || item.infoContent || '',
          time: this.formatTime(item.publishTime || item.publish_time || item.createTime)
        }))
      } catch (err) {
        console.error('加载信息列表失败:', err)
      }
    },

    /**
     * 下载文件
     */
    downloadFile(file) {
      const fileExt = file.fileType || this.getFileType(file.fileName) || 'pdf'

      // #ifdef H5
      const link = document.createElement('a')
      link.href = file.fileUrl
      link.download = file.fileName
      link.target = '_blank'
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      uni.showToast({
        title: '开始下载',
        icon: 'success'
      })
      return
      // #endif

      // #ifndef H5
      uni.showLoading({ title: '准备下载' })
      uni.downloadFile({
        url: file.fileUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.openDocument({
              filePath: res.tempFilePath,
              fileType: fileExt,
              success: () => {
                uni.hideLoading()
                uni.showToast({ title: '打开成功', icon: 'success' })
              },
              fail: (err) => {
                uni.hideLoading()
                console.error('打开文件失败:', err)
                uni.showToast({ title: '打开失败', icon: 'none' })
              }
            })
          }
        },
        fail: (err) => {
          uni.hideLoading()
          console.error('下载失败:', err)
          uni.showToast({ title: '下载失败', icon: 'none' })
        }
      })
      // #endif
    },

    /**
     * 获取文件类型
     */
    getFileType(fileName) {
      if (!fileName) return 'pdf'
      const ext = fileName.split('.').pop().toLowerCase()
      return ext
    },

    /**
     * 获取文件图标
     */
    getFileIcon(fileType) {
      const iconMap = {
        'pdf': '📕',
        'doc': '📘',
        'docx': '📘',
        'xls': '📗',
        'xlsx': '📗',
        'ppt': '📙',
        'pptx': '📙',
        'txt': '📄',
        'zip': '📦',
        'rar': '📦'
      }
      return iconMap[fileType] || '📄'
    },

    /**
     * 格式化文件大小
     */
    formatFileSize(bytes) {
      if (!bytes || bytes === 0) return '0 B'
      if (typeof bytes === 'string') return bytes

      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
    },

    /**
     * 获取信息类型样式类名
     */
    getInfoType(type) {
      const typeMap = {
        1: 'notice',
        2: 'announcement',
        3: 'important',
        'notice': 'notice',
        'announcement': 'announcement',
        'important': 'important'
      }
      return typeMap[type] || 'notice'
    },

    /**
     * 获取信息类型文本
     */
    getInfoTypeText(type) {
      const typeMap = {
        1: '通知',
        2: '公告',
        3: '重要',
        'notice': '通知',
        'announcement': '公告',
        'important': '重要'
      }
      return typeMap[type] || '通知'
    },

    /**
     * 格式化时间
     */
    formatTime(timeStr) {
      if (!timeStr) return ''

      const date = new Date(timeStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}`
    },

    handleItemClick(item) {
      uni.navigateTo({
        url: `/pages/event-info-detail/event-info-detail?id=${item.id}&type=${item.type}&typeText=${encodeURIComponent(item.typeText)}&title=${encodeURIComponent(item.title)}&content=${encodeURIComponent(item.desc)}&time=${encodeURIComponent(item.time)}`
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.event-info-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx 30rpx;
}

// 区块标题
.section-title {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-bottom: 20rpx;
  padding: 0 10rpx;
}

.title-icon {
  font-size: 32rpx;
}

.title-text {
  font-size: 30rpx;
  font-weight: bold;
  color: #333333;
}

// 附件下载区
.attachments-section {
  margin-bottom: 30rpx;
}

.attachments-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.attachment-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 25rpx 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s;

  &:active {
    background-color: #f8f8f8;
    transform: scale(0.98);
  }
}

.file-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
  flex: 1;
  min-width: 0;
}

.file-icon {
  font-size: 48rpx;
  flex-shrink: 0;
}

.file-details {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-size: 24rpx;
  color: #999999;
}

.download-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #C93639;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.download-icon {
  font-size: 32rpx;
  color: #fff;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.info-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
}

.info-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15rpx;
}

.info-tag {
  font-size: 24rpx;
  padding: 8rpx 20rpx;
  border-radius: 8rpx;
  color: #fff;
}

.info-tag.notice {
  background-color: #C93639;
}

.info-tag.announcement {
  background-color: #FF8C00;
}

.info-tag.important {
  background-color: #DC143C;
}

.info-time {
  font-size: 24rpx;
  color: #999999;
}

.info-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 10rpx;
  line-height: 1.4;
}

.info-desc {
  font-size: 26rpx;
  color: #666666;
  line-height: 1.6;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.empty-state {
  padding: 200rpx 0;
  text-align: center;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}
</style>
