<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { Document, Upload, FolderOpened, MessageBox, Clock } from '@element-plus/icons-vue';
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';

// 统计数据
const statistics = ref({
  pendingUpload: 0,      // 待上传文件数
  pendingArchive: 0,     // 待归档文件数
  pendingSubmit: 0,      // 待递交文件数
  overdueSubmit: 0,      // 逾期未递交文件数
  pendingReview: 0       // 待审核文件数
});

// 卡片配置
const cardConfigs = [
  {
    title: '待上传文件数',
    key: 'pendingUpload',
    icon: Upload,
    color: '#409EFF',
    bgColor: '#ecf5ff'
  },
  {
    title: '待归档文件数',
    key: 'pendingArchive',
    icon: FolderOpened,
    color: '#67C23A',
    bgColor: '#f0f9ff'
  },
  {
    title: '待递交文件数',
    key: 'pendingSubmit',
    icon: Document,
    color: '#E6A23C',
    bgColor: '#fdf6ec'
  },
  {
    title: '逾期未递交文件数',
    key: 'overdueSubmit',
    icon: Clock,
    color: '#F56C6C',
    bgColor: '#fef0f0'
  },
  {
    title: '待审核文件数',
    key: 'pendingReview',
    icon: MessageBox,
    color: '#909399',
    bgColor: '#f4f4f5'
  }
];

// 图表实例
const pieChartRef = ref<HTMLDivElement>();
let pieChartInstance: echarts.ECharts | null = null;

// 获取统计数据
const fetchStatistics = async () => {
  try {
    // TODO: 替换为实际的API调用
    // const res = await getWorkbenchStatistics();
    // statistics.value = res.data;
    
    // 模拟数据
    statistics.value = {
      pendingUpload: 12,
      pendingArchive: 8,
      pendingSubmit: 15,
      overdueSubmit: 3,
      pendingReview: 6
    };
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
};

// 初始化饼状图
const initPieChart = () => {
  if (!pieChartRef.value) return;
  
  // 如果已存在实例，先销毁
  if (pieChartInstance) {
    pieChartInstance.dispose();
  }
  
  pieChartInstance = echarts.init(pieChartRef.value);
  
  const option: EChartsOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: '10%',
      top: 'center',
      itemGap: 15,
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '文件统计',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['35%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: statistics.value.pendingUpload, name: '待上传文件数', itemStyle: { color: '#409EFF' } },
          { value: statistics.value.pendingArchive, name: '待归档文件数', itemStyle: { color: '#67C23A' } },
          { value: statistics.value.pendingSubmit, name: '待递交文件数', itemStyle: { color: '#E6A23C' } },
          { value: statistics.value.overdueSubmit, name: '逾期未递交文件数', itemStyle: { color: '#F56C6C' } },
          { value: statistics.value.pendingReview, name: '待审核文件数', itemStyle: { color: '#909399' } }
        ]
      }
    ]
  };
  
  pieChartInstance.setOption(option);
};

// 监听统计数据变化，更新图表
watch(statistics, () => {
  if (pieChartInstance) {
    initPieChart();
  }
}, { deep: true });

// 窗口大小变化时调整图表
const handleResize = () => {
  pieChartInstance?.resize();
};

onMounted(async () => {
  await fetchStatistics();
  await nextTick();
  initPieChart();
  window.addEventListener('resize', handleResize);
});

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

<template>
  <div class="workbench-container">
    <!-- 第一行：统计卡片 -->
    <div class="statistics-cards">
      <el-card 
        v-for="card in cardConfigs" 
        :key="card.key"
        class="stat-card"
        shadow="hover"
      >
        <div class="card-content">
          <div class="icon-wrapper" :style="{ backgroundColor: card.bgColor }">
            <el-icon :size="32" :color="card.color">
              <component :is="card.icon" />
            </el-icon>
          </div>
          <div class="info-wrapper">
            <div class="title">{{ card.title }}</div>
            <div class="count" :style="{ color: card.color }">
              {{ statistics[card.key] }}
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 第二行：饼状图 -->
    <div class="chart-section">
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="header-title">文件统计分布</span>
          </div>
        </template>
        <div ref="pieChartRef" class="pie-chart"></div>
      </el-card>
    </div>
  </div>
</template>

<style scoped lang="scss">
.workbench-container {
  padding: 20px;

  .statistics-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 20px;
    margin-bottom: 20px;

    @media (max-width: 1400px) {
      grid-template-columns: repeat(3, 1fr);
    }

    @media (max-width: 992px) {
      grid-template-columns: repeat(2, 1fr);
    }

    @media (max-width: 576px) {
      grid-template-columns: 1fr;
    }

    .stat-card {
      cursor: pointer;
      transition: transform 0.3s ease, box-shadow 0.3s ease;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
      }

      :deep(.el-card__body) {
        padding: 20px;
      }

      .card-content {
        display: flex;
        align-items: center;
        gap: 16px;

        .icon-wrapper {
          width: 64px;
          height: 64px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;
        }

        .info-wrapper {
          flex: 1;
          min-width: 0;

          .title {
            font-size: 14px;
            color: #606266;
            margin-bottom: 8px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .count {
            font-size: 28px;
            font-weight: bold;
            line-height: 1;
          }
        }
      }
    }
  }

  .chart-section {
    margin-top: 20px;
    
    .chart-card {
      :deep(.el-card__header) {
        padding: 16px 20px;
        border-bottom: 1px solid #ebeef5;
      }

      :deep(.el-card__body) {
        padding: 20px;
      }

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

        .header-title {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }

      .pie-chart {
        width: 100%;
        height: 400px;
      }
    }
  }
}
</style>
