<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 今日新增订单 -->
      <el-col :span="6">
        <div class="data-card bg-blue">
          <div class="card-title">今日新增订单</div>
          <div class="card-value">
            <span class="num">{{ countData.orderCountToday || 0 }}</span>
            <span class="unit">单</span>
          </div>
          <div class="card-footer">
            <div class="footer-left">较昨日</div>
            <div class="footer-right">-</div>
          </div>
        </div>
      </el-col>
      
      <!-- 今日订单支出 -->
      <el-col :span="6">
        <div class="data-card bg-orange">
          <div class="card-title">今日订单支出</div>
          <div class="card-value">
            <span style="font-size: 14px; margin-right: 2px;">¥</span>
            <span class="num">{{ formatMoney(countData.costToday) }}</span>
          </div>
          <div class="card-footer">
            <div class="footer-left">较昨日</div>
            <div class="footer-right">
              <span v-if="costRate > 0">↑ {{ costRate }}%</span>
              <span v-else-if="costRate < 0">↓ {{ Math.abs(costRate) }}%</span>
              <span v-else>-</span>
            </div>
          </div>
        </div>
      </el-col>
      
      <!-- 本月累计完成 -->
      <el-col :span="6">
        <div class="data-card bg-green">
          <div class="card-title">本月累计完成</div>
          <div class="card-value">
            <span class="num">{{ countData.orderCompletedThisMonth || 0 }}</span>
            <span class="unit">单</span>
          </div>
          <div class="card-footer linkable" @click="goTo('/order/management')">
            <div class="footer-left">查看订单明细</div>
          </div>
        </div>
      </el-col>
      
      <!-- 待派单 -->
      <el-col :span="6">
        <div class="data-card bg-purple">
          <div class="card-title">待派单</div>
          <div class="card-value">
            <span class="num">{{ countData.pendingDispatchCount || 0 }}</span>
            <span class="unit">项</span>
          </div>
          <div class="card-footer linkable" @click="goTo('/order/management')">
            <div class="footer-left">前往处理</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="mt-4">
      <!-- 趋势分析 -->
      <el-col :span="16">
        <el-card shadow="never" class="dashboard-card">
          <template #header>
            <div class="card-title-header">
              <span class="indicator-bar"></span>
              <span>近7日订单趋势分析</span>
            </div>
          </template>
          <div ref="lineChartRef" style="height: 320px; width: 100%;"></div>
        </el-card>
      </el-col>

      <!-- 订单类型占比 -->
      <el-col :span="8">
        <el-card shadow="never" class="dashboard-card">
          <template #header>
            <div class="card-title-header">
              <span class="indicator-bar"></span>
              <span>服务订单占比</span>
            </div>
          </template>
          <div ref="pieChartRef" style="height: 320px; width: 100%;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单动态 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :span="24">
        <el-card shadow="never" class="dashboard-card no-padding-body">
          <template #header>
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <div class="card-title-header">
                <span class="indicator-bar"></span>
                <span>今日关注订单动态</span>
                <el-tag size="small" type="info" style="margin-left: 10px;" effect="plain">全部门店</el-tag>
              </div>
              <el-button link type="primary" @click="goTo('/order/management')" style="font-size: 13px;">查看全部订单</el-button>
            </div>
          </template>
          <el-table :data="tableOrders" style="width: 100%" :header-cell-style="{ background: '#f8f9fb', color: '#606266' }">
            <el-table-column prop="code" label="订单号" min-width="180" />
            <el-table-column prop="service" label="服务项目" min-width="120">
              <template #default="scope">
                <el-tag :color="getServiceColor(scope.row.service, true)" 
                        :style="{ color: getServiceColor(scope.row.service), borderColor: getServiceColor(scope.row.service, true) }" 
                        size="small">
                  {{ getServiceName(scope.row.service) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="服务宠物" min-width="120">
              <template #default> 
                <!-- API无宠物数据时默认显示暂无 -->
                <span style="color: #909399;">暂无数据</span>
              </template>
            </el-table-column>
            <el-table-column prop="serviceTime" label="今日预约时间" min-width="150" />
            <el-table-column prop="status" label="订单状态" min-width="120">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)" effect="dark" size="small">{{ getStatusLabel(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import { getMerchantIndexCount, listMerchantOrder } from '@/api/system/merchant';
import { MerchantIndexCountVO } from '@/api/system/merchant/types';
import { listAllService } from '@/api/service/list';

const router = useRouter();

const countData = ref<MerchantIndexCountVO>({
  orderCountToday: 0,
  costToday: 0,
  costLastday: 0,
  orderCompletedThisMonth: 0,
  pendingDispatchCount: 0
});

const serviceList = ref<any[]>([]);
const orderList = ref<any[]>([]);

const lineChartRef = ref();
const pieChartRef = ref();
let lineChart: echarts.ECharts | null = null;
let pieChart: echarts.ECharts | null = null;

const tableOrders = computed(() => {
  return orderList.value.slice(0, 5); // 仅显示今天最新的几条关注动态
});

const getCount = async () => {
  try {
    const res: any = await getMerchantIndexCount();
    if (res.code === 200 && res.data) {
      countData.value = Object.assign(countData.value, res.data);
    }
  } catch (error) {
    console.error('获取统计数据失败', error);
  }
};

const getOrders = async () => {
  try {
    const res: any = await listMerchantOrder();
    if (res.code === 200 && res.data) {
      orderList.value = res.data || [];
      initCharts();
    }
  } catch (error) {
    console.error('获取订单列表失败', error);
  }
};

const getServices = async () => {
  try {
    const res: any = await listAllService();
    serviceList.value = res.data || res || [];
  } catch (error) {
    console.error('获取服务项失败', error);
  }
};

const getServiceName = (id: number) => {
  const s = serviceList.value.find(item => String(item.id) === String(id));
  return s ? s.name : '未知服务';
};

// 构造服务标签伪随机色彩
const COLORS = ['#409eff', '#e6a23c', '#67c23a', '#f56c6c', '#9c27b0', '#19d4ae'];
const OPACITY_COLORS = ['#ecf5ff', '#fdf6ec', '#f0f9eb', '#fef0f0', '#f9ebfb', '#e5fbf7'];

const getServiceColor = (id: number, isBg = false) => {
  const index = Number(id || 0) % COLORS.length;
  return isBg ? OPACITY_COLORS[index] : COLORS[index];
};

const getStatusLabel = (status: number) => {
  const map: any = { 0: '待派单', 1: '待接单', 2: '待服务', 3: '服务中', 4: '已完成', 5: '已取消' };
  return map[status] || '未知状态';
};

const getStatusType = (status: number) => {
  const map: any = { 0: 'danger', 1: 'warning', 2: 'primary', 3: 'warning', 4: 'success', 5: 'info' };
  return map[status] || 'info';
};

const formatMoney = (val: number) => {
  if (!val) return '0';
  return (val / 100).toString();
};

const costRate = computed(() => {
  const today = countData.value.costToday || 0;
  const lastday = countData.value.costLastday || 0;
  if (lastday === 0) {
    return today > 0 ? 100 : 0;
  }
  return Number((((today - lastday) / lastday) * 100).toFixed(1));
});

const goTo = (path: string) => {
  router.push(path);
};

// 生成过去7天的日期数组, 例如 "03-14"
const getLast7Days = () => {
  const dates = [];
  for (let i = 6; i >= 0; i--) {
    const d = new Date();
    d.setDate(d.getDate() - i);
    const m = (d.getMonth() + 1).toString().padStart(2, '0');
    const day = d.getDate().toString().padStart(2, '0');
    dates.push(`${m}-${day}`);
  }
  return dates;
};

const initCharts = () => {
  if (!lineChartRef.value || !pieChartRef.value) return;

  // ==== 1. 趋势分析折线图 ====
  const dates = getLast7Days();
  const newOrderCounts = new Array(7).fill(0);
  const completedOrderCounts = new Array(7).fill(0);

  // 根据返回的 orderList 聚合数据
  orderList.value.forEach(order => {
    if (order.createTime) {
      // 提取 MM-DD
      let dateMatch = order.createTime.match(/\d{4}-(\d{2}-\d{2})/);
      if (!dateMatch) return;
      let md = dateMatch[1];
      const index = dates.indexOf(md);
      if (index !== -1) {
        newOrderCounts[index]++;
        if (order.status === 4) {
          completedOrderCounts[index]++;
        }
      }
    }
  });

  lineChart = echarts.init(lineChartRef.value);
  lineChart.setOption({
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      padding: [10, 15],
      textStyle: { color: '#333' },
      axisPointer: { type: 'line', lineStyle: { color: '#ddd' } },
      extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'
    },
    legend: {
      data: ['新增订单', '完成订单'],
      top: '0',
      icon: 'emptyCircle'
    },
    grid: { left: '3%', right: '4%', bottom: '5%', containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLine: { lineStyle: { color: '#E4E7ED' } },
      axisLabel: { color: '#909399' }
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { lineStyle: { type: 'dashed', color: '#ebeef5' } },
      axisLabel: { color: '#909399' }
    },
    series: [
      {
        name: '新增订单',
        type: 'line',
        smooth: true,
        symbolSize: 8,
        itemStyle: { color: '#409EFF', borderWidth: 2, borderColor: '#fff' },
        lineStyle: { color: '#409EFF', width: 3 },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64,158,255,0.2)' },
            { offset: 1, color: 'rgba(64,158,255,0)' }
          ])
        },
        data: newOrderCounts
      },
      {
        name: '完成订单',
        type: 'line',
        smooth: true,
        symbolSize: 8,
        itemStyle: { color: '#67C23A', borderWidth: 2, borderColor: '#fff' },
        lineStyle: { color: '#67C23A', width: 3 },
        data: completedOrderCounts
      }
    ]
  });

  // ==== 2. 服务订单占比饼图 ====
  // 聚合分类数据
  const serviceCounts: Record<string, number> = {};
  let totalOrder = orderList.value.length || 1; // 防止/0
  
  orderList.value.forEach(order => {
    let sName = getServiceName(order.service);
    if (!serviceCounts[sName]) serviceCounts[sName] = 0;
    serviceCounts[sName]++;
  });

  const pieData = Object.keys(serviceCounts).map(name => {
    return { name: name, value: serviceCounts[name] };
  });
  
  // 处理空数据展示
  if(pieData.length === 0) pieData.push({name: '暂无数据', value: 0});

  pieChart = echarts.init(pieChartRef.value);
  pieChart.setOption({
    title: {
      text: 'Total\n100%',
      left: '34%',
      top: 'center',
      textAlign: 'center',
      textStyle: {
        fontSize: 13,
        fontWeight: 'bold',
        color: '#303133',
        lineHeight: 18
      }
    },
    tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'center',
      itemWidth: 10,
      itemHeight: 10,
      textStyle: { color: '#606266' },
      formatter: (name: string) => {
        const item = pieData.find(i => i.name === name);
        const val = item ? item.value : 0;
        const percent = ((val / totalOrder) * 100).toFixed(0);
        return `${name}  ${percent}%`;
      }
    },
    color: ['#409EFF', '#E6A23C', '#67C23A', '#F56C6C', '#9C27B0'],
    series: [
      {
        name: '服务占比',
        type: 'pie',
        radius: ['50%', '75%'],
        center: ['35%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 4,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: { show: false, position: 'center' },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold',
            formatter: '{b}\n{c}'
          }
        },
        labelLine: { show: false },
        data: pieData
      }
    ]
  });
};

const resizeCharts = () => {
  if (lineChart) lineChart.resize();
  if (pieChart) pieChart.resize();
};

onMounted(async () => {
  await getServices(); // 先拉取字典，这样聚合时才有正确名字
  getCount();
  getOrders(); // 拉取完进行图表渲染
  window.addEventListener('resize', resizeCharts);
});

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

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

.mt-4 { margin-top: 20px; }

.data-card {
  border-radius: 8px;
  padding: 20px;
  color: #fff;
  height: 140px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
  
  &:hover {
    transform: translateY(-5px);
  }

  &.bg-blue { background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%); }
  &.bg-orange { background: linear-gradient(135deg, #E6A23C 0%, #f3d19e 100%); }
  &.bg-green { background: linear-gradient(135deg, #67C23A 0%, #85ce61 100%); }
  &.bg-purple { background: linear-gradient(135deg, #9C27B0 0%, #b05da6 100%); }

  .card-title { font-size: 14px; font-weight: 500; opacity: 0.9; }

  .card-value {
    margin-top: 10px;
    margin-bottom: 20px;
    display: flex;
    align-items: baseline;
    
    .num { font-size: 36px; font-weight: bold; line-height: 1; margin-right: 2px;}
    .unit { font-size: 14px; margin-left: 2px; opacity: 0.8; }
  }

  .card-footer {
    border-top: 1px solid rgba(255, 255, 255, 0.2);
    padding-top: 10px;
    display: flex;
    justify-content: space-between;
    font-size: 13px;
    opacity: 0.85;

    &.linkable {
      cursor: pointer;
      display: flex;
      &:hover { opacity: 1; }
    }
  }
}

.dashboard-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 1px 4px rgba(0,21,41,.04);

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

.card-title-header {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;

  .indicator-bar {
    display: inline-block;
    width: 4px;
    height: 16px;
    background-color: #409EFF;
    border-radius: 2px;
    margin-right: 10px;
  }
}

.no-padding-body {
  :deep(.el-card__body) {
    padding: 0;
  }

  :deep(.el-table__inner-wrapper::before) {
    display: none;
  }
  
  :deep(.el-table th.el-table__cell) {
    background-color: #f8f9fb;
    padding: 12px 20px;
    font-weight: 600;
    color: #606266;
  }

  :deep(.el-table td.el-table__cell) {
    padding: 16px 20px;
  }
}
</style>
