<template>
  <div class="event-detail-page" :style="{ paddingBottom: `${safeHeight}px` }">
    <!-- 活动封面 -->
    <div class="event-cover">
      <image class="cover-image" :src="eventDetail.coverImage || defaultCover" mode="aspectFill" />
      <div class="event-status" :class="[
        eventDetail.status === 'active' ? 'status-active' :
          (eventDetail.status === 'ended' ? 'status-ended' : 'status-draft')
      ]">
        {{ getStatusText(eventDetail.status) }}
      </div>
    </div>

    <!-- 活动基本信息 -->
    <div class="event-header">
      <div class="event-title">{{ eventDetail.eventName }}</div>

      <div class="event-meta">
        <div class="meta-item">
          <span class="meta-icon">📅</span>
          <span class="meta-text">{{ formatFullDateTime(eventDetail.eventTime) }}</span>
        </div>
        <div class="meta-item">
          <span class="meta-icon">📍</span>
          <span class="meta-text">{{ eventDetail.eventLocation }}</span>
        </div>
        <div class="meta-item">
          <span class="meta-icon">👥</span>
          <span class="meta-text">
            {{ eventDetail.currentParticipants || 0 }} / {{ eventDetail.maxParticipants || '不限' }}人
          </span>
        </div>
      </div>
    </div>

    <!-- 活动内容 -->
    <div class="content-section">
      <div class="section-title">活动介绍</div>
      <text class="content-text">{{ eventDetail.eventContent }}</text>
    </div>

    <!-- 活动要求 -->
    <div class="requirements-section" v-if="eventDetail.requirements">
      <div class="section-title">参与要求</div>
      <text class="content-text">{{ eventDetail.requirements }}</text>
    </div>

    <!-- 注意事项 -->
    <div class="notice-section" v-if="eventDetail.notice">
      <div class="section-title">注意事项</div>
      <text class="content-text">{{ eventDetail.notice }}</text>
    </div>

    <!-- 报名按钮 -->
    <div class="action-section">
      <div class="action-btn" :class="[
        eventDetail.status === 'ended' ? 'action-disabled' :
          (isEventFull() ? 'action-full' :
            (hasRegistered ? 'action-registered' : 'action-normal'))
      ]" @click="handleAction">
        <span class="btn-text">{{ getActionText() }}</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      safeHeight: "",
      eventId: "",
      eventDetail: {},
      hasRegistered: false, // 是否已报名当前活动
      defaultCover: 'https://picsum.photos/seed/event-detail/400/300.jpg'
    };
  },
  onLoad(query) {
    let systemInfo = uni.getSystemInfoSync();
    let height = systemInfo.safeAreaInsets.bottom;
    this.safeHeight = Number(height);

    if (query.id) {
      this.eventId = query.id;
    }

    if (query.hasRegistered) {
      this.hasRegistered = query.hasRegistered === 'true';
    }

    this.loadEventDetail();
  },
  onShareAppMessage() {
    return {
      title: `${this.eventDetail.eventName}`,
      path: `/pages/eventRegistration/detail?id=${this.eventId}`,
    };
  },
  onShareTimeline() {
    return {
      title: `${this.eventDetail.eventName}`,
      path: `/pages/eventRegistration/detail?id=${this.eventId}`,
    };
  },
  methods: {
    // 加载活动详情
    async loadEventDetail() {
      try {
        uni.showLoading({
          title: '加载中...',
          mask: true
        });

        // 这里调用实际接口获取活动详情
        // const res = await this.$api.getEventDetail({
        //   eventId: this.eventId
        // });

        // 模拟数据
        const mockData = {
          id: this.eventId,
          eventName: "春季音乐节",
          eventContent: "春暖花开，音乐与美好相遇。本次音乐节邀请了多位知名音乐人，为大家带来一场视听盛宴。活动包含民谣、流行、摇滚等多种音乐风格，适合各个年龄段的观众参与。",
          eventLocation: "昆明市中心广场露天舞台",
          eventTime: "2024-03-15 19:00:00",
          maxParticipants: 500,
          currentParticipants: 280,
          status: "active",
          coverImage: "https://picsum.photos/seed/music-festival-detail/400/300.jpg",
          requirements: "1. 活动免费参与，无需门票\n2. 请提前15分钟到场\n3. 建议携带防寒衣物\n4. 禁止携带危险物品入场\n5. 活动期间请保持现场秩序",
          notice: "1. 如遇恶劣天气，活动可能延期或取消\n2. 请保管好个人财物\n3. 活动现场禁止吸烟\n4. 请遵守现场工作人员指引\n5. 建议绿色出行，避免交通拥堵"
        };

        this.eventDetail = mockData;
        this.checkRegistrationStatus();

        uni.hideLoading();

      } catch (error) {
        console.error('加载活动详情失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      }
    },

    // 检查报名状态
    async checkRegistrationStatus() {
      try {
        // 这里应该调用接口检查用户是否已报名该活动
        // const res = await this.$api.checkRegistrationStatus({
        //   eventId: this.eventId,
        //   userId: getUserId()
        // });
        // this.hasRegistered = res.hasRegistered;

        // 模拟数据 - 可以从URL参数传入或调用接口获取
        // this.hasRegistered = false;

      } catch (error) {
        console.error('检查报名状态失败:', error);
        this.hasRegistered = false;
      }
    },

    // 处理按钮点击
    handleAction() {
      if (this.eventDetail.status === 'ended') {
        uni.showToast({
          title: '活动已结束',
          icon: 'none'
        });
        return;
      }

      if (this.isEventFull()) {
        uni.showToast({
          title: '报名人数已满',
          icon: 'none'
        });
        return;
      }

      if (this.hasRegistered) {
        uni.showToast({
          title: '您已报名过该活动',
          icon: 'none'
        });
        return;
      }

      // 跳转到报名页面
      uni.navigateTo({
        url: `/pages/eventRegistration/registration?eventId=${this.eventId}`
      });
    },

    // 跳转到报名信息页面
    goToRegistrationInfo() {
      uni.navigateTo({
        url: `/pages/eventRegistration/registration?eventId=${this.eventId}&mode=view&hasRegistered=true`
      });
    },

    // 格式化完整日期时间
    formatFullDateTime(dateTime) {
      if (!dateTime) return '';
      try {
        const date = new Date(dateTime);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()];
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `${year}年${month}月${day}日 ${weekDay} ${hours}:${minutes}`;
      } catch (error) {
        return dateTime;
      }
    },


    // 获取活动状态文本
    getStatusText(status) {
      const statusMap = {
        'active': '报名中',
        'ended': '已结束',
        'draft': '筹备中'
      };
      return statusMap[status] || '报名中';
    },

    // 判断活动是否已满员
    isEventFull() {
      if (!this.eventDetail.maxParticipants) return false;
      return this.eventDetail.currentParticipants >= this.eventDetail.maxParticipants;
    },


    // 获取按钮文本
    getActionText() {
      if (this.eventDetail.status === 'ended') return '活动已结束';
      if (this.isEventFull()) return '报名已满员';
      if (this.hasRegistered) return '已报名';
      return '立即报名';
    }
  }
};
</script>

<style scoped lang="less">
.event-detail-page {
  width: 100vw;
  min-height: 100vh;
  background: #f8fafc;
  overflow-y: scroll;

  .event-cover {
    position: relative;
    width: 100%;
    height: 300rpx;
    overflow: hidden;

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

    .event-status {
      position: absolute;
      top: 40rpx;
      right: 40rpx;
      padding: 16rpx 32rpx;
      border-radius: 24rpx;
      font-size: 24rpx;
      font-weight: 600;
      backdrop-filter: blur(10rpx);

      &.status-active {
        background: rgba(34, 197, 94, 0.9);
        color: white;
      }

      &.status-ended {
        background: rgba(107, 114, 128, 0.9);
        color: white;
      }

      &.status-draft {
        background: rgba(251, 146, 60, 0.9);
        color: white;
      }
    }
  }

  .event-header {
    background: white;
    padding: 24rpx;
    margin: -40rpx 32rpx 32rpx;
    border-radius: 24rpx 24rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
    position: relative;
    z-index: 2;

    .event-title {
      font-size: 30rpx;
      font-weight: 600;
      color: #1f2937;
      line-height: 1.4;
      margin-bottom: 12rpx;
    }

    .event-meta {
      .meta-item {
        display: flex;
        align-items: center;
        margin-bottom: 12rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .meta-icon {
          font-size: 24rpx;
          margin-right: 16rpx;
          width: 40rpx;
          text-align: center;
        }

        .meta-text {
          font-size: 24rpx;
          color: #374151;
          line-height: 1.4;
        }
      }
    }
  }

  .content-section,
  .requirements-section,
  .notice-section {
    background: white;
    margin: 0 32rpx 32rpx;
    padding: 32rpx;
    border-radius: 24rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);

    .section-title {
      font-size: 28rpx;
      font-weight: 600;
      color: #1f2937;
      margin-bottom: 12rpx;
      position: relative;
      padding-left: 16rpx;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 8rpx;
        bottom: 8rpx;
        width: 6rpx;
        background: #22c55e;
        border-radius: 3rpx;
      }
    }

    .content-text {
      font-size: 24rpx;
      color: #374151;
      line-height: 1.6;
      white-space: pre-wrap;
    }
  }

  .notice-section {
    margin: 0 32rpx calc(24rpx + env(safe-area-inset-bottom) + 24rpx + 28rpx + 40rpx);
  }

  .action-section {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background: white;
    border-top: 1rpx solid #f0f0f0;
    padding: 24rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
    z-index: 100;

    .action-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      font-weight: 600;
      transition: all 0.3s ease;
      border: 2rpx solid #e5e7eb;

      &.action-normal {
        background: linear-gradient(135deg, #22c55e, #16a34a);
        color: white;
        border-color: #22c55e;

        &:active {
          opacity: 0.9;
        }

        .btn-text {
          margin-right: 12rpx;
        }

        .btn-icon {
          font-size: 28rpx;
        }
      }

      &.action-registered {
        background: #f3f4f6;
        color: #9ca3af;
        border-color: #e5e7eb;

        &:active {
          background: #e5e7eb;
        }

        .btn-text {
          margin-right: 12rpx;
        }

        .registered-icon {
          font-size: 24rpx;
          color: #6b7280;
        }
      }

      &.action-full {
        background: #f3f4f6;
        color: #9ca3af;
        border-color: #e5e7eb;

        &:active {
          background: #e5e7eb;
        }
      }

      &.action-disabled {
        background: #f9fafb;
        color: #d1d5db;
        border-color: #f3f4f6;
      }
    }
  }
}

.event-detail-page::-webkit-scrollbar {
  display: none;
}
</style>