<template>
  <div class="app-container dashboard-wrapper">
    <!-- Header / Welcome Section -->
    <el-card class="welcome-card" shadow="hover">
      <div class="welcome-content">
        <div class="welcome-text">
          <h2 class="greeting">欢迎回来，商户管理员！👋</h2>
          <p class="subtitle">这里是您的综合业务数据概览，实时获取最新的运营数据。</p>
        </div>
        <div class="welcome-image">
          <el-icon class="welcome-icon"><DataBoard /></el-icon>
        </div>
      </div>
    </el-card>

    <!-- Data Summary Cards -->
    <el-row :gutter="20" class="stat-cards" v-loading="loadingStats">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" :body-style="{ padding: '30px' }" class="stat-card">
          <div class="stat-header">
            <span class="stat-title">测评管理总发布数量</span>
            <el-tag type="success" effect="light" size="small">总数</el-tag>
          </div>
          <div class="stat-body">
            <span class="stat-value">{{ evaluationTotalCount }}</span>
            <el-icon class="stat-icon" style="color: #67c23a"><Document /></el-icon>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" :body-style="{ padding: '30px' }" class="stat-card">
          <div class="stat-header">
            <span class="stat-title">部门数量</span>
            <el-tag type="warning" effect="light" size="small">部门</el-tag>
          </div>
          <div class="stat-body">
            <span class="stat-value">{{ deptCount }}</span>
            <el-icon class="stat-icon" style="color: #e6a23c"><OfficeBuilding /></el-icon>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" :body-style="{ padding: '30px' }" class="stat-card">
          <div class="stat-header">
            <span class="stat-title">昨日加入公司人数</span>
            <el-tag type="danger" effect="light" size="small">昨日</el-tag>
          </div>
          <div class="stat-body">
            <span class="stat-value">{{ userYesterdayCount }}</span>
            <el-icon class="stat-icon" style="color: #f56c6c"><UserFilled /></el-icon>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" :body-style="{ padding: '30px' }" class="stat-card">
          <div class="stat-header">
            <span class="stat-title">公司人员总数</span>
            <el-tag type="primary" effect="light" size="small">总共</el-tag>
          </div>
          <div class="stat-body">
            <span class="stat-value">{{ companyUserCount }}</span>
            <el-icon class="stat-icon" style="color: #409eff"><User /></el-icon>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Charts Section -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :lg="24">
        <el-card shadow="hover" class="chart-card" v-loading="loadingChart">
          <template #header>
            <div class="card-header">
              <span>岗位管理 - 近日发布数量报表</span>
            </div>
          </template>
          <div ref="lineChartRef" class="echart-container" style="height: 400px;"></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 { getPostRecentStats, getEvaluationTotalStats, getCompanyStats, getDeptStats, getUserYesterdayStats, TrendData } from '@/api/main/dashboard/index';

// 反应式状态
const loadingStats = ref(true);
const loadingChart = ref(true);
const evaluationTotalCount = ref<number>(0);
const deptCount = ref<number>(0);
const userYesterdayCount = ref<number>(0);
const companyUserCount = ref<number>(0);

// 图表 Ref 与实例
const lineChartRef = ref<HTMLElement | null>(null);
let lineChart: echarts.ECharts | null = null;

// 加载头部卡片统计数据
const loadSummaryStats = async () => {
  loadingStats.value = true;
  try {
    const [evalRes, deptRes, userYestRes, companyRes] = await Promise.all([
      getEvaluationTotalStats(),
      getDeptStats(),
      getUserYesterdayStats(),
      getCompanyStats()
    ]);
    
    // axios request wrapper in RuoYi usually returns { code: 200, data: ... }
    // @ts-ignore
    evaluationTotalCount.value = evalRes.data || 0;
    // @ts-ignore
    deptCount.value = deptRes.data || 0;
    // @ts-ignore
    userYesterdayCount.value = userYestRes.data || 0;
    // @ts-ignore
    companyUserCount.value = companyRes.data || 0;
  } catch (error) {
    console.error("Failed to load summary stats:", error);
  } finally {
    loadingStats.value = false;
  }
};

// 加载并渲染岗位近日发布趋势报表
const loadPostRecentChart = async () => {
  loadingChart.value = true;
  try {
    const res = await getPostRecentStats();
    // @ts-ignore
    const trendData: TrendData[] = res.data || [];
    
    const dates = trendData.map(item => item.date);
    const counts = trendData.map(item => item.count);

    renderLineChart(dates, counts);
  } catch (error) {
    console.error("Failed to load post recent stats:", error);
  } finally {
    loadingChart.value = false;
  }
};

// 初始化并渲染 ECharts 折线图
const renderLineChart = (xAxisData: string[], seriesData: number[]) => {
  if (!lineChartRef.value) return;
  
  if (!lineChart) {
    lineChart = echarts.init(lineChartRef.value);
  }

  const option = {
    tooltip: { trigger: 'axis' },
    legend: { data: ['岗位发布数量'], bottom: 0 },
    grid: { left: '3%', right: '4%', bottom: '10%', containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData
    },
    yAxis: { 
      type: 'value',
      minInterval: 1 // 强制 Y 轴只显示整数刻度
    },
    series: [
      {
        name: '岗位发布数量',
        type: 'line',
        smooth: true,
        data: seriesData,
        itemStyle: { color: '#409eff' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64,158,255,0.4)' },
            { offset: 1, color: 'rgba(64,158,255,0.05)' }
          ])
        }
      }
    ]
  };
  
  lineChart.setOption(option);
};

const handleResize = () => {
  lineChart?.resize();
};

onMounted(() => {
  nextTick(() => {
    loadSummaryStats();
    loadPostRecentChart();
    window.addEventListener('resize', handleResize);
  });
});

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

<style lang="scss" scoped>
.dashboard-wrapper {
  padding: 20px;
  background-color: #f2f3f5;
  min-height: calc(100vh - 84px);
  
  .welcome-card {
    margin-bottom: 20px;
    border-radius: 12px;
    background: linear-gradient(135deg, #74ebd5 0%, #9face6 100%);
    color: #fff;
    border: none;
    
    .welcome-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px 20px;
      
      .welcome-text {
        .greeting {
          margin: 0 0 10px 0;
          font-size: 24px;
          font-weight: 600;
          color: #fff;
        }
        .subtitle {
          margin: 0;
          font-size: 14px;
          color: rgba(255, 255, 255, 0.9);
        }
      }
      
      .welcome-icon {
        font-size: 80px;
        color: rgba(255, 255, 255, 0.25);
        transform: rotate(-10deg);
      }
    }
  }

  .stat-cards {
    margin-bottom: 20px;
    
    .stat-card {
      border-radius: 12px;
      margin-bottom: 20px;
      transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 12px 24px rgba(0,0,0,0.08);
      }
      
      .stat-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        
        .stat-title {
          font-size: 16px;
          color: #606266;
          font-weight: bold;
        }
      }
      
      .stat-body {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .stat-value {
          font-size: 42px;
          font-weight: bold;
          color: #303133;
          font-family: Arial, Helvetica, sans-serif;
        }
        
        .stat-icon {
          font-size: 48px;
          padding: 12px;
          background-color: rgba(0,0,0,0.03);
          border-radius: 50%;
        }
      }
    }
  }

  .charts-row {
    margin-bottom: 20px;
  }

  .chart-card {
    border-radius: 12px;
    margin-bottom: 20px;
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 8px 24px rgba(0,0,0,0.05);
    }
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: bold;
      color: #303133;
      font-size: 16px;
      
      &::before {
        content: '';
        display: inline-block;
        width: 4px;
        height: 16px;
        background-color: #409eff;
        margin-right: 10px;
        border-radius: 2px;
      }
    }
  }
}
</style>
