<template>
  <div class="app-container home">
    <el-row :gutter="20" class="panel-group">
      <el-col :span="6" class="card-panel-col">
        <el-card shadow="hover" class="box-card">
          <div class="card-panel-icon-wrapper icon-blue">
            <el-icon :size="45"><OfficeBuilding /></el-icon>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">供应商总数</div>
            <div class="card-panel-num">
              <span v-if="!loadingSupplier">{{ formatNum(supplierTotal) }}</span>
              <el-skeleton v-else animated :rows="1" style="width: 80px;" />
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6" class="card-panel-col">
        <el-card shadow="hover" class="box-card">
          <div class="card-panel-icon-wrapper icon-green">
            <el-icon :size="45"><Goods /></el-icon>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">商品总数</div>
            <div class="card-panel-num">
              <span v-if="!loadingProduct">{{ formatNum(productTotal) }}</span>
              <el-skeleton v-else animated :rows="1" style="width: 80px;" />
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6" class="card-panel-col">
        <el-card shadow="hover" class="box-card">
          <div class="card-panel-icon-wrapper icon-orange">
            <el-icon :size="45"><Document /></el-icon>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">采购订单</div>
            <div class="card-panel-num">
              <span v-if="!loadingOrder">{{ formatNum(orderTotal) }}</span>
              <el-skeleton v-else animated :rows="1" style="width: 80px;" />
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6" class="card-panel-col">
        <el-card shadow="hover" class="box-card">
          <div class="card-panel-icon-wrapper icon-red">
            <el-icon :size="45"><Clock /></el-icon>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">待审核商品</div>
            <div class="card-panel-num">
              <span v-if="!loadingProduct">{{ formatNum(waitAuditCount) }}</span>
              <el-skeleton v-else animated :rows="1" style="width: 80px;" />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="16">
        <el-card shadow="hover" v-loading="loadingOrderStats">
          <template #header>
            <div class="clearfix">
              <span>订单状态分布</span>
            </div>
          </template>
          <div ref="barChartRef" style="height: 350px; width: 100%;"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" v-loading="loadingProduct">
          <template #header>
            <div class="clearfix">
              <span>商品状态分布</span>
            </div>
          </template>
          <div ref="pieChartRef" style="height: 350px; width: 100%;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Index" lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import * as echarts from 'echarts';
import { OfficeBuilding, Goods, Document, Clock } from '@element-plus/icons-vue';
import { listInfo } from '@/api/customer/supplierInfo';
import { getProductStatusCount } from '@/api/product/base';
import { listOrderMain, queryOrderStatusStats } from '@/api/order/orderMain';

const barChartRef = ref<HTMLElement | null>(null);
const pieChartRef = ref<HTMLElement | null>(null);

let barChart: echarts.ECharts | null = null;
let pieChart: echarts.ECharts | null = null;

// 统计数据
const supplierTotal = ref(0);
const productTotal = ref(0);
const orderTotal = ref(0);
const waitAuditCount = ref(0);

// 加载状态
const loadingSupplier = ref(true);
const loadingProduct = ref(true);
const loadingOrder = ref(true);
const loadingOrderStats = ref(true);

// 格式化数字
const formatNum = (num: number): string => {
  if (num === 0) return '0';
  return num.toLocaleString('zh-CN');
};

/** 获取供应商总数 */
const fetchSupplierTotal = async () => {
  try {
    const res: any = await listInfo({ pageNum: 1, pageSize: 1 });
    supplierTotal.value = res.total || 0;
  } catch (error) {
    console.error('获取供应商总数失败:', error);
  } finally {
    loadingSupplier.value = false;
  }
};

/** 获取商品统计数据 */
const fetchProductStats = async () => {
  try {
    const res: any = await getProductStatusCount();
    if (res.data) {
      productTotal.value = res.data.total || 0;
      waitAuditCount.value = res.data.waitAudit || 0;
      // 初始化饼图
      initPieChart(res.data);
    }
  } catch (error) {
    console.error('获取商品统计失败:', error);
  } finally {
    loadingProduct.value = false;
  }
};

/** 获取订单总数 */
const fetchOrderTotal = async () => {
  try {
    const res: any = await listOrderMain({ pageNum: 1, pageSize: 1 });
    orderTotal.value = res.total || 0;
  } catch (error) {
    console.error('获取订单总数失败:', error);
  } finally {
    loadingOrder.value = false;
  }
};

/** 获取订单状态分布 */
const fetchOrderStats = async () => {
  try {
    const res: any = await queryOrderStatusStats();
    initBarChart(res);
  } catch (error) {
    console.error('获取订单状态统计失败:', error);
  } finally {
    loadingOrderStats.value = false;
  }
};

/** 初始化订单状态柱状图 */
const initBarChart = (data: any) => {
  if (!barChartRef.value) return;
  barChart = echarts.init(barChartRef.value);
  const categories = ['待付款', '待发货', '已发货', '已完成', '已关闭'];
  const values = [
    data?.pendingPaymentCount || 0,
    data?.pendingShipmentCount || 0,
    data?.shippedCount || 0,
    data?.completedCount || 0,
    data?.closedCount || 0
  ];
  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      data: ['订单数量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: { fontSize: 12 }
    },
    yAxis: {
      type: 'value',
      minInterval: 1
    },
    series: [
      {
        name: '订单数量',
        type: 'bar',
        barWidth: '50%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#409EFF' },
            { offset: 1, color: '#79bbff' }
          ]),
          borderRadius: [6, 6, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#337ecc' },
              { offset: 1, color: '#5ba5e8' }
            ])
          }
        },
        label: {
          show: true,
          position: 'top',
          fontSize: 12,
          color: '#333'
        },
        data: values
      }
    ]
  };
  barChart.setOption(option);
};

/** 初始化商品状态饼图 */
const initPieChart = (data: any) => {
  if (!pieChartRef.value) return;
  pieChart = echarts.init(pieChartRef.value);
  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      bottom: '0%',
      left: 'center'
    },
    series: [
      {
        name: '商品状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: data?.onSale || 0, name: '已上架', itemStyle: { color: '#67C23A' } },
          { value: data?.offSale || 0, name: '已下架', itemStyle: { color: '#909399' } },
          { value: data?.waitAudit || 0, name: '待审核', itemStyle: { color: '#E6A23C' } },
          { value: data?.auditPass || 0, name: '审核通过', itemStyle: { color: '#409EFF' } },
          { value: data?.auditReject || 0, name: '审核驳回', itemStyle: { color: '#F56C6C' } }
        ]
      }
    ]
  };
  pieChart.setOption(option);
};

const handleResize = () => {
  if (barChart) barChart.resize();
  if (pieChart) pieChart.resize();
};

onMounted(() => {
  nextTick(() => {
    window.addEventListener('resize', handleResize);
  });
  // 并行请求所有数据
  fetchSupplierTotal();
  fetchProductStats();
  fetchOrderTotal();
  fetchOrderStats();
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  if (barChart) barChart.dispose();
  if (pieChart) pieChart.dispose();
});
</script>

<style lang="scss" scoped>
.home {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);

  .panel-group {
    margin-bottom: 20px;

    .card-panel-col {
      margin-bottom: 10px;
    }

    .box-card {
      :deep(.el-card__body) {
        padding: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      .card-panel-icon-wrapper {
        padding: 16px;
        border-radius: 12px;
        transition: all 0.38s ease-out;
      }

      .icon-blue {
        color: #40c9c6;
        background: #eaffff;
      }
      .icon-green {
        color: #36a3f7;
        background: #e8f4ff;
      }
      .icon-orange {
        color: #f4516c;
        background: #ffe8eb;
      }
      .icon-red {
        color: #34bfa3;
        background: #eafff6;
      }

      &:hover {
        .card-panel-icon-wrapper {
          color: #fff;
        }
        .icon-blue {
          background: #40c9c6;
        }
        .icon-green {
          background: #36a3f7;
        }
        .icon-orange {
          background: #f4516c;
        }
        .icon-red {
          background: #34bfa3;
        }
      }

      .card-panel-description {
        font-weight: bold;
        text-align: right;

        .card-panel-text {
          line-height: 18px;
          color: #8c8c8c;
          font-size: 16px;
          margin-bottom: 12px;
        }

        .card-panel-num {
          font-size: 24px;
          color: #333;
          min-height: 32px;
          display: flex;
          align-items: center;
          justify-content: flex-end;
        }
      }
    }
  }
}
</style>
