<template>
  <div class="dashboard-container" v-loading="loading">
    <!-- 第一排：客户统计 & 客户跟进 -->
    <el-row :gutter="15">
      <el-col :span="12">
        <div class="stat-card color-customer">
          <div class="card-header"><span class="title">客户</span></div>
          <div class="card-body">
            <div class="stat-grid">
              <div v-for="(item, index) in customerStats" :key="index" class="stat-item">
                <div class="label">{{ item.label }}</div>
                <div class="value">{{ item.value }}</div>
                <div v-if="item.trend !== undefined" class="trend">
                  较上周 <span :class="item.trend >= 0 ? 'up' : 'down'">
                    {{ Math.abs(Math.round(item.trend * 100)) }}%
                    <i :class="item.trend >= 0 ? 'i-ep-caret-top' : 'i-ep-caret-bottom'"></i>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="stat-card color-followup">
          <div class="card-header"><span class="title">客户跟进</span></div>
          <div class="card-body">
            <div class="stat-grid">
              <div v-for="(item, index) in followUpStats" :key="index" class="stat-item">
                <div class="label">{{ item.label }}</div>
                <div class="value">{{ item.value }}</div>
                <div v-if="item.trend !== undefined" class="trend">
                  较上周 <span :class="item.trend >= 0 ? 'up' : 'down'">
                    {{ Math.abs(Math.round(item.trend * 100)) }}%
                    <i :class="item.trend >= 0 ? 'i-ep-caret-top' : 'i-ep-caret-bottom'"></i>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 第二排：项目商机 & 跟进中的项目商机 -->
    <el-row :gutter="15" class="mt15">
      <el-col :span="12">
        <div class="stat-card color-opp-total">
          <div class="card-header"><span class="title">项目商机</span></div>
          <div class="card-body">
            <div class="stat-grid">
              <div v-for="(item, index) in opportunityTotalStats" :key="index" class="stat-item">
                <div class="label">{{ item.label }}</div>
                <div class="value">{{ item.value }}</div>
                <div v-if="item.trend !== undefined" class="trend">
                  较上周 <span :class="item.trend >= 0 ? 'up' : 'down'">
                    {{ Math.abs(Math.round(item.trend * 100)) }}%
                    <i :class="item.trend >= 0 ? 'i-ep-caret-top' : 'i-ep-caret-bottom'"></i>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="stat-card color-opp-follow">
          <div class="card-header"><span class="title">跟进中的项目商机</span></div>
          <div class="card-body">
            <div class="stat-grid">
              <div v-for="(item, index) in opportunityInFollowStats" :key="index" class="stat-item">
                <div class="label">{{ item.label }}</div>
                <div class="value">{{ item.value }}</div>
                <div v-if="item.trend !== undefined" class="trend">
                  较上周 <span :class="item.trend >= 0 ? 'up' : 'down'">
                    {{ Math.abs(Math.round(item.trend * 100)) }}%
                    <i :class="item.trend >= 0 ? 'i-ep-caret-top' : 'i-ep-caret-bottom'"></i>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 第三排：年度入围 & 跟进中的年度入围 -->
    <el-row :gutter="15" class="mt15">
      <el-col :span="12">
        <div class="stat-card color-sel-total">
          <div class="card-header"><span class="title">年度入围</span></div>
          <div class="card-body">
            <div class="stat-grid">
              <div v-for="(item, index) in selectionTotalStats" :key="index" class="stat-item">
                <div class="label">{{ item.label }}</div>
                <div class="value">{{ item.value }}</div>
                <div v-if="item.trend !== undefined" class="trend">
                  较上周 <span :class="item.trend >= 0 ? 'up' : 'down'">
                    {{ Math.abs(Math.round(item.trend * 100)) }}%
                    <i :class="item.trend >= 0 ? 'i-ep-caret-top' : 'i-ep-caret-bottom'"></i>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="stat-card color-sel-follow">
          <div class="card-header"><span class="title">跟进中的年度入围</span></div>
          <div class="card-body">
            <div class="stat-grid">
              <div v-for="(item, index) in selectionInFollowStats" :key="index" class="stat-item">
                <div class="label">{{ item.label }}</div>
                <div class="value">{{ item.value }}</div>
                <div v-if="item.trend !== undefined" class="trend">
                  较上周 <span :class="item.trend >= 0 ? 'up' : 'down'">
                    {{ Math.abs(Math.round(item.trend * 100)) }}%
                    <i :class="item.trend >= 0 ? 'i-ep-caret-top' : 'i-ep-caret-bottom'"></i>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 漏斗图排 -->
    <el-row :gutter="20" class="mt20">
      <el-col :span="8">
        <div class="stat-card chart-card color-funnel-opp">
          <div class="card-header"><span class="title">商机漏斗</span></div>
          <div class="card-body"><div ref="oppFunnelRef" class="chart-box"></div></div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="stat-card chart-card color-funnel-cus">
          <div class="card-header"><span class="title">客户漏斗</span></div>
          <div class="card-body"><div ref="cusFunnelRef" class="chart-box"></div></div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="stat-card chart-card color-visit-stat">
          <div class="card-header"><span class="title">访销统计</span></div>
          <div class="card-body"><div ref="visitChartRef" class="chart-box"></div></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, shallowRef, onMounted, onUnmounted, nextTick } from 'vue';
import { getWorkbenchStat } from '@/api/workbench';
import * as echarts from 'echarts';
import { debounce } from '@/utils';

const loading = ref(false);

interface StatItem {
  label: string;
  value: string;
  trend?: number;
  unit?: string;
}

// 统计面板数据
const customerStats = ref<StatItem[]>([]);
const followUpStats = ref<StatItem[]>([]);
const opportunityTotalStats = ref<StatItem[]>([]);
const opportunityInFollowStats = ref<StatItem[]>([]);
const selectionTotalStats = ref<StatItem[]>([]);
const selectionInFollowStats = ref<StatItem[]>([]);

// 图表 DOM 引用
const oppFunnelRef = ref<HTMLElement | null>(null);
const cusFunnelRef = ref<HTMLElement | null>(null);
const visitChartRef = ref<HTMLElement | null>(null);

// 图表实例
const oppChart = shallowRef<echarts.ECharts | null>(null);
const cusChart = shallowRef<echarts.ECharts | null>(null);
const visitChart = shallowRef<echarts.ECharts | null>(null);

// 颜色：蓝、绿、黄
const colors = ['#409EFF', '#67C23A', '#E6A23C'];

// 初始化商机漏斗
const initOppFunnel = (data: StatItem[]) => {
  if (!oppFunnelRef.value || !data.length) return;
  if (!oppChart.value) oppChart.value = echarts.init(oppFunnelRef.value);
  const funnelData = data.map((item, index) => ({
    name: item.label,
    value: 100 - index * 30,
    realValue: item.value,
    unit: item.unit || '',
    itemStyle: { color: colors[index % colors.length] }
  }));
  oppChart.value.setOption({
    tooltip: { trigger: 'item', formatter: (p: any) => `${p.data.name}: ${p.data.realValue}万` },
    series: [
      {
        type: 'funnel', left: '5%', right: '40%', top: 20, bottom: 20, width: '55%',
        label: { show: true, position: 'inside', formatter: (p: any) => `${p.data.name}: ${p.data.realValue}万`, color: '#fff' },
        data: funnelData
      },
      {
        type: 'funnel', left: '5%', right: '40%', top: 20, bottom: 20, width: '55%',
        label: { show: true, position: 'right', formatter: (p: any) => `{name|${p.data.name}}\n{value|${p.data.unit}}`, rich: { name: { color: '#666', fontSize: 11, align: 'left', padding: [0,0,4,10] }, value: { color: '#333', fontSize: 12, fontWeight: 'bold', align: 'left', padding: [0,0,0,10] } } },
        labelLine: { show: true, length: 40, lineStyle: { color: '#ddd' } },
        data: funnelData, z: 1
      }
    ]
  });
};

// 初始化客户漏斗
const initCusFunnel = (data: StatItem[]) => {
  if (!cusFunnelRef.value || !data.length) return;
  if (!cusChart.value) cusChart.value = echarts.init(cusFunnelRef.value);
  const funnelData = data.map((item, index) => ({
    name: item.label,
    value: 100 - index * 30,
    realValue: item.value,
    unit: item.unit || '',
    itemStyle: { color: colors[index % colors.length] }
  }));
  cusChart.value.setOption({
    tooltip: { trigger: 'item', formatter: (p: any) => `${p.data.name}: ${p.data.realValue}个` },
    series: [{
      type: 'funnel', left: '10%', right: '10%', top: 20, bottom: 20, width: '80%',
      label: { show: true, position: 'inside', formatter: (p: any) => `${p.data.name}: ${p.data.realValue}个`, color: '#fff' },
      data: funnelData
    }]
  });
};

// 初始化访销统计
const initVisitChart = (data: StatItem[]) => {
  if (!visitChartRef.value || !data.length) return;
  if (!visitChart.value) visitChart.value = echarts.init(visitChartRef.value);
  const chartData = data.map((item, index) => ({
    name: item.label,
    value: parseFloat(item.value) || 0,
    itemStyle: { color: ['#409EFF', '#67C23A', '#FFBB96'][index % 3] }
  }));
  visitChart.value.setOption({
    tooltip: { trigger: 'item', formatter: '{b}: {c}' },
    legend: {
      orient: 'vertical', right: '2%', top: 'center', itemGap: 20,
      formatter: (name: string) => {
        const item = data.find(i => i.label === name);
        return `{name|${name}: }{value|${item?.value || ''}}`;
      },
      textStyle: { rich: { name: { color: '#666' }, value: { color: '#333', fontWeight: 'bold' } } }
    },
    series: [
      { type: 'pie', radius: ['45%', '65%'], center: ['30%', '50%'], label: { show: false }, data: chartData },
      { type: 'pie', radius: ['40%', '70%'], center: ['30%', '50%'], silent: true, itemStyle: { color: '#f0f2f5' }, z: -1, data: [{ value: 1 }] }
    ]
  });
};

// 获取数据并刷新图表
const getStats = async () => {
  loading.value = true;
  try {
    const res = await getWorkbenchStat();
    if (res.data) {
      customerStats.value = res.data.customerStats;
      followUpStats.value = res.data.followUpStats;
      opportunityTotalStats.value = res.data.opportunityTotalStats;
      opportunityInFollowStats.value = res.data.opportunityInFollowStats;
      selectionTotalStats.value = res.data.selectionTotalStats;
      selectionInFollowStats.value = res.data.selectionInFollowStats;
      
      nextTick(() => {
        initOppFunnel(res.data.opportunityFunnel);
        initCusFunnel(res.data.customerFunnel);
        initVisitChart(res.data.visitStats);
      });
    }
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
};

const handleResize = debounce(() => {
  oppChart.value?.resize();
  cusChart.value?.resize();
  visitChart.value?.resize();
}, 200, false);

onMounted(() => {
  getStats();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 15px; background-color: #f5f7fa; min-height: calc(100vh - 84px);
  .mt15 { margin-top: 15px; }
    .el-row {
      display: flex;
      flex-wrap: wrap;
      align-items: stretch; /* 确保所有列等高 */
    }

    .el-col {
      display: flex;
      flex-direction: column;
    }

    .stat-card {
      background: #fff;
      border-radius: 8px;
      border: 1px solid #f0f0f0;
      /* 使用更清晰的多层阴影 */
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.02), 0 4px 12px rgba(0, 0, 0, 0.05);
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      position: relative;
      overflow: hidden;
      
      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.05);
        border-color: #409eff44;
      }

    .card-header {
      padding: 12px 16px;
      border-bottom: 1px solid #f8f8f8;
      background-color: #fafbfc; /* 头部微背景色，增加层次感 */
      .title { 
        font-size: 14px; 
        font-weight: 700; 
        color: #1a1a1a; 
        letter-spacing: 0.5px;
      }
    }

    .card-body {
      padding: 16px;
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      
      .stat-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        .stat-item {
          flex: 1;
          min-width: 100px;
          height: 90px;
          background-color: #ffffff;
          border: 1px solid #f2f2f2; /* 给子项添加细边框增加清晰度 */
          padding: 12px;
          border-radius: 6px;
          display: flex;
          flex-direction: column;
          transition: all 0.2s ease;
          cursor: default;

          &:hover {
            background-color: #f5f9ff;
            border-color: #d9ecff;
            transform: scale(1.02);
          }

          .label { 
            font-size: 12px; 
            color: #8c8c8c; 
            margin-bottom: 8px; 
            font-weight: 500;
          }
          .value { 
            font-size: 24px; 
            font-weight: 800; 
            color: #262626; 
            margin-bottom: 6px;
            line-height: 1;
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
          }
          .trend {
            font-size: 11px;
            color: #bfbfbf;
            white-space: nowrap;
            display: flex;
            align-items: center;
            .up { color: #52c41a; margin-left: 4px; font-weight: bold; }
            .down { color: #f5222d; margin-left: 4px; font-weight: bold; }
          }
        }
      }
    }
  }
  .chart-card:hover {
    transform: none; /* 图表卡片保持静止，避免 canvas 抖动 */
  }
  .chart-box { width: 100%; height: 350px; }

  /* 颜色装饰类 */
  .color-customer { .title { color: #409eff !important; } }
  .color-followup { .title { color: #409eff !important; } }
  .color-opp-total { .title { color: #409eff !important; } }
  .color-opp-follow { .title { color: #409eff !important; } }
  .color-sel-total { .title { color: #409eff !important; } }
  .color-sel-follow { .title { color: #409eff !important; } }
  .color-funnel-opp { .title { color: #409eff !important; } }
  .color-funnel-cus { .title { color: #409eff !important; } }
  .color-visit-stat { .title { color: #409eff !important; } }
}
</style>
