<template>
  <view class="ranking-board">
    <!-- 顶部Header -->
    <view class="ranking-header">
      <view class="header-content">
        <view class="header-info">
          <view class="title-row">
            <text class="header-title">排行榜</text>
            <view class="trophy-icon">🏆</view>
          </view>
          <text v-if="currentTab === 'today'" class="date-label">{{ dayLabel }}</text>
          <text v-else-if="currentTab === 'week'" class="date-label">{{ weekLabel }}</text>
          <text v-else class="date-label">{{ monthLabel }}</text>
        </view>
        <view v-if="currentTab === 'today'" class="header-actions">
          <view class="quick-btn" :class="{ active: isToday }" @click="onTodayClick">今日</view>
          <view class="quick-btn" :class="{ active: isYesterday }" @click="onYesterdayClick">昨日</view>
          <picker mode="date" :value="selectedDate" :end="todayStr" @change="handleDateChange">
            <view class="history-btn">往期</view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="ranking-content" scroll-y>
      <!-- Tabs -->
      <view class="ranking-tabs">
        <view 
          class="tab-item" 
          :class="{ active: currentTab === 'today' }"
          @click="switchTab('today')"
        >
          日排行
        </view>
        <view 
          class="tab-item" 
          :class="{ active: currentTab === 'week' }"
          @click="switchTab('week')"
        >
          周排行
        </view>
        <view 
          class="tab-item" 
          :class="{ active: currentTab === 'month' }"
          @click="switchTab('month')"
        >
          月排行
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <view class="loading-text">加载中...</view>
      </view>

      <!-- 排行榜内容 -->
      <view v-else class="ranking-list-container">
        <!-- 当前用户排名（高亮显示） -->
        <view v-if="currentUserRank" class="my-ranking-card">

          <view class="my-ranking-stats">

            <view class="stat-item">
              <text class="stat-value">我</text>
            </view>
            <view class="stat-item">
              <text class="stat-value">第{{ currentUserRank.rank }}名</text>
            </view>
            <view class="stat-item">
              <text class="stat-value">{{ currentUserRank.addNum }}</text>
            </view>
            <view class="stat-item">
              <text class="stat-value">{{ currentUserRank.followNum }}</text>
            </view>
            <view class="stat-item">
              <text class="stat-value">{{ currentUserRank.intentionNum }}</text>
            </view>
            <view class="stat-item">
              <text class="stat-value">{{ currentUserRank.addWxNum }}</text>
            </view>
          </view>
        </view>

        <!-- 表头 -->
        <view class="ranking-table-header">
          <view class="header-col rank-col">排名</view>
          <view class="header-col name-col">名称</view>
          <view class="header-col stat-col">新增</view>
          <view class="header-col stat-col">跟进</view>
          <view class="header-col stat-col">加微信</view>
          <view class="header-col stat-col">高意向</view>
          <view class="header-col stat-col">成交</view>
        </view>

        <!-- 排行榜列表 -->
        <view class="ranking-list">
          <view 
            v-for="(item, index) in currentRankingList" 
            :key="item.userId"
            class="ranking-item"
            :class="{ 'is-current-user': String(item.userId) === String(currentUserId) }"
          >
            <!-- 排名 -->
            <view class="rank-col">
              <view v-if="index === 0" class="medal gold">🥇</view>
              <view v-else-if="index === 1" class="medal silver">🥈</view>
              <view v-else-if="index === 2" class="medal bronze">🥉</view>
              <text v-else class="rank-number">{{ index + 1 }}</text>
            </view>
            
            <!-- 名称 -->
            <view class="name-col">

              <text class="user-name">{{ item.userName }}</text>
            </view>
            
            <!-- 统计数据 -->
            <view class="stat-col">
              <text class="stat-text">{{ item.addNum }}</text>
            </view>
            <view class="stat-col">
              <text class="stat-text">{{ item.followNum }}</text>
            </view>
            <view class="stat-col">
              <text class="stat-text">{{ item.addWxNum }}</text>
            </view>
            <view class="stat-col">
              <text class="stat-text">{{ item.highIntentionNum }}</text>
            </view>

            <view class="stat-col">
              <text class="stat-text">{{ item.dealNum }}</text>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="!loading && currentRankingList.length === 0" class="empty-state">
          <text class="empty-text">暂无数据</text>
        </view>
      </view>
    </scroll-view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getCustomerStatistics } from '@/api/dashboard';
import { useUserStore } from '@/store/user';

const currentTab = ref('today');
const loading = ref(false);

const userStore = useUserStore();
const currentUserId = computed(() => {
  const userId = userStore.userInfo?.user?.userId;
  return userId != null ? String(userId) : '';
});

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = `${date.getMonth() + 1}`.padStart(2, '0');
  const day = `${date.getDate()}`.padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const addDays = (date, days) => {
  const next = new Date(date);
  next.setDate(next.getDate() + days);
  return next;
};

const getWeekRange = (date) => {
  const temp = new Date(date);
  const day = temp.getDay();
  const diffToMonday = day === 0 ? -6 : 1 - day;
  const startDate = addDays(temp, diffToMonday);
  const endDate = addDays(startDate, 6);
  return {
    start: formatDate(startDate),
    end: formatDate(endDate)
  };
};

const getMonthRange = (date) => {
  const startDate = new Date(date.getFullYear(), date.getMonth(), 1);
  const endDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);
  return {
    start: formatDate(startDate),
    end: formatDate(endDate)
  };
};

const todayStr = formatDate(new Date());
const yesterdayStr = formatDate(addDays(new Date(), -1));
const selectedDate = ref(todayStr);

const weekRange = ref(getWeekRange(new Date()));
const monthRange = ref(getMonthRange(new Date()));

const dayRanking = ref([]);
const weekRanking = ref([]);
const monthRanking = ref([]);

const isToday = computed(() => selectedDate.value === todayStr);
const isYesterday = computed(() => selectedDate.value === yesterdayStr);

const dayLabel = computed(() => {
  if (isToday.value) return '统计日期：今日';
  if (isYesterday.value) return '统计日期：昨日';
  return `统计日期：${selectedDate.value}`;
});
const weekLabel = computed(() => `统计周期：${weekRange.value.start} ~ ${weekRange.value.end}`);
const monthLabel = computed(() => `统计周期：${monthRange.value.start} ~ ${monthRange.value.end}`);

const currentRankingList = computed(() => {
  let list;
  if (currentTab.value === 'today') list= dayRanking.value;
  else if (currentTab.value === 'week') list = weekRanking.value;
  else list = monthRanking.value;
  return [...list].sort((a, b) => b.addNum-a.addNum);
});

const currentUserRank = computed(() => {
  const list = currentRankingList.value;
  const userId = currentUserId.value;
  if (!userId || !Array.isArray(list) || list.length === 0) return null;
  const index = list.findIndex(item => String(item.userId) === String(userId));
  if (index === -1) return null;
  return {
    ...list[index],
    rank: index + 1
  };
});

const normalizeList = (res) => {
  if (!res) return [];
  if (Array.isArray(res)) return res;
  if (Array.isArray(res.data)) return res.data;
  if (Array.isArray(res.rows)) return res.rows;
  return [];
};

const buildRangeParams = (start, end) => ([start, end]);

const fetchDayRanking = async (date) => {
  const res = await getCustomerStatistics(buildRangeParams(date, date));
  dayRanking.value = normalizeList(res);
};

const fetchWeekRanking = async () => {
  const { start, end } = weekRange.value;
  const res = await getCustomerStatistics(buildRangeParams(start, end));
  weekRanking.value = normalizeList(res);
};

const fetchMonthRanking = async () => {
  const { start, end } = monthRange.value;
  const res = await getCustomerStatistics(buildRangeParams(start, end));
  monthRanking.value = normalizeList(res);
};

const init = async () => {
  loading.value = true;
  try {
    await Promise.all([
      fetchDayRanking(selectedDate.value),
      fetchWeekRanking(),
      fetchMonthRanking()
    ]);
  } catch (err) {
    console.error('加载排行榜数据失败:', err);
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

const refreshDayRanking = async () => {
  loading.value = true;
  try {
    await fetchDayRanking(selectedDate.value);
  } catch (err) {
    console.error('加载日排行失败:', err);
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

const switchTab = (tab) => {
  currentTab.value = tab;
};

const setDay = (date) => {
  if (!date || selectedDate.value === date) return;
  selectedDate.value = date;
  refreshDayRanking();
};

const handleDateChange = (event) => {
  const value = event?.detail?.value;
  if (value) {
    setDay(value);
  }
};

const onTodayClick = () => setDay(todayStr);
const onYesterdayClick = () => setDay(yesterdayStr);

onMounted(() => {
  init();
});
</script>

<style lang="scss" scoped>
.ranking-board {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f6f7fb;
  overflow: hidden;
  position: relative;
}

.ranking-header {
  background: linear-gradient(135deg, #ffd700 0%, #ffb347 100%);
  padding: 40rpx 32rpx 60rpx;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 300rpx;
    height: 300rpx;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
    transform: translate(30%, -30%);
  }
  
  &::after {
    content: '';
    position: absolute;
    bottom: -50rpx;
    right: -50rpx;
    width: 200rpx;
    height: 200rpx;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
  }
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  z-index: 1;
}

.header-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #ffffff;
}
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 24rpx;
}
.header-info {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}
.title-row {
  display: flex;
  align-items: center;
  gap: 12rpx;
}
.date-label {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
}
.header-actions {
  display: flex;
  align-items: center;
  gap: 16rpx;
}
.quick-btn,
.history-btn {
  padding: 12rpx 28rpx;
  border-radius: 999rpx;
  font-size: 24rpx;
  color: #ffffff;
  border: 1rpx solid rgba(255, 255, 255, 0.6);
  background: rgba(255, 255, 255, 0.2);
}
.quick-btn.active {
  background: #ffffff;
  color: #ff6b35;
  border-color: #ffffff;
}
.history-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.trophy-icon {
  font-size: 80rpx;
  line-height: 1;
}

.ranking-content {
  flex: 1;
  background: #ffffff;
  border-radius: 32rpx 32rpx 0 0;
  margin-top: -32rpx;
  position: relative;
  z-index: 2;
  padding-top: 24rpx;
  height: 0; /* 配合 flex: 1 使用 */
}

.ranking-tabs {
  display: flex;
  padding: 0 32rpx;
  border-bottom: 2rpx solid #f0f0f0;
  margin-bottom: 24rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 24rpx 0;
  font-size: 28rpx;
  color: #666666;
  position: relative;
  
  &.active {
    color: #ff6b35;
    font-weight: 600;
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 60rpx;
      height: 4rpx;
      background: #ff6b35;
      border-radius: 2rpx;
    }
  }
}

.loading-container {
  padding: 100rpx 0;
  text-align: center;
}

.loading-text {
  font-size: 28rpx;
  color: #999999;
}

.ranking-list-container {
  padding: 0 32rpx 40rpx;
}

.my-ranking-card {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border-radius: 16rpx;
  padding: 24rpx 0;
  margin-bottom: 24rpx;
}

.my-ranking-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.my-label {
  flex: 1;
  font-size: 28rpx;
  font-weight: 600;
  color: #1976d2;
  margin-right: 16rpx;
}

.my-avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
}

.avatar-text {
  font-size: 24rpx;
  color: #1976d2;
  font-weight: 600;
}

.my-rank {
  flex: 1;
  font-size: 28rpx;
  font-weight: 600;
  color: #1976d2;
  margin-left: auto;
}

.my-ranking-stats {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #1976d2;
}

.ranking-table-header {
  display: flex;
  padding: 16rpx 0;
  background: #f8f9fa;
  border-radius: 8rpx;
  margin-bottom: 16rpx;
}

.header-col {
  flex: 1;
  font-size: 24rpx;
  color: #666666;
  text-align: center;
  
  &.rank-col {
flex:1;
    flex-shrink: 0;
  }
  
  &.name-col {

    text-align: left;

    justify-content: center;
  }
  
  &.stat-col {

    flex-shrink: 0;
  }
}

.ranking-list {
  display: flex;
  flex-direction: column;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  flex:1;

  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
  
  &.is-current-user {
    background: #f0f7ff;
    border-radius: 8rpx;

    margin: 8rpx 0;
  }
}

.rank-col {
  flex:1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.medal {
  font-size: 40rpx;
  line-height: 1;
}

.rank-number {
  font-size: 28rpx;
  color: #333333;
  font-weight: 600;
}

.name-col {
  flex:1;
  display: flex;
  align-items: center;

}

.user-avatar {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  background: #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
}

.user-avatar .avatar-text {
  font-size: 22rpx;
  color: #666666;
  font-weight: 500;
}

.user-name {
  font-size: 28rpx;
  color: #333333;
}

.stat-col {
  flex:1;

  flex-shrink: 0;
  text-align: center;
}

.stat-text {
  font-size: 26rpx;
  color: #333333;
}

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

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