<template>
  <div class="app-container home">
    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="panel-group">
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-blue">
            <el-icon><ShoppingCart /></el-icon>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">今日新增订单</div>
            <div class="card-panel-num">{{ dashboardData.todayOrders }}</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-green">
            <el-icon><Money /></el-icon>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">本周销售总额</div>
            <div class="card-panel-num">{{ formatCurrency(dashboardData.weekRevenue) }}</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-orange">
            <el-icon><Van /></el-icon>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">待发货数量</div>
            <div class="card-panel-num">{{ dashboardData.pendingShipment }}</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-purple">
            <el-icon><Goods /></el-icon>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">在售商品数</div>
            <div class="card-panel-num">{{ dashboardData.onSaleProducts.toLocaleString() }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表和列表 -->
    <el-row :gutter="20" class="chart-container">
      <!-- 折线图 -->
      <el-col :xs="24" :sm="24" :lg="16">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>近期订单发货量走势</span>
            </div>
          </template>
          <div ref="lineChartRef" style="height: 350px"></div>
        </el-card>
      </el-col>

      <!-- 饼图 -->
      <el-col :xs="24" :sm="24" :lg="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>商品类型销售占比</span>
            </div>
          </template>
          <div ref="pieChartRef" style="height: 350px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近订单列表 -->
    <el-row :gutter="20" class="list-container">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最新发货动态</span>
            </div>
          </template>
          <el-table :data="dashboardData.latestShipments" style="width: 100%" stripe border>
            <el-table-column prop="orderNo" label="订单编号" width="180" />
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column label="订单金额" width="120">
              <template #default="scope">
                {{ formatCurrency(scope.row.amount) }}
              </template>
            </el-table-column>
            <el-table-column prop="customer" label="收货人" width="120" />
            <el-table-column prop="status" label="订单状态" width="100">
              <template #default="scope">
                <dict-tag :options="order_status" :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column prop="date" label="时间" width="160" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts" name="Index">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { ShoppingCart, Money, Van, Goods } from '@element-plus/icons-vue';
import { partnerInfoIndexData } from '@/api/partner/merchant';
import type { PartnerInfoIndexVO } from '@/api/partner/merchant/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_status } = toRefs<any>(proxy?.useDict('order_status'));
import * as echarts from 'echarts';

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

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

const dashboardData = ref<PartnerInfoIndexVO>({
  todayOrders: 0,
  weekRevenue: 0,
  pendingShipment: 0,
  onSaleProducts: 0,
  shipmentTrend: [],
  productTypeSales: [],
  latestShipments: []
});

const formatCurrency = (val: number) => '￥ ' + val.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

const fetchData = async () => {
  const { data } = await partnerInfoIndexData();
  dashboardData.value = data;
};

// 初始化折线图
const initLineChart = () => {
  if (!lineChartRef.value) return;
  lineChart = echarts.init(lineChartRef.value);
  const trend = dashboardData.value.shipmentTrend;
  const option = {
    tooltip: { trigger: 'axis' },
    legend: { data: ['发货量'] },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: trend.map((item) => item.date)
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '发货量',
        type: 'line',
        itemStyle: { color: '#67C23A' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(103,194,58,0.3)' },
            { offset: 1, color: 'rgba(103,194,58,0)' }
          ])
        },
        data: trend.map((item) => item.count)
      }
    ]
  };
  lineChart.setOption(option);
};

// 初始化饼图
const initPieChart = () => {
  if (!pieChartRef.value) return;
  pieChart = echarts.init(pieChartRef.value);
  const sales = dashboardData.value.productTypeSales;
  const option = {
    tooltip: { trigger: 'item' },
    legend: { top: 'bottom' },
    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: sales,
        color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
      }
    ]
  };
  pieChart.setOption(option);
};

// 监听窗口大小变化以重绘图表
const handleResize = () => {
  lineChart?.resize();
  pieChart?.resize();
};

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

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

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

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

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

  .card-panel {
    height: 108px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    border-radius: 8px;
    display: flex;
    align-items: center;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);

      .card-panel-icon-wrapper {
        color: #fff;
      }
      .icon-blue {
        background: #409eff;
      }
      .icon-green {
        background: #67c23a;
      }
      .icon-orange {
        background: #e6a23c;
      }
      .icon-purple {
        background: #b050e6;
      }
    }

    .card-panel-icon-wrapper {
      margin: 14px 0 0 14px;
      padding: 16px;
      transition: all 0.3s ease-out;
      border-radius: 6px;
      font-size: 48px;
    }

    .icon-blue {
      color: #409eff;
    }
    .icon-green {
      color: #67c23a;
    }
    .icon-orange {
      color: #e6a23c;
    }
    .icon-purple {
      color: #b050e6;
    }

    .card-panel-description {
      margin-left: auto;
      margin-right: 20px;
      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;
      }
    }
  }
}

.chart-container {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-container {
  margin-bottom: 20px;
}
</style>
