<template>
  <div class="home-page">
    <van-search
      v-model="keyword"
      :show-action="showSearchAction"
      action-text="取消"
      placeholder="搜索精彩活动"
      shape="round"
      background="#fff"
      @search="onSearch"
      @cancel="onCancel"
      @focus="onSearchFocus"
    />

    <van-tabs v-model:active="activeTab" sticky color="#1989fa">
      <van-tab title="活动列表">
        <!-- 筛选控件 -->
        <div class="filter-section">
          <van-dropdown-menu>
            <van-dropdown-item v-model="filterStatus" :options="statusOptions" @change="onFilterChange" />
            <van-dropdown-item v-model="filterTimeRange" :options="timeRangeOptions" @change="onFilterChange" />
          </van-dropdown-menu>
        </div>

        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多活动了"
            :immediate-check="false"
            @load="onLoad"
          >
            <div class="activity-list">
              <div
                v-for="item in list"
                :key="item.id"
                class="activity-card"
                @click="goToDetail(item.id)"
              >
                <div class="card-cover">
                  <van-image
                    fit="cover"
                    :src="item.coverImage || getRandomCover(item.id)"
                    class="cover-image"
                  >
                    <template #error>
                      <div class="image-placeholder">
                        <van-icon name="photo-o" size="30" />
                      </div>
                    </template>
                  </van-image>
                  <div class="status-tag">
                    <van-tag :type="getStatusType(item.status)" round size="medium">
                      {{ formatStatus(item.status) }}
                    </van-tag>
                  </div>
                </div>

                <div class="card-content">
                  <h3 class="activity-title van-ellipsis">{{ item.title }}</h3>
                  
                  <div class="info-row">
                    <van-icon name="clock-o" class="icon" />
                    <span class="text">{{ formatTimeRange(item.startTime, item.endTime) }}</span>
                  </div>
                  
                  <div class="info-row">
                    <van-icon name="location-o" class="icon" />
                    <span class="text van-ellipsis">{{ item.location }}</span>
                  </div>

                  <div class="card-footer">
                    <van-tag plain type="primary" size="medium">{{ item.category || '未分类' }}</van-tag>
                    <div class="participants">
                      <van-icon name="friends-o" />
                      <span>{{ item.currentParticipants }}/{{ item.maxParticipants }} 已报名</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </van-list>
        </van-pull-refresh>
      </van-tab>
      <van-tab title="活动日历">
        <div class="calendar-container">
          <van-calendar
            title="活动日历"
            :poppable="false"
            :show-confirm="false"
            :style="{ height: '500px' }"
            color="#1989fa"
            :formatter="calendarFormatter"
            :min-date="minDate"
            :max-date="maxDate"
            @select="onSelectDate"
            @month-show="onMonthChange"
          />
          
          <!-- 选中日期的活动列表 -->
          <div v-if="selectedDateActivities.length > 0" class="selected-date-activities">
            <div class="section-title">
              <van-icon name="calendar-o" />
              <span>{{ formatSelectedDate() }} 的活动</span>
            </div>
            <div class="date-activity-list">
              <div
                v-for="item in selectedDateActivities"
                :key="item.id"
                class="date-activity-card"
                @click="goToDetail(item.id)"
              >
                <div class="date-activity-content">
                  <h4 class="date-activity-title">{{ item.title }}</h4>
                  <div class="date-activity-time">
                    <van-icon name="clock-o" size="14" />
                    <span>{{ formatActivityTime(item.startTime, item.endTime) }}</span>
                  </div>
                  <div class="date-activity-location">
                    <van-icon name="location-o" size="14" />
                    <span>{{ item.location }}</span>
                  </div>
                  <div class="date-activity-footer">
                    <van-tag :type="getStatusType(item.status)">
                      {{ formatStatus(item.status) }}
                    </van-tag>
                    <span class="participants">
                      {{ item.currentParticipants }}/{{ item.maxParticipants }}人
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div v-else-if="selectedDate" class="no-activities">
            <van-empty description="该日期暂无活动" />
          </div>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getActivities, getCalendarActivities } from '@/services/activity';
import type { Activity } from '@/types/activity';
import dayjs from 'dayjs';

const router = useRouter();

const keyword = ref('');
const activeTab = ref(0);
const list = ref<Activity[]>([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const currentPage = ref(1);
const showSearchAction = ref(false);

// 筛选相关状态
const filterStatus = ref(0);
const filterTimeRange = ref(0);

// 状态选项
const statusOptions = [
  { text: '全部状态', value: 0 },
  { text: '报名中', value: 1 },
  { text: '进行中', value: 2 },
  { text: '已结束', value: 3 },
];

// 时间范围选项
const timeRangeOptions = [
  { text: '全部时间', value: 0 },
  { text: '本周', value: 1 },
  { text: '本月', value: 2 },
  { text: '下月', value: 3 },
];

// 日历相关状态
const calendarActivities = ref<Activity[]>([]);
const selectedDate = ref<Date | null>(null);
const minDate = ref(new Date(new Date().getFullYear(), 0, 1));
const maxDate = ref(new Date(new Date().getFullYear() + 2, 11, 31));

// 选中日期的活动列表
const selectedDateActivities = computed(() => {
  if (!selectedDate.value) return [];
  const selectedDateStr = dayjs(selectedDate.value).format('YYYY-MM-DD');
  return calendarActivities.value.filter(activity => {
    const activityDate = dayjs(activity.startTime).format('YYYY-MM-DD');
    return activityDate === selectedDateStr;
  });
});

const onLoad = async () => {
  if (refreshing.value) {
    list.value = [];
    refreshing.value = false;
  }

  try {
    loading.value = true;

    // 构建请求参数
    const params: any = {
      current: currentPage.value,
      size: 10,
      keyword: keyword.value,
    };

    // 添加状态筛选
    if (filterStatus.value !== 0) {
      params.status = filterStatus.value;
    }

    // 添加时间范围筛选
    const timeRange = getTimeRange(filterTimeRange.value);
    if (timeRange.startDate) {
      params.startDate = timeRange.startDate;
    }
    if (timeRange.endDate) {
      params.endDate = timeRange.endDate;
    }

    const res = await getActivities(params);

    const { records, total } = res;
    if (currentPage.value === 1) {
      list.value = records;
    } else {
      list.value.push(...records);
    }

    loading.value = false;
    currentPage.value++;

    if (list.value.length >= total) {
      finished.value = true;
    }
  } catch (error) {
    loading.value = false;
    finished.value = true;
    console.error(error);
  }
};

const onRefresh = () => {
  finished.value = false;
  currentPage.value = 1;
  onLoad();
};

const onSearch = () => {
  list.value = [];
  currentPage.value = 1;
  finished.value = false;
  loading.value = true;
  showSearchAction.value = true;
  onLoad();
};

const onSearchFocus = () => {
  showSearchAction.value = true;
};

const onCancel = () => {
  keyword.value = '';
  showSearchAction.value = false;
  onSearch();
};

const goToDetail = (id: number) => {
  router.push(`/activity/${id}`);
};

const formatTimeRange = (start: string, end: string) => {
  const s = dayjs(start);
  const e = dayjs(end);
  if (s.isSame(e, 'day')) {
    return `${s.format('MM-DD HH:mm')} - ${e.format('HH:mm')}`;
  }
  return `${s.format('MM-DD HH:mm')} - ${e.format('MM-DD HH:mm')}`;
};

const formatStatus = (status: number) => {
  const map: Record<number, string> = {
    0: '草稿',
    1: '报名中',
    2: '进行中',
    3: '已结束',
    4: '已取消',
  };
  return map[status] || '未知';
};

const getStatusType = (status: number) => {
  const map: Record<number, 'primary' | 'success' | 'warning' | 'danger' | 'default'> = {
    0: 'default',
    1: 'success',
    2: 'primary',
    3: 'default',
    4: 'danger',
  };
  return map[status] || 'default';
};

const getRandomCover = (id: number) => {
  return `https://picsum.photos/seed/${id}/600/400`;
};

// 筛选条件变化处理
const onFilterChange = () => {
  list.value = [];
  currentPage.value = 1;
  finished.value = false;
  loading.value = true;
  onLoad();
};

// 获取时间范围
const getTimeRange = (range: number) => {
  const now = dayjs();
  let startDate = '';
  let endDate = '';

  switch (range) {
    case 1: // 本周
      startDate = now.startOf('week').format('YYYY-MM-DD HH:mm:ss');
      endDate = now.endOf('week').format('YYYY-MM-DD HH:mm:ss');
      break;
    case 2: // 本月
      startDate = now.startOf('month').format('YYYY-MM-DD HH:mm:ss');
      endDate = now.endOf('month').format('YYYY-MM-DD HH:mm:ss');
      break;
    case 3: // 下月
      startDate = now.add(1, 'month').startOf('month').format('YYYY-MM-DD HH:mm:ss');
      endDate = now.add(1, 'month').endOf('month').format('YYYY-MM-DD HH:mm:ss');
      break;
    default:
      break;
  }

  return { startDate, endDate };
};

// 加载日历数据
const loadCalendarData = async (year: number, month: number) => {
  try {
    const res = await getCalendarActivities(year, month);
    calendarActivities.value = res;
  } catch (error) {
    console.error('加载日历数据失败:', error);
  }
};

// 日历formatter - 标记有活动的日期
const calendarFormatter = (day: any) => {
  const dateStr = dayjs(day.date).format('YYYY-MM-DD');
  const hasActivity = calendarActivities.value.some(activity => {
    const activityDate = dayjs(activity.startTime).format('YYYY-MM-DD');
    return activityDate === dateStr;
  });

  if (hasActivity) {
    day.bottomInfo = '有活动';
    day.className = 'has-activity';
  }

  return day;
};

// 月份切换事件
const onMonthChange = (date: Date) => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  loadCalendarData(year, month);
};

// 日期选择事件
const onSelectDate = (date: Date) => {
  selectedDate.value = date;
};

// 格式化选中的日期
const formatSelectedDate = () => {
  if (!selectedDate.value) return '';
  return dayjs(selectedDate.value).format('YYYY年MM月DD日');
};

// 格式化活动时间
const formatActivityTime = (start: string, end: string) => {
  const s = dayjs(start);
  const e = dayjs(end);
  if (s.isSame(e, 'day')) {
    return `${s.format('HH:mm')} - ${e.format('HH:mm')}`;
  }
  return `${s.format('MM-DD HH:mm')} - ${e.format('MM-DD HH:mm')}`;
};

onMounted(() => {
  onLoad();
  // 加载当前月份的日历数据
  const now = new Date();
  loadCalendarData(now.getFullYear(), now.getMonth() + 1);
});
</script>

<style scoped lang="scss">
.home-page {
  padding-bottom: 60px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.filter-section {
  background: #fff;
  border-bottom: 1px solid #f5f6f7;
}

.calendar-container {
  background: #fff;
  
  :deep(.has-activity) {
    .van-calendar__day {
      color: #1989fa;
      font-weight: 600;
    }
    
    .van-calendar__bottom-info {
      color: #1989fa;
      font-size: 11px;
    }
  }
}

.section-title {
  display: flex;
  align-items: center;
  padding: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  border-bottom: 1px solid #f5f6f7;
  
  .van-icon {
    margin-right: 8px;
    color: #1989fa;
    font-size: 18px;
  }
}

.selected-date-activities {
  margin-top: 12px;
  background: #fff;
}

.date-activity-list {
  padding: 12px;
}

.date-activity-card {
  background: #f7f8fa;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  transition: all 0.2s;
  
  &:active {
    background: #e8eaed;
  }
  
  &:last-child {
    margin-bottom: 0;
  }
}

.date-activity-content {
  .date-activity-title {
    margin: 0 0 8px;
    font-size: 15px;
    font-weight: 600;
    color: #323233;
    line-height: 1.4;
  }
  
  .date-activity-time,
  .date-activity-location {
    display: flex;
    align-items: center;
    margin-bottom: 6px;
    font-size: 13px;
    color: #646566;
    
    .van-icon {
      margin-right: 6px;
      color: #969799;
    }
  }
  
  .date-activity-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 10px;
    
    .participants {
      font-size: 12px;
      color: #969799;
    }
  }
}

.no-activities {
  padding: 40px 20px;
  background: #fff;
}

.activity-list {
  padding: 12px;
}

.activity-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  transition: all 0.2s;
  
  &:active {
    transform: scale(0.99);
  }

  .card-cover {
    position: relative;
    height: 160px;
    width: 100%;
    
    .cover-image {
      width: 100%;
      height: 100%;
    }

    .status-tag {
      position: absolute;
      top: 12px;
      right: 12px;
      z-index: 1;
    }
    
    .image-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f5f5f5;
      color: #dcdee0;
    }
  }

  .card-content {
    padding: 12px 16px;

    .activity-title {
      margin: 0 0 10px;
      font-size: 17px;
      font-weight: 600;
      color: #323233;
      line-height: 1.4;
    }

    .info-row {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      color: #646566;
      font-size: 14px;

      .icon {
        margin-right: 8px;
        font-size: 16px;
        color: #969799;
      }
      
      .text {
        flex: 1;
      }
    }

    .card-footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px solid #f5f6f7;

      .participants {
        display: flex;
        align-items: center;
        font-size: 13px;
        color: #969799;

        .van-icon {
          margin-right: 4px;
          font-size: 15px;
        }
      }
    }
  }
}
</style>
