<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">
        <el-card shadow="hover" class="box-card">
          <div class="card-header">
            <span class="card-title">今日订单(笔)</span>
            <el-tag type="primary">日</el-tag>
          </div>
          <div class="card-value">{{ indexData.todayOrders.toLocaleString() }}</div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <el-card shadow="hover" class="box-card">
          <div class="card-header">
            <span class="card-title">待发货订单(笔)</span>
            <el-tag type="warning">待办</el-tag>
          </div>
          <div class="card-value">{{ indexData.pendingDeliveryOrders.toLocaleString() }}</div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <el-card shadow="hover" class="box-card">
          <div class="card-header">
            <span class="card-title">本月成交额(元)</span>
            <el-tag type="success">月</el-tag>
          </div>
          <div class="card-value">￥{{ indexData.monthlyRevenue.toLocaleString() }}</div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <el-card shadow="hover" class="box-card">
          <div class="card-header">
            <span class="card-title">售后退款订单(笔)</span>
            <el-tag type="danger">售后</el-tag>
          </div>
          <div class="card-value">{{ indexData.afterSaleOrders.toLocaleString() }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 中部图表区域 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="16">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header-flex">
              <span class="title">近七日订单趋势</span>
            </div>
          </template>
          <!-- 柱状图 -->
          <div ref="chartRef" style="height: 350px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header-flex">
              <span class="title">平台订单占比</span>
            </div>
          </template>
          <!-- 饼图 -->
          <div ref="pieRef" style="height: 350px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部最新订单列表 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="24">
        <el-card shadow="hover" class="table-card">
          <template #header>
            <div class="card-header-flex">
              <span class="title">最新订单动态</span>
              <el-button link type="primary" @click="viewAllOrders">查看全部</el-button>
            </div>
          </template>
          <el-table :data="indexData.latestOrders" style="width: 100%" max-height="400">
            <el-table-column prop="orderNo" label="订单编号" />
            <el-table-column prop="customerName" label="客户名称" />
            <el-table-column prop="orderSource" label="订单来源">
              <template #default="scope">
                <dict-tag :options="order_source" :value="scope.row.orderSource" />
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="订单金额(元)">
              <template #default="scope">
                {{ scope.row.amount?.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="订单状态">
              <template #default="scope">
                <dict-tag :options="order_status" :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间"> </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Index" lang="ts">
import { ref, onMounted, onUnmounted, nextTick, getCurrentInstance, toRefs } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import { orderIndexData } from '@/api/order/orderMain';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import { CaretTop, CaretBottom } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_status, order_source } = toRefs<any>(proxy?.useDict('order_status', 'order_source'));

const router = useRouter();

// 图表 refs
const chartRef = ref<HTMLElement | null>(null);
const pieRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;
let pieInstance: echarts.ECharts | null = null;

// 首页数据
const indexData = ref({
  todayOrders: 0,
  pendingDeliveryOrders: 0,
  monthlyRevenue: 0,
  afterSaleOrders: 0,
  weeklyTrend: [] as { date: string; count: number }[],
  platformProportion: [] as { name: string; value: number }[],
  latestOrders: [] as any[]
});

const getIndexData = async () => {
  const res = await orderIndexData();
  if (res.code === 200) {
    indexData.value = res.data;
  }
};

// 跳转订单列表
const viewAllOrders = () => {
  router.push('/order-center/order-list');
};

// 初始化柱状图
const initBarChart = () => {
  if (!chartRef.value) return;
  chartInstance = echarts.init(chartRef.value);
  const { weeklyTrend } = indexData.value;
  chartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: weeklyTrend.map((item) => item.date),
        axisTick: { alignWithLabel: true },
        axisLine: { lineStyle: { color: '#909399' } }
      }
    ],
    yAxis: [
      {
        type: 'value',
        splitLine: { lineStyle: { type: 'dashed' } }
      }
    ],
    series: [
      {
        name: '新增订单数',
        type: 'bar',
        barWidth: '40%',
        data: weeklyTrend.map((item) => item.count),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ]),
          borderRadius: [4, 4, 0, 0]
        }
      }
    ]
  });
};

// 初始化饼图
const initPieChart = () => {
  if (!pieRef.value) return;
  pieInstance = echarts.init(pieRef.value);
  const { platformProportion } = indexData.value;
  const colors = ['#f56c6c', '#e6a23c', '#409eff', '#67c23a', '#909399'];
  pieInstance.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}笔 ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 'bottom'
    },
    series: [
      {
        name: '订单来源平台',
        type: 'pie',
        radius: ['45%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold',
            formatter: '{b}\n{d}%'
          }
        },
        labelLine: {
          show: false
        },
        data: platformProportion.map((item, index) => ({
          value: item.value,
          name: item.name,
          itemStyle: { color: colors[index % colors.length] }
        }))
      }
    ]
  });
};

// 自适应图表大小
const resizeCharts = () => {
  chartInstance?.resize();
  pieInstance?.resize();
};

onMounted(async () => {
  await getIndexData();
  nextTick(() => {
    initBarChart();
    initPieChart();
    window.addEventListener('resize', resizeCharts);
  });
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeCharts);
  chartInstance?.dispose();
  pieInstance?.dispose();
});
</script>

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

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

.box-card {
  border-radius: 8px;
  border: none;
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #909399;
    font-size: 14px;
    margin-bottom: 12px;
    .card-title {
      font-weight: 500;
    }
  }
  .card-value {
    font-size: 28px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 15px;
  }
  .card-footer {
    border-top: 1px solid #ebeef5;
    padding-top: 12px;
    font-size: 13px;
    color: #606266;
    display: flex;
    align-items: center;

    .trend {
      display: flex;
      align-items: center;
      gap: 5px;

      .up {
        color: #f56c6c;
        display: inline-flex;
        align-items: center;
      }
      .down {
        color: #67c23a;
        display: inline-flex;
        align-items: center;
      }
    }
  }
}

.chart-card {
  border-radius: 8px;
  border: none;
  .card-header-flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.table-card {
  border-radius: 8px;
  border: none;
  .card-header-flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
}

// 覆盖 Element Plus 默认的卡片头部 padding
:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}
</style>
