<template>
  <div class="dashboard-card">
    <div class="card-header">
      <h3>转化对比图</h3>
      <div class="time-selector">
        <select v-model="selectedTimeRange" @change="handleTimeRangeChange" class="time-select">
          <option value="month">本月 vs 上月</option>
          <option value="periods">本期 vs 上期</option> 
        </select>
      </div>
    </div>
    <div class="bar-chart">
      <div class="chart-legend">
        <div class="legend-item">
          <span class="legend-color current"></span>
          <span class="legend-text">{{ currentPeriodLabel }}</span>
        </div>
        <div class="legend-item">
          <span class="legend-color previous"></span>
          <span class="legend-text">{{ previousPeriodLabel }}</span>
        </div>
      </div>
      <div class="chart-container">
        <div v-for="(stage, index) in chartData" :key="stage.name" class="chart-stage">
          <div class="bars-container">
            <div class="bar-group">
              <div 
                class="bar current-bar" 
                :style="{ height: getBarHeight(stage.current, maxValue) + '%' }"
                :title="`${currentPeriodLabel}: ${stage.current}`"
              >
                <span class="bar-value">{{ stage.current }}</span>
              </div>
              <div 
                class="bar previous-bar" 
                :style="{ height: getBarHeight(stage.previous, maxValue) + '%' }"
                :title="`${previousPeriodLabel}: ${stage.previous}`"
              >
                <span class="bar-value">{{ stage.previous }}</span>
              </div>
            </div>
            <div class="change-indicator">
              <span 
                :class="['change-text', getChangeClass(stage.current, stage.previous)]"
              >
                {{ getChangeText(stage.current, stage.previous) }}
              </span>
            </div>
          </div>
          <div class="stage-name">{{ stage.name }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue';

const props = defineProps({
  funnelData: Array,
  comparisonData: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['time-range-change']);

const selectedTimeRange = ref('month');

// 计算属性：当前和上一期的标签
const currentPeriodLabel = computed(() => {
  return selectedTimeRange.value === 'periods' ? '本期' : '本月';
});

const previousPeriodLabel = computed(() => {
  return selectedTimeRange.value === 'periods' ? '上期' : '上月';
});

// 计算属性：图表数据
const chartData = computed(() => {
  if (!props.funnelData || !Array.isArray(props.funnelData)) {
    return [];
  }
  
  return props.funnelData.map(stage => {
    const comparisonStage = props.comparisonData[selectedTimeRange.value]?.find(
      item => item.name === stage.name
    );
    
    return {
      name: stage.name,
      current: stage.count || 0,
      previous: comparisonStage?.count || 0
    };
  });
});

// 计算属性：最大值（用于计算柱状图高度）
const maxValue = computed(() => {
  if (!chartData.value.length) return 100;
  
  const allValues = chartData.value.flatMap(stage => [stage.current, stage.previous]);
  return Math.max(...allValues, 1);
});

// 方法：计算柱状图高度百分比
const getBarHeight = (value, max) => {
  if (!value || !max) return 0;
  return Math.max((value / max) * 100, 2); // 最小高度2%
};

// 方法：获取变化文本
const getChangeText = (current, previous) => {
  if (!previous) return current > 0 ? '+100%' : '0%';
  
  const change = ((current - previous) / previous) * 100;
  const sign = change >= 0 ? '+' : '';
  return `${sign}${change.toFixed(1)}%`;
};

// 方法：获取变化样式类
const getChangeClass = (current, previous) => {
  if (!previous) return current > 0 ? 'positive' : 'neutral';
  
  const change = current - previous;
  if (change > 0) return 'positive';
  if (change < 0) return 'negative';
  return 'neutral';
};

// 方法：处理时间范围变化
const handleTimeRangeChange = () => {
  emit('time-range-change', selectedTimeRange.value);
};
</script>

<style scoped>
.dashboard-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  padding: 24px;
  display: flex;
  flex-direction: column;
  flex: 1;
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
}

.time-selector {
  display: flex;
  align-items: center;
}

.time-select {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background-color: #fff;
  font-size: 14px;
  color: #374151;
  cursor: pointer;
  transition: all 0.2s ease;
}

.time-select:hover {
  border-color: #3b82f6;
}

.time-select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.bar-chart {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chart-legend {
  display: flex;
  justify-content: center;
  margin: 20px 0;
  gap: 24px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 4px;
}

.legend-color.current {
  background-color: #3b82f6;
}

.legend-color.previous {
  background-color: #e5e7eb;
}

.legend-text {
  font-size: 14px;
  color: #6b7280;
  font-weight: 500;
}

.chart-container {
  flex: 1;
  display: flex;
  justify-content: center;
  /* align-items: flex-end; */
  padding: 20px 0;
  min-height: 250px;
}

.chart-stage {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  max-width: 80px;
}

.stage-name {
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 12px;
  text-align: center;
  font-weight: 500;
}

.bars-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 200px;
}

.bar-group {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  gap: 4px;
  height: 160px;
  width: 100%;
}

.bar {
  width: 24px;
  min-height: 4px;
  border-radius: 4px 4px 0 0;
  position: relative;
  transition: all 0.3s ease;
  cursor: pointer;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.bar:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.current-bar {
  background-color: #3b82f6;
}

.previous-bar {
  background-color: #e5e7eb;
}

.bar-value {
  position: absolute;
  top: -20px;
  font-size: 11px;
  font-weight: 600;
  color: #374151;
  white-space: nowrap;
}

.change-indicator {
  margin-top: 8px;
  text-align: center;
}

.change-text {
  font-size: 11px;
  font-weight: 600;
  padding: 2px 6px;
  border-radius: 4px;
}

.change-text.positive {
  color: #059669;
  background-color: #d1fae5;
}

.change-text.negative {
  color: #dc2626;
  background-color: #fee2e2;
}

.change-text.neutral {
  color: #6b7280;
  background-color: #f3f4f6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-card {
    padding: 16px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .chart-container {
    flex-wrap: wrap;
    gap: 16px;
  }
  
  .chart-stage {
    min-width: 80px;
  }
  
  .bar {
    width: 20px;
  }
}
</style>