<template>
  <view class="event-schedule-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="date-tabs" v-if="dates.length > 0">
      <view
        class="date-tab"
        v-for="(date, index) in dates"
        :key="index"
        :class="{ active: currentDate === index }"
        @click="currentDate = index"
      >
        <view class="date-day">{{ date.day }}</view>
        <view class="date-text">{{ date.text }}</view>
      </view>
    </view>

    <!-- 日程时间线 -->
    <view class="schedule-timeline" v-if="currentSchedule.length > 0">
      <view class="timeline-item" v-for="(item, index) in currentSchedule" :key="index">
        <view class="time-dot"></view>
        <view class="time-line" v-if="index < currentSchedule.length - 1"></view>
        <view class="schedule-card">
          <view class="schedule-time">{{ item.time }}</view>
          <view class="schedule-title">{{ item.title }}</view>
          <view class="schedule-location" v-if="item.location">
            <text class="location-icon">📍</text>
            <text>{{ item.location }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="attachments.length === 0 && dates.length === 0">
      <text class="empty-icon">📅</text>
      <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: '',
      currentDate: 0,
      dates: [],
      schedules: {},
      attachments: []
    };
  },
  computed: {
    currentSchedule() {
      return this.schedules[this.currentDate] || [];
    }
  },
  onLoad(options) {
    if (options.eventId) {
      this.eventId = options.eventId
      this.loadAttachments(options.eventId)
      this.loadScheduleDates(options.eventId)
    }
  },
  watch: {
    currentDate(newVal) {
      if (this.dates[newVal] && this.dates[newVal].date) {
        this.loadScheduleByDate(this.eventId, this.dates[newVal].date)
      }
    }
  },
  methods: {
    /**
     * 加载附件列表
     */
    async loadAttachments(eventId) {
      try {
        const res = await competitionAPI.getAttachments({
          competitionId: eventId,
          type: 'schedule'
        })

        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)
      }
    },

    /**
     * 下载文件
     */
    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]
    },

    /**
     * 加载日程日期列表
     */
    async loadScheduleDates(eventId) {
      try {
        const res = await infoAPI.getActivityScheduleList({ competitionId: eventId })

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

        if (list.length === 0) {
          return
        }

        // 提取唯一日期
        const dateSet = new Set()
        list.forEach(item => {
          const date = item.scheduleDate || item.schedule_date || item.date
          if (date) {
            dateSet.add(date)
          }
        })

        // 格式化日期选项卡并排序
        this.dates = Array.from(dateSet)
          .sort((a, b) => new Date(a) - new Date(b))
          .map(date => {
            const d = new Date(date)
            const month = d.getMonth() + 1
            const day = d.getDate()
            const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][d.getDay()]

            return {
              date: date,
              day: `${month}月${day}日`,
              text: weekDay
            }
          })

        // 按日期分组日程
        list.forEach(item => {
          const date = item.scheduleDate || item.schedule_date || item.date
          const dateIndex = this.dates.findIndex(d => d.date === date)

          if (dateIndex >= 0) {
            if (!this.schedules[dateIndex]) {
              this.schedules[dateIndex] = []
            }

            this.schedules[dateIndex].push({
              time: this.formatTime(item.scheduleTime || item.schedule_time || item.time),
              timeRaw: item.scheduleTime || item.schedule_time || item.time,
              title: item.eventName || item.event_name || item.title || item.activityName || item.scheduleName,
              location: item.venue || item.location || ''
            })
          }
        })

        // 对每个日期内的日程按时间排序
        Object.keys(this.schedules).forEach(dateIndex => {
          this.schedules[dateIndex].sort((a, b) => {
            const timeA = a.timeRaw || a.time
            const timeB = b.timeRaw || b.time
            return timeA.localeCompare(timeB)
          })
        })

        // 加载第一天的日程
        if (this.dates.length > 0 && this.dates[0].date) {
          this.loadScheduleByDate(eventId, this.dates[0].date)
        }
      } catch (err) {
        console.error('加载日程日期失败:', err)
      }
    },

    /**
     * 加载指定日期的日程
     */
    async loadScheduleByDate(eventId, date) {
      try {
        const res = await infoAPI.getScheduleList({ competitionId: eventId, date: date })

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

        const dateIndex = this.dates.findIndex(d => d.date === date)
        if (dateIndex >= 0) {
          this.schedules[dateIndex] = list
            .map(item => ({
              time: this.formatTime(item.scheduleTime || item.schedule_time || item.time),
              timeRaw: item.scheduleTime || item.schedule_time || item.time,
              title: item.eventName || item.event_name || item.title || item.activityName || item.scheduleName,
              location: item.venue || item.location || ''
            }))
            .sort((a, b) => {
              const timeA = a.timeRaw || a.time
              const timeB = b.timeRaw || b.time
              return timeA.localeCompare(timeB)
            })

          this.$forceUpdate()
        }
      } catch (err) {
        console.error('加载日程详情失败:', err)
      }
    },

    /**
     * 格式化时间（只取时分）
     */
    formatTime(timeStr) {
      if (!timeStr) return ''

      if (/^\d{2}:\d{2}$/.test(timeStr)) {
        return timeStr
      }

      if (/^\d{2}:\d{2}:\d{2}$/.test(timeStr)) {
        return timeStr.substring(0, 5)
      }

      const date = new Date(timeStr)
      if (!isNaN(date.getTime())) {
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        return `${hours}:${minutes}`
      }

      return timeStr
    }
  }
};
</script>

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

// 区块标题
.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 {
  padding: 20rpx 30rpx;
  margin-bottom: 10rpx;
}

.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;
}

.date-tabs {
  background-color: #fff;
  display: flex;
  padding: 20rpx 30rpx;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.date-tab {
  flex: 1;
  text-align: center;
  padding: 20rpx;
  border-radius: 12rpx;
  background-color: #f5f5f5;
}

.date-tab.active {
  background-color: #C93639;
  color: #fff;
}

.date-day {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 5rpx;
}

.date-text {
  font-size: 24rpx;
  opacity: 0.8;
}

.schedule-timeline {
  padding: 20rpx 30rpx;
}

.timeline-item {
  display: flex;
  gap: 20rpx;
  position: relative;
  margin-bottom: 40rpx;
}

.time-dot {
  width: 24rpx;
  height: 24rpx;
  background-color: #C93639;
  border-radius: 50%;
  flex-shrink: 0;
  margin-top: 10rpx;
  position: relative;
  z-index: 2;
}

.time-line {
  position: absolute;
  left: 11rpx;
  top: 34rpx;
  bottom: -40rpx;
  width: 2rpx;
  background-color: #E0E0E0;
  z-index: 1;
}

.schedule-card {
  flex: 1;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 25rpx;
}

.schedule-time {
  font-size: 26rpx;
  color: #C93639;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.schedule-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 10rpx;
}

.schedule-location {
  font-size: 24rpx;
  color: #666666;
  display: flex;
  align-items: center;
  gap: 5rpx;
}

.location-icon {
  font-size: 22rpx;
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
  gap: 20rpx;
}

.empty-icon {
  font-size: 120rpx;
  opacity: 0.3;
}

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