<template>
  <div class="performance-comparison">
    <div class="comparison-header">
      <h2>业绩周期对比</h2>
      <div class="period-selector-wrapper">
        <label for="period-select">对比周期：</label>
        <select id="period-select" v-model="selectedPeriod" @change="fetchComparisonData" class="period-select">
          <option value="last_week">与上周对比</option>
          <option value="last_month">与上月对比</option>
          <option value="last_quarter">与上季度对比</option>
        </select>
      </div>
    </div>

    <div v-if="isLoading" class="loading-state">
      <div class="loading-spinner"></div>
      <p>正在加载对比数据...</p>
    </div>

    <div v-else-if="!previousPeriodData" class="empty-state">
      <p>暂无对比周期的数据。</p>
    </div>

    <div v-else class="comparison-table-wrapper">
      <table class="comparison-table">
        <thead>
          <tr>
            <th class="metric-col">核心指标</th>
            <th>本期数据</th>
            <th>{{ selectedPeriodLabel }}数据</th>
            <th class="change-col">变化情况</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="metric in comparedMetrics" :key="metric.key">
            <td class="metric-col">
              <span class="metric-label">{{ metric.label }}</span>
            </td>
            <td>{{ formatValue(metric.current, metric.unit) }}</td>
            <td>{{ formatValue(metric.previous, metric.unit) }}</td>
            <td class="change-col">
              <div class="change-cell">
                <span class="change-value" :class="getChangeClass(metric.change.trend)">
                  <span v-if="metric.change.trend === 'up'" class="trend-icon">↑</span>
                  <span v-if="metric.change.trend === 'down'" class="trend-icon">↓</span>
                  {{ metric.change.percentage }}
                </span>
                <span class="change-diff">{{ formatChange(metric.change.diff, metric.unit) }}</span>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
// 假设你有一个API服务来获取对比数据
// import { getPerformanceComparisonData } from '@/api/senorManger.js';

// **MODIFIED**: 更新模拟API以返回新的数据结构
const getPerformanceComparisonData = async (params) => {
  console.log('模拟API请求 (新数据结构):', params);
  return new Promise(resolve => {
    setTimeout(() => {
      let mockData;
      if (params.period === 'last_week') {
        mockData = {
          "allocated_data_volume": 650,
          "wechat_added_volume": 410,
          "call_volume_after_classification": { "加微通话": 10, "20分钟通话": 50, "未分类": 150, "无效通话": 100, "促到课": 40 },
          "call_avg_duration_after_classification": { "加微通话": 4.5, "20分钟通话": 15.0, "未分类": 1.5, "无效通话": 1.0, "促到课": 2.0 },
          "deposit_volume": 40,
          "transaction_volume": 52,
          "conversion_rate": "8.00%"
        };
      } else if (params.period === 'last_month') {
        mockData = {
          "allocated_data_volume": 2800,
          "wechat_added_volume": 1800,
          "call_volume_after_classification": { "加微通话": 40, "20分钟通话": 220, "未分类": 600, "视频通话": 50, "无效通话": 450, "促到课": 180 },
          "call_avg_duration_after_classification": { "加微通话": 5.0, "20分钟通话": 16.0, "未分类": 1.8, "视频通话": 6.0, "无效通话": 1.1, "促到课": 1.5 },
          "deposit_volume": 180,
          "transaction_volume": 230,
          "conversion_rate": "8.21%"
        };
      } else { // last_quarter
        mockData = {
          "allocated_data_volume": 8500,
          "wechat_added_volume": 5500,
          "call_volume_after_classification": { "加微通话": 120, "20分钟通话": 650, "未分类": 1800, "视频通话": 150, "无效通话": 1200, "促到课": 500 },
          "call_avg_duration_after_classification": { "加微通话": 4.8, "20分钟通话": 16.5, "未分类": 1.7, "视频通话": 5.5, "无效通话": 1.0, "促到课": 1.8 },
          "deposit_volume": 550,
          "transaction_volume": 700,
          "conversion_rate": "8.24%"
        };
      }
      resolve({ code: 200, data: mockData });
    }, 800);
  });
};

const props = defineProps({
  currentPeriodData: {
    type: Object,
    required: true,
  },
});

const selectedPeriod = ref('last_month');
const previousPeriodData = ref(null);
const isLoading = ref(false);

const periodLabels = {
  last_week: '上周',
  last_month: '上月',
  last_quarter: '上季度',
};

const selectedPeriodLabel = computed(() => periodLabels[selectedPeriod.value]);

const fetchComparisonData = async () => {
  isLoading.value = true;
  try {
    const res = await getPerformanceComparisonData({ period: selectedPeriod.value });
    if (res.code === 200) {
      previousPeriodData.value = res.data;
    } else {
      previousPeriodData.value = null;
    }
  } catch (error) {
    console.error('获取对比数据失败:', error);
    previousPeriodData.value = null;
  } finally {
    isLoading.value = false;
  }
};

onMounted(() => {
  fetchComparisonData();
});

watch(() => props.currentPeriodData, () => {
    fetchComparisonData();
}, { deep: true });

// **NEW**: 新增一个工具函数，用于处理API返回的复杂数据结构
// 并将其转换为表格渲染所需的扁平化结构
const processRawData = (rawData) => {
  if (!rawData) return null;

  // 1. 计算通话总量
  const totalCalls = Object.values(rawData.call_volume_after_classification || {})
    .reduce((sum, count) => sum + count, 0);

  // 2. 计算通话总时长 (分钟)
  // 逻辑: (分类通话数 * 分类平均时长) 的总和
  const callVolumes = rawData.call_volume_after_classification || {};
  const avgDurations = rawData.call_avg_duration_after_classification || {};
  const totalDurationInMinutes = Object.keys(callVolumes).reduce((sum, key) => {
    const volume = callVolumes[key] || 0;
    const avgDuration = avgDurations[key] || 0;
    return sum + (volume * avgDuration);
  }, 0);

  // 3. 将转化率字符串 "7.98%" 转为数字 7.98
  const conversionRateValue = parseFloat(rawData.conversion_rate) || 0;

  // 4. 返回一个与旧版组件兼容的对象结构
  return {
    assignedLeads: rawData.allocated_data_volume,
    wechatAdds: rawData.wechat_added_volume,
    calls: totalCalls,
    // 组件内部格式化时会除以60，因此这里需要乘以60，将分钟转为秒
    callDuration: totalDurationInMinutes * 60,
    deposits: rawData.deposit_volume,
    deals: rawData.transaction_volume,
    conversionRate: conversionRateValue,
  };
};


const comparedMetrics = computed(() => {
  // **MODIFIED**: 在计算前，先使用 processRawData 对数据进行处理
  const processedCurrentData = processRawData(props.currentPeriodData);
  const processedPreviousData = processRawData(previousPeriodData.value);

  if (!processedCurrentData || !processedPreviousData) return [];
  
  // 指标配置保持不变，因为数据已经被处理成它期望的格式
  const metricsConfig = [
    { key: 'assignedLeads', label: '分配数据量', unit: '个' },
    { key: 'wechatAdds', label: '加微量', unit: '个' },
    { key: 'calls', label: '通话量', unit: '次' },
    { key: 'callDuration', label: '通话总时长', unit: '分钟' },
    { key: 'deposits', label: '定金量', unit: '单' },
    { key: 'deals', label: '成交量', unit: '单' },
    { key: 'conversionRate', label: '转化率', unit: '%' },
  ];

  return metricsConfig.map(metric => {
    const current = processedCurrentData[metric.key];
    const previous = processedPreviousData[metric.key];
    return {
      ...metric,
      current,
      previous,
      change: calculateChange(current, previous),
    };
  });
});

const calculateChange = (current, previous) => {
  if (previous === null || previous === undefined || isNaN(current) || isNaN(previous)) {
    return { diff: 'N/A', percentage: 'N/A', trend: 'neutral' };
  }

  const diff = current - previous;
  let percentage;
  if (previous === 0) {
    percentage = current > 0 ? '+100.0%' : '0.0%';
  } else {
    const percentageValue = (diff / previous) * 100;
    percentage = `${percentageValue > 0 ? '+' : ''}${percentageValue.toFixed(1)}%`;
  }
  
  let trend = 'neutral';
  if (diff > 0) trend = 'up';
  if (diff < 0) trend = 'down';

  return { diff, percentage, trend };
};

const formatValue = (value, unit) => {
  if (value === null || value === undefined) return '-';
  if (unit === '分钟') {
    // 假设传入的value是秒，转换为分钟显示
    return `${Math.round(value / 60)} 分钟`; 
  }
  if (unit === '%') {
    return `${value.toFixed(1)}%`;
  }
  return value.toLocaleString();
};

const formatChange = (diff, unit) => {
  if (typeof diff !== 'number') return '';
  const prefix = diff > 0 ? '+' : '-';
  const absDiff = Math.abs(diff);

  if (unit === '分钟') {
     // 假设diff是秒，转换为分钟显示
     return `${prefix}${Math.round(absDiff / 60)} 分钟`;
  }
  if (unit === '%') {
    return `${prefix}${absDiff.toFixed(1)}%`;
  }
  return `${prefix}${absDiff.toLocaleString()}`;
};

const getChangeClass = (trend) => {
  if (trend === 'up') return 'positive';
  if (trend === 'down') return 'negative';
  return 'neutral';
};

</script>

<style lang="scss" scoped>
/* 样式部分无需改动，因此省略以保持简洁 */
.performance-comparison {
  background: #ffffff;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #e2e8f0;
}

.comparison-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 1rem;
  border-bottom: 1px solid #f1f5f9;

  h2 {
    font-size: 1.5rem;
    font-weight: 700;
    color: #1a202c;
    margin: 0;
  }
  
  .period-selector-wrapper {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    
    label {
      font-size: 0.9rem;
      color: #718096;
    }

    .period-select {
      padding: 0.6rem 1rem;
      border-radius: 8px;
      border: 1px solid #cbd5e0;
      background-color: #ffffff;
      font-size: 0.9rem;
      cursor: pointer;
      transition: border-color 0.2s, box-shadow 0.2s;

      &:hover {
        border-color: #a0aec0;
      }

      &:focus {
        outline: none;
        border-color: #4299e1;
        box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.5);
      }
    }
  }
}

.comparison-table-wrapper {
  overflow-x: auto;
}

.comparison-table {
  width: 100%;
  border-collapse: collapse;
  
  th, td {
    padding: 1rem 1.25rem;
    text-align: left;
    vertical-align: middle;
  }

  thead th {
    font-size: 0.8rem;
    color: #718096;
    font-weight: 600;
    text-transform: uppercase;
    background-color: #f7fafc;
    border-bottom: 2px solid #e2e8f0;
  }

  tbody tr {
    transition: background-color 0.15s ease-in-out;
    &:nth-child(odd) {
      background-color: #fdfdff;
    }
    &:not(:last-child) {
        border-bottom: 1px solid #f1f5f9;
    }
    &:hover {
      background-color: #f0f5ff;
    }
  }

  tbody td {
    font-size: 0.95rem;
    color: #2d3748;
  }
  
  .metric-col {
      min-width: 150px;
      font-weight: 500;
  }

  .change-col {
      width: 180px;
  }
}

.change-cell {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 0.25rem;

  .change-value {
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
    font-weight: 600;
    padding: 0.25rem 0.6rem;
    border-radius: 9999px;
    font-size: 0.85rem;

    &.positive {
      background-color: #ecfdf5;
      color: #065f46;
    }
    &.negative {
      background-color: #fff1f2;
      color: #9f1239;
    }
    &.neutral {
      background-color: #f8fafc;
      color: #475569;
    }

    .trend-icon {
      font-size: 1rem;
    }
  }

  .change-diff {
    font-size: 0.8rem;
    color: #718096;
    margin-left: 0.25rem;
  }
}


.loading-state, .empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 4rem;
  color: #a0aec0;
  font-size: 1rem;
  background-color: #f7fafc;
  border-radius: 8px;

  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #e2e8f0;
    border-top: 4px solid #4299e1;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 1.5rem;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>