<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="text-xl font-bold">WMS报表中心</span>
          <el-button type="primary" @click="refreshAllData">刷新数据</el-button>
        </div>
      </template>

      <!-- 报表导航卡片 -->
      <el-row :gutter="20" class="mb-6">
        <el-col :span="8" v-for="report in reportCards" :key="report.key">
          <el-card shadow="hover" class="report-card" @click="navigateToReport(report.route)">
            <div class="report-item">
              <div class="report-icon">
                <el-icon :size="40" :color="report.color">
                  <component :is="report.icon" />
                </el-icon>
              </div>
              <div class="report-content">
                <div class="report-title">{{ report.title }}</div>
                <div class="report-desc">{{ report.description }}</div>
                <div class="report-count">{{ report.count }} 条记录</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 快速统计概览 -->
      <el-row :gutter="20" class="mb-6">
        <el-col :span="24">
          <el-card shadow="hover">
            <template #header>
              <span>快速统计概览</span>
            </template>
            <el-row :gutter="20">
              <el-col :span="4">
                <div class="overview-item">
                  <div class="overview-value text-red-500">{{ overviewStats.alertCount }}</div>
                  <div class="overview-label">预警物料</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="overview-item">
                  <div class="overview-value text-orange-500">{{ overviewStats.stagnantCount }}</div>
                  <div class="overview-label">呆滞物料</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="overview-item">
                  <div class="overview-value text-yellow-500">{{ overviewStats.returnCount }}</div>
                  <div class="overview-label">退库单数</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="overview-item">
                  <div class="overview-value text-blue-500">{{ overviewStats.differenceCount }}</div>
                  <div class="overview-label">盘点差异</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="overview-item">
                  <div class="overview-value text-green-500">{{ overviewStats.avgTurnoverRate.toFixed(1) }}%</div>
                  <div class="overview-label">平均周转率</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="overview-item">
                  <div class="overview-value text-purple-500">{{ overviewStats.totalInventory }}</div>
                  <div class="overview-label">总库存量</div>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表展示区域 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <span>报表数据分布</span>
            </template>
            <div ref="pieChartRef" style="height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <span>关键指标趋势</span>
            </template>
            <div ref="lineChartRef" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup name="ReportDashboard" lang="ts">
import { 
  getReturnReasonAnalysis, 
  getInventoryTrendAnalysis, 
  getSafetyStockAlert, 
  getStagnantInventory, 
  getInventoryDifference, 
  getInventoryTurnover 
} from '@/api/wms/report';
import * as echarts from 'echarts';
import { useRouter } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();

// 报表卡片配置
const reportCards = ref([
  {
    key: 'returnReason',
    title: '退库原因分析',
    description: '分析各类退库原因及占比',
    icon: 'PieChart',
    color: '#409EFF',
    route: '/wms/returnReasonAnalysis',
    count: 0
  },
  {
    key: 'inventoryTrend',
    title: '库存变动趋势',
    description: '展示库存数量变化趋势',
    icon: 'TrendCharts',
    color: '#67C23A',
    route: '/wms/inventoryTrendAnalysis',
    count: 0
  },
  {
    key: 'safetyStock',
    title: '安全库存预警',
    description: '监控库存安全水位',
    icon: 'Warning',
    color: '#E6A23C',
    route: '/wms/safetyStockAlert',
    count: 0
  },
  {
    key: 'stagnantInventory',
    title: '呆滞料库存',
    description: '识别长期未流动物料',
    icon: 'Clock',
    color: '#F56C6C',
    route: '/wms/stagnantInventory',
    count: 0
  },
  {
    key: 'inventoryDifference',
    title: '库存差异报表',
    description: '盘点差异分析',
    icon: 'DataAnalysis',
    color: '#909399',
    route: '/wms/inventoryDifference',
    count: 0
  },
  {
    key: 'inventoryTurnover',
    title: '库存周转报表',
    description: '分析库存周转效率',
    icon: 'Refresh',
    color: '#9C27B0',
    route: '/wms/inventoryTurnover',
    count: 0
  }
]);

// 概览统计数据
const overviewStats = ref({
  alertCount: 0,
  stagnantCount: 0,
  returnCount: 0,
  differenceCount: 0,
  avgTurnoverRate: 0,
  totalInventory: 0
});

// 图表引用
const pieChartRef = ref<HTMLDivElement>();
const lineChartRef = ref<HTMLDivElement>();
let pieChart: echarts.ECharts;
let lineChart: echarts.ECharts;

/** 导航到具体报表页面 */
const navigateToReport = (route: string) => {
  router.push(route);
};

/** 刷新所有数据 */
const refreshAllData = async () => {
  await Promise.all([
    loadReturnReasonData(),
    loadInventoryTrendData(),
    loadSafetyStockData(),
    loadStagnantInventoryData(),
    loadInventoryDifferenceData(),
    loadInventoryTurnoverData()
  ]);
  
  nextTick(() => {
    updateCharts();
  });
};

/** 加载各报表数据 */
const loadReturnReasonData = async () => {
  try {
    const res = await getReturnReasonAnalysis({});
    reportCards.value[0].count = res.data.length;
    overviewStats.value.returnCount = res.data.reduce((sum, item) => sum + (item.returnOrderCount || 0), 0);
  } catch (error) {
    console.error('加载退库原因数据失败:', error);
  }
};

const loadInventoryTrendData = async () => {
  try {
    const res = await getInventoryTrendAnalysis({});
    reportCards.value[1].count = res.data.length;
  } catch (error) {
    console.error('加载库存趋势数据失败:', error);
  }
};

const loadSafetyStockData = async () => {
  try {
    const res = await getSafetyStockAlert({});
    reportCards.value[2].count = res.data.length;
    overviewStats.value.alertCount = res.data.filter(item => item.alertStatus !== '正常').length;
  } catch (error) {
    console.error('加载安全库存数据失败:', error);
  }
};

const loadStagnantInventoryData = async () => {
  try {
    const res = await getStagnantInventory({});
    reportCards.value[3].count = res.data.length;
    overviewStats.value.stagnantCount = res.data.length;
    overviewStats.value.totalInventory = res.data.reduce((sum, item) => sum + (item.stagnantInventoryQty || 0), 0);
  } catch (error) {
    console.error('加载呆滞料数据失败:', error);
  }
};

const loadInventoryDifferenceData = async () => {
  try {
    const res = await getInventoryDifference({});
    reportCards.value[4].count = res.data.length;
    overviewStats.value.differenceCount = res.data.filter(item => item.differenceType !== '无差异').length;
  } catch (error) {
    console.error('加载库存差异数据失败:', error);
  }
};

const loadInventoryTurnoverData = async () => {
  try {
    const res = await getInventoryTurnover({});
    reportCards.value[5].count = res.data.length;
    overviewStats.value.avgTurnoverRate = res.data.length > 0 
      ? res.data.reduce((sum, item) => sum + (item.inventoryTurnoverRate || 0), 0) / res.data.length 
      : 0;
  } catch (error) {
    console.error('加载库存周转数据失败:', error);
  }
};

/** 初始化图表 */
const initCharts = () => {
  if (pieChartRef.value) {
    pieChart = echarts.init(pieChartRef.value);
  }
  if (lineChartRef.value) {
    lineChart = echarts.init(lineChartRef.value);
  }
};

/** 更新图表数据 */
const updateCharts = () => {
  // 饼图：报表数据分布
  const pieData = reportCards.value.map(card => ({
    name: card.title,
    value: card.count
  }));

  const pieOption = {
    title: {
      text: '报表数据分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '数据量',
        type: 'pie',
        radius: '50%',
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  // 折线图：关键指标趋势（模拟数据）
  const lineOption = {
    title: {
      text: '关键指标趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['预警物料', '呆滞物料', '差异物料'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: ['本周', '上周', '上上周', '三周前', '四周前']
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '预警物料',
        type: 'line',
        data: [overviewStats.value.alertCount, overviewStats.value.alertCount * 0.9, overviewStats.value.alertCount * 1.1, overviewStats.value.alertCount * 0.8, overviewStats.value.alertCount * 1.2],
        smooth: true,
        itemStyle: { color: '#E6A23C' }
      },
      {
        name: '呆滞物料',
        type: 'line',
        data: [overviewStats.value.stagnantCount, overviewStats.value.stagnantCount * 1.1, overviewStats.value.stagnantCount * 0.9, overviewStats.value.stagnantCount * 1.3, overviewStats.value.stagnantCount * 0.7],
        smooth: true,
        itemStyle: { color: '#F56C6C' }
      },
      {
        name: '差异物料',
        type: 'line',
        data: [overviewStats.value.differenceCount, overviewStats.value.differenceCount * 0.8, overviewStats.value.differenceCount * 1.2, overviewStats.value.differenceCount * 0.6, overviewStats.value.differenceCount * 1.4],
        smooth: true,
        itemStyle: { color: '#909399' }
      }
    ]
  };

  pieChart?.setOption(pieOption);
  lineChart?.setOption(lineOption);
};

/** 窗口大小改变时重新调整图表 */
const handleResize = () => {
  pieChart?.resize();
  lineChart?.resize();
};

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

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

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

.report-card {
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.report-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.report-item {
  display: flex;
  align-items: center;
  padding: 20px;
}

.report-icon {
  margin-right: 20px;
}

.report-content {
  flex: 1;
}

.report-title {
  font-size: 1.2rem;
  font-weight: bold;
  margin-bottom: 8px;
  color: #303133;
}

.report-desc {
  font-size: 0.9rem;
  color: #606266;
  margin-bottom: 8px;
}

.report-count {
  font-size: 0.8rem;
  color: #909399;
}

.overview-item {
  text-align: center;
  padding: 20px;
}

.overview-value {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 8px;
}

.overview-label {
  font-size: 0.9rem;
  color: #666;
}

.el-card {
  margin-bottom: 20px;
}
</style>