<template>
  <div class="app-container master-data-dashboard">
    <el-row :gutter="20" class="mb-20">
      <el-col :span="24">
        <div class="welcome-header">
          <h2>总控平台控制台</h2>
        </div>
      </el-col>
    </el-row>

    <!-- Metrics Cards -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :lg="6" v-for="metric in metrics" :key="metric.title" class="mb-20">
        <el-card shadow="hover" class="metric-card" :body-style="{ padding: '20px', display: 'flex', alignItems: 'center' }">
          <div class="metric-icon" :style="{ color: metric.color, backgroundColor: metric.bgColor }">
            <el-icon><Component :is="metric.icon" /></el-icon>
          </div>
          <div class="metric-info">
            <div class="metric-title">{{ metric.title }}</div>
            <div class="metric-value">{{ metric.value }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Quick Links & Charts -->
    <el-row :gutter="20">
      <!-- Quick Links -->
      <el-col :xs="24" :sm="24" :lg="8" class="mb-20">
        <el-card shadow="hover" class="quick-links-card" style="height: 400px">
          <template #header>
            <div class="card-header">
              <span>常用配置入口</span>
            </div>
          </template>
          <div class="quick-links-grid">
            <div class="quick-link-item" v-for="link in quickLinks" :key="link.name">
              <div class="link-icon">
                <el-icon><Component :is="link.icon" /></el-icon>
              </div>
              <div class="link-name">{{ link.name }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- Distribution Chart -->
      <el-col :xs="24" :sm="12" :lg="8" class="mb-20">
        <el-card shadow="hover" style="height: 400px">
          <template #header>
            <div class="card-header">
              <span>系统对象分布</span>
            </div>
          </template>
          <div ref="pieChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>

      <!-- Activity Chart -->
      <el-col :xs="24" :sm="12" :lg="8" class="mb-20">
        <el-card shadow="hover" style="height: 400px">
          <template #header>
            <div class="card-header">
              <span>近期参数变更趋势 (次)</span>
            </div>
          </template>
          <div ref="barChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Recent Logs -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最新参数变更记录</span>
            </div>
          </template>
          <el-table :data="recentLogs" style="width: 100%" stripe>
            <el-table-column prop="module" label="配置模块" width="180">
              <template #default="scope">
                <el-tag size="small">{{ scope.row.module }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="action" label="操作类型" width="120">
              <template #default="scope">
                <el-tag :type="scope.row.action === '新增' ? 'success' : scope.row.action === '删除' ? 'danger' : 'warning'" size="small">
                  {{ scope.row.action }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="detail" label="变更详情" show-overflow-tooltip></el-table-column>
            <el-table-column prop="user" label="操作人" width="150"></el-table-column>
            <el-table-column prop="time" label="操作时间" width="180"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Index" lang="ts">
import { ref, onMounted, onUnmounted, nextTick, markRaw } from 'vue';
import * as echarts from 'echarts';
import { OfficeBuilding, House, User, Setting, Money, Wallet, List, Van, Collection } from '@element-plus/icons-vue';

// Generate dynamic times for logs
function getCurrentTime(hoursOffset = 0) {
  const date = new Date(Date.now() + hoursOffset * 60 * 60 * 1000);
  const pad = (n: number) => n.toString().padStart(2, '0');
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}

const metrics = ref([
  { title: '接入公司总数', value: '18', icon: markRaw(OfficeBuilding), color: '#409EFF', bgColor: '#ecf5ff' },
  { title: '已归档客户资料', value: '2,654', icon: markRaw(User), color: '#67C23A', bgColor: '#f0f9eb' },
  { title: '合作供应商', value: '312', icon: markRaw(Van), color: '#E6A23C', bgColor: '#fdf6ec' },
  { title: '全局配置参数项', value: '143', icon: markRaw(Setting), color: '#F56C6C', bgColor: '#fef0f0' }
]);

const quickLinks = ref([
  { name: '公司信息', icon: markRaw(OfficeBuilding) },
  { name: '人员设定', icon: markRaw(User) },
  { name: '区域设置', icon: markRaw(House) },
  { name: '产品税率', icon: markRaw(Money) },
  { name: '交易币别', icon: markRaw(Wallet) },
  { name: '物流公司', icon: markRaw(Van) },
  { name: '仓库信息', icon: markRaw(Collection) },
  { name: '收入费用', icon: markRaw(List) },
  { name: '全局参数', icon: markRaw(Setting) }
]);

const pieChartRef = ref();
const barChartRef = ref();
let pieChartInstance: echarts.ECharts | null = null;
let barChartInstance: echarts.ECharts | null = null;

const initCharts = () => {
  if (pieChartRef.value) {
    pieChartInstance = echarts.init(pieChartRef.value);
    pieChartInstance.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{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: 1048, name: '客户主数据' },
            { value: 735, name: '商品主数据' },
            { value: 580, name: '供应商基础数据' },
            { value: 484, name: '组织架构数据' },
            { value: 300, name: '系统公共参数' }
          ]
        }
      ]
    });
  }

  if (barChartRef.value) {
    barChartInstance = echarts.init(barChartRef.value);
    barChartInstance.setOption({
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: [{ type: 'category', data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'], axisTick: { alignWithLabel: true } }],
      yAxis: [{ type: 'value' }],
      series: [
        {
          name: '变更项次',
          type: 'bar',
          barWidth: '60%',
          data: [12, 45, 130, 89, 210, 48, 23],
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          }
        }
      ]
    });
  }
};

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

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

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  pieChartInstance?.dispose();
  barChartInstance?.dispose();
});

const recentLogs = ref([
  { module: '产品税率配置', action: '修改', detail: '将增值税率从 13% 调整为 11%', user: 'admin', time: getCurrentTime(-1) },
  { module: '区域设置', action: '新增', detail: '新增销售大区：华南西南区', user: '张三', time: getCurrentTime(-5) },
  { module: '公司信息', action: '修改', detail: '更新公司注册地址和统一社会信用代码', user: '李四', time: getCurrentTime(-24) },
  { module: '交易币别', action: '新增', detail: '新增支持交易币别：欧元 (EUR)', user: 'admin', time: getCurrentTime(-48) },
  { module: '物流公司', action: '删除', detail: '移除已解约的物流服务商', user: '王五', time: getCurrentTime(-72) }
]);
</script>

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

.welcome-header {
  background: white;
  padding: 24px 30px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  h2 {
    margin: 0 0 10px 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
  }
  p {
    margin: 0;
    color: #909399;
    font-size: 14px;
  }
}

.mb-20 {
  margin-bottom: 20px;
}

.metric-card {
  border: none;
  border-radius: 8px;
  .metric-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 30px;
    margin-right: 16px;
  }
  .metric-info {
    flex: 1;
  }
  .metric-title {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
  }
  .metric-value {
    font-size: 26px;
    font-weight: bold;
    color: #303133;
  }
}

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

.quick-links-card {
  border: none;
  border-radius: 8px;
  .quick-links-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
  }
  .quick-link-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 16px 10px;
    background-color: #f8f9fc;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background-color: #ecf5ff;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);

      .link-icon,
      .link-name {
        color: #409eff;
      }
    }

    .link-icon {
      font-size: 26px;
      color: #606266;
      margin-bottom: 12px;
      transition: color 0.3s ease;
    }

    .link-name {
      font-size: 13px;
      color: #606266;
      transition: color 0.3s ease;
      text-align: center;
    }
  }
}

.el-card {
  border: none;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08) !important;
}
</style>
