<template>
  <div class="dashboard">
    <div class="grid-container">
      <!-- 五大维修中心预算使用率 -->
      <div class="card">
        <h3 class="card-title">维修中心预算使用率</h3>
        <div class="progress-circles">
          <div v-for="(center, index) in maintenanceCenters" :key="index" class="progress-item">
            <div ref="progressCharts" class="progress-chart"></div>
            <span class="center-name">{{ center.name }}</span>
          </div>
        </div>
        <div class="stacked-bars">
          <div v-for="(monthData, index) in maintenanceCenters" :key="index" class="bar-group">
            <h2>{{ monthData.month }}</h2>
            <el-tooltip
              v-for="(value, i) in monthData.values"
              :key="i"
              :content="getTooltipContent(monthData, i)"
              placement="top"
              effect="light"
            >
              <div
                class="bar-segment"
                :style="{ height: `${value}%`, backgroundColor: barColors[i % barColors.length] }"
              >
                {{ value }}%
              </div>
            </el-tooltip>
          </div>
        </div>
      </div>

      <div class="card">
        <div class="card-header">
          <h3 class="card-title">仓库总览</h3>
          <div class="warehouse-toggle">
            <el-button type="text" class="toggle-button" @click="showButtons = !showButtons">
              <i :class="['el-icon-caret-right', { 'rotated': showButtons }]"></i>
            </el-button>
            <transition name="fade">
              <div class="button-group" v-show="showButtons">
                <el-button
                  size="small"
                  :type="currentWarehouse === 'primary' ? 'primary' : 'info'"
                  @click="changeWarehouse('primary')">一级库</el-button>
                <el-button
                  size="small"
                  :type="currentWarehouse === 'other' ? 'primary' : 'info'"
                  @click="changeWarehouse('other')">其他库</el-button>
                <el-button
                  size="small"
                  :type="currentWarehouse === 'global' ? 'primary' : 'info'"
                  @click="changeWarehouse('global')">全局</el-button>
              </div>
            </transition>
          </div>
        </div>
        <div class="overview-content">
          <div class="overview-stats">
            <div class="stat-group">
              <div class="stat-item">
                <span class="stat-label">货值总计</span>
                <span class="stat-value">{{ totalValue }}万元</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">仓库数量</span>
                <span class="stat-value">{{ warehouseCount }}</span>
              </div>
            </div>
            <div class="stat-group">
              <div class="stat-item">
                <span class="stat-label">本月累计入库金额</span>
                <span class="stat-value">{{ monthlyInbound }}万元</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">本月累计出库金额</span>
                <span class="stat-value">{{ monthlyOutbound }}万元</span>
              </div>
            </div>
          </div>
          <div class="budget-section">
            <div class="budget-info">
              <div class="budget-item">
                <span class="budget-label">本年预算</span>
                <span class="budget-value">{{ yearBudget }}万元</span>
              </div>
              <div class="budget-item">
                <span class="budget-label">已用预算</span>
                <span class="budget-value">{{ usedBudget }}万元</span>
              </div>
            </div>
            <div ref="budgetGauge" class="budget-gauge"></div>
          </div>
        </div>
      </div>

      <div class="card">
        <h3 class="card-title">全年存货总值(万元)</h3>
        <div ref="yearlyInventoryChart" class="chart"></div>
      </div>

      <!-- 五大维修中心本月采领金额 -->
      <div class="card">
        <h3 class="card-title">维修中心本月采领金额（万元）</h3>
        <div ref="monthlyPurchaseChart" class="chart"></div>
      </div>

      <div class="card">
        <h3 class="card-title">本月各仓出入库金额(万元)</h3>
        <div ref="monthlyInOutChart" class="chart"></div>
      </div>

      <!-- 仓库总览 -->
      <div class="card">
        <h3 class="card-title">库存趋势(万元)</h3>
        <div ref="inventoryTrendChart" class="chart"></div>
      </div>

      <div class="card">
        <h3 class="card-title">近6个月出库金额(万元)</h3>
        <div ref="sixMonthChart" class="chart"></div>
      </div>

      <div class="card">
        <h3 class="card-title">货值分布</h3>
        <div ref="valueDistributionChart" class="chart"></div>
      </div>

      <div class="card">
        <h3 class="card-title">各仓本月出库分布(万元)</h3>
        <div ref="outboundDistributionChart" class="chart"></div>
      </div>
    </div>

    <div v-if="loading" class="loading-overlay">
      <div class="loading-logo">
        <img src="@/assets/images/ldr_logo.png" alt="Loading">
      </div>
      <div class="loading-spinner"></div>
      <p class="loading-text">数据加载中</p>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import axios from 'axios';
import {listTotal} from "@/api/system/tMiStock";

export default {
  name: 'WarehouseDashboard',
  data() {
    return {
      tMiStockLists: [],
      tMiStockListss: [],
      totalMoney: '',
      maintenanceCenters: [
        // { month: '一月', values: [30, 40, 50, 60] },
        // { month: '二月', values: [35, 45, 55, 65] },
        // { month: '三月', values: [40, 50, 60, 70] },
        // 添加更多月份数据...
      ],
      barColors: [
        { start: '#667eea', end: '#764ba2' },  // 紫色渐变
        { start: '#f093fb', end: '#f5576c' },  // 粉红渐变
        { start: '#4facfe', end: '#00f2fe' },  // 蓝青渐变
        { start: '#43e97b', end: '#38f9d7' },  // 绿青渐变
        { start: '#fa709a', end: '#fee140' },  // 橙黄渐变
        { start: '#30cfd0', end: '#330867' },  // 深蓝渐变
        { start: '#a8edea', end: '#fed6e3' },  // 粉绿渐变
        { start: '#ff6b6b', end: '#feca57' },  // 红黄渐变
        { start: '#5f27cd', end: '#341f97' },  // 深紫渐变
        { start: '#48dbfb', end: '#0abde3' },  // 亮蓝渐变
        { start: '#1dd1a1', end: '#10ac84' },  // 绿色渐变
        { start: '#ee5a6f', end: '#c44569' }   // 玫瑰渐变
      ],
      centerNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],

      // maintenanceCenters: [],
      // barColors: ['#4B96FF', '#41D9D9', '#de8226', '#FFC442','#c5229f','#63CF7E'],
      totalValue: null,
      totalValues: null,
      warehouseCount: null,
      monthlyInbound: null,
      monthlyOutbound: null,
      yearBudget: null,
      usedBudget: null,
      tmi: [],
      tmiPie: [],
      charts: [],
      loading: true,
      dataLoaded: {
        maintenanceCenters: false,
        inventoryTrend: false,
        yearlyInventory: false,
        sixMonthChart: false,
        monthlyInOut: false,
        monthlyPurchase: false,
        outboundDistribution: false,
        overviewStats: false
      },
      currentWarehouse: 'primary', // 默认为一级库视图
      showButtons: false,
    }
  },
  watch: {
    dataLoaded: {
      handler(newVal) {
        if (Object.values(newVal).every(val => val)) {
          this.loading = false;
          this.$nextTick(() => {
            this.initAllCharts();
          });
        }
      },
      deep: true
    }
  },
  mounted() {
    this.fetchData();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.charts.forEach(chart => chart.dispose());
  },
  methods: {
    getTooltipContent(monthData, index) {
      return `${this.centerNames[index]}: ${monthData.values[index]}%`;
    },
    // 获取通用图表配置
    getCommonChartConfig() {
      return {
        animation: true,
        animationDuration: 1000,
        animationEasing: 'cubicOut',
        animationDelay: (idx) => idx * 100,
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(10, 22, 40, 0.95)',
          borderColor: 'rgba(75, 150, 255, 0.5)',
          borderWidth: 1,
          textStyle: {
            color: '#fff',
            fontSize: 14
          },
          padding: [12, 16],
          extraCssText: 'backdrop-filter: blur(10px); box-shadow: 0 4px 20px rgba(0,0,0,0.6); border-radius: 8px;'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          axisLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.2)',
              width: 1
            }
          },
          axisLabel: {
            color: 'rgba(255, 255, 255, 0.7)',
            fontSize: 12
          },
          splitLine: {
            show: false
          }
        },
        yAxis: {
          axisLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.2)',
              width: 1
            }
          },
          axisLabel: {
            color: 'rgba(255, 255, 255, 0.7)',
            fontSize: 12
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.08)',
              type: 'dashed'
            }
          }
        }
      };
    },
    // 获取渐变色
    getGradientColor(colorIndex) {
      const colors = this.barColors[colorIndex % this.barColors.length];
      return new echarts.graphic.LinearGradient(0, 1, 0, 0, [
        { offset: 0, color: colors.start },
        { offset: 1, color: colors.end }
      ]);
    },
    async fetchData() {
      this.loading = true;
      try {
        let apiPaths;

        // 根据仓库类型选择不同的API路径
        switch(this.currentWarehouse) {
          case 'primary':
            // 一级库的模拟API路径
            apiPaths = {
              maintenanceCenters: '/dev-api/system/LargeScreen/ys/global',
              inventoryTrend: '/dev-api/system/LargeScreen/tmistock/global',
              yearlyInventory: '/dev-api/system/LargeScreen/tmistockPie/global',
              sixMonthChart: '/dev-api/system/LargeScreen/tCk/global',
              monthlyInOut: '/dev-api/system/LargeScreen/sendTotal/global',
              monthlyPurchase: '/dev-api/system/LargeScreen/CLMoney/global',
              outboundDistribution: '/dev-api/system/LargeScreen/Outbound/global',
              overviewStats: '/dev-api/system/LargeScreen/tmistockTotal/global'
            };
            break;
          case 'other':
            // 其他库的模拟API路径
            apiPaths = {
              maintenanceCenters: '/dev-api/system/LargeScreen/ys/other',
              inventoryTrend: '/dev-api/system/LargeScreen/tmistock/other',
              yearlyInventory: '/dev-api/system/LargeScreen/tmistockPie/other',
              sixMonthChart: '/dev-api/system/LargeScreen/tCk/other',
              monthlyInOut: '/dev-api/system/LargeScreen/sendTotal/other',
              monthlyPurchase: '/dev-api/system/LargeScreen/CLMoney/other',
              outboundDistribution: '/dev-api/system/LargeScreen/Outbound/other',
              overviewStats: '/dev-api/system/LargeScreen/tmistockTotal/other'
            };
            break;
          default: // 'global' - 全局（使用现有的API路径）
            apiPaths = {
              maintenanceCenters: '/dev-api/system/LargeScreen/ys',
              inventoryTrend: '/dev-api/system/LargeScreen/tmistock',
              yearlyInventory: '/dev-api/system/LargeScreen/tmistockPie',
              sixMonthChart: '/dev-api/system/LargeScreen/tCk',
              monthlyInOut: '/dev-api/system/LargeScreen/sendTotal',
              monthlyPurchase: '/dev-api/system/LargeScreen/CLMoney',
              outboundDistribution: '/dev-api/system/LargeScreen/Outbound',
              overviewStats: '/dev-api/system/LargeScreen/tmistockTotal'
            };
        }

        // 清空现有图表
        this.charts.forEach(chart => chart.dispose());
        this.charts = [];

        const [
          maintenanceCenters,
          inventoryTrend,
          yearlyInventory,
          sixMonthChart,
          monthlyInOut,
          monthlyPurchase,
          outboundDistribution,
          overviewStats
        ] = await Promise.all([
          axios.get(apiPaths.maintenanceCenters),
          axios.get(apiPaths.inventoryTrend),
          axios.get(apiPaths.yearlyInventory),
          axios.get(apiPaths.sixMonthChart),
          axios.get(apiPaths.monthlyInOut),
          axios.get(apiPaths.monthlyPurchase),
          axios.get(apiPaths.outboundDistribution),
          axios.get(apiPaths.overviewStats)
        ]);

        // 更新数据
        this.maintenanceCenters = maintenanceCenters.data;
        this.tmi = inventoryTrend.data;
        this.tmiPie = yearlyInventory.data;
        this.sixMonthData = sixMonthChart.data;
        this.monthlyInOutData = monthlyInOut.data;
        this.monthlyPurchaseData = monthlyPurchase.data;
        this.outboundDistributionData = outboundDistribution.data;

        if (Array.isArray(overviewStats.data)) {
          const [totalValue, monthlyOutbound, monthlyInbound, warehouseCount, usedBudget, yearBudget] = overviewStats.data;
          this.totalValue = totalValue;
          this.monthlyOutbound = monthlyOutbound;
          this.monthlyInbound = monthlyInbound;
          this.warehouseCount = warehouseCount;
          this.usedBudget = usedBudget;
          this.yearBudget = yearBudget;
        } else {
          const data = overviewStats.data;
          this.totalValue = data.totalValue;
          this.monthlyOutbound = data.monthlyOutbound;
          this.monthlyInbound = data.monthlyInbound;
          this.warehouseCount = data.warehouseCount;
          this.usedBudget = data.usedBudget;
          this.yearBudget = data.yearBudget;
        }

        // 设置所有数据加载完成标志
        for (let key in this.dataLoaded) {
          this.dataLoaded[key] = true;
        }

        // 重新初始化图表
        this.$nextTick(() => {
          this.initAllCharts();
        });

      } catch (error) {
        console.error('Error in fetchData:', error);
        this.$message.error(`获取${this.getWarehouseTypeName()}数据失败，请稍后重试`);
      } finally {
        this.loading = false;
      }
    },
    handleResize() {
      this.charts.forEach(chart => chart.resize())
    },
    initAllCharts() {
      this.initProgressCharts();
      this.initBudgetGauge();
      this.initMonthlyPurchaseChart();
      this.initSixMonthChart();
      this.initValueDistributionChart();
      this.initMonthlyInOutChart();
      this.initOutboundDistributionChart();
      this.initYearlyInventoryChart();
      this.initInventoryTrendChart();
    },
    initProgressCharts() {
      if (!this.$refs.progressCharts) return;

      this.maintenanceCenters.forEach((center, index) => {
        const chartDom = this.$refs.progressCharts[index];
        if (!chartDom) return;

        const chart = echarts.init(chartDom);
        const option = {
          series: [{
            type: 'gauge',
            startAngle: 90,
            endAngle: -270,
            radius: '100%',
            center: ['50%', '50%'],
            pointer: {show: false},
            progress: {
              show: true,
              overlap: false,
              roundCap: true,
              clip: false,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                  { offset: 0, color: '#4facfe' },
                  { offset: 1, color: '#00f2fe' }
                ]),
                shadowBlur: 20,
                shadowColor: 'rgba(79, 172, 254, 0.8)'
              }
            },
            axisLine: {
              lineStyle: {
                width: 10,
                color: [[1, 'rgba(255, 255, 255, 0.1)']]
              }
            },
            splitLine: {show: false},
            axisTick: {show: false},
            axisLabel: {show: false},
            data: [{
              value: center.rate,
              detail: {
                valueAnimation: true,
                offsetCenter: ['0%', '0%']
              }
            }],
            detail: {
              fontSize: 16,
              color: '#fff',
              fontWeight: 700,
              formatter: '{value}%'
            }
          }],
          animation: true,
          animationDuration: 2000,
          animationEasing: 'elasticOut'
        };
        chart.setOption(option);
        this.charts.push(chart);
      });
    },
    initBudgetGauge() {
      const data = (this.usedBudget/this.yearBudget*100).toFixed(2);
      const chart = echarts.init(this.$refs.budgetGauge);
      const option = {
        series: [{
          type: 'gauge',
          startAngle: 180,
          endAngle: 0,
          min: 0,
          max: 100,
          radius: '100%',
          progress: {
            show: true,
            width: 20,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                { offset: 0, color: '#4facfe' },
                { offset: 1, color: '#00f2fe' }
              ]),
              shadowBlur: 20,
              shadowColor: 'rgba(79, 172, 254, 0.8)'
            }
          },
          pointer: { show: false },
          axisLine: {
            lineStyle: {
              width: 20,
              color: [[1, 'rgba(255, 255, 255, 0.1)']]
            }
          },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: { show: false },
          detail: {
            valueAnimation: true,
            formatter: '{value}%',
            color: '#fff',
            fontSize: 28,
            fontWeight: 700,
            offsetCenter: [0, '20%']
          },
          data: [{
            value: data,
            name: '预算使用率',
            title: {
              offsetCenter: [0, '80%'],
              color: 'rgba(255, 255, 255, 0.7)',
              fontSize: 14
            }
          }]
        }],
        animation: true,
        animationDuration: 2000,
        animationEasing: 'elasticOut'
      };
      chart.setOption(option);
      this.charts.push(chart);
    },
    initMonthlyPurchaseChart() {
      const chart = echarts.init(this.$refs.monthlyPurchaseChart);
      const commonConfig = this.getCommonChartConfig();

      const option = {
        ...commonConfig,
        tooltip: {
          ...commonConfig.tooltip,
          axisPointer: {
            type: 'shadow',
            shadowStyle: {
              color: 'rgba(75, 150, 255, 0.1)'
            }
          }
        },
        legend: {
          data: ['入库金额', '出库金额'],
          textStyle: {
            color: '#fff',
            fontSize: 14
          },
          itemWidth: 20,
          itemHeight: 12,
          itemGap: 20
        },
        xAxis: {
          ...commonConfig.xAxis,
          type: 'category',
          data: Object.keys(this.monthlyPurchaseData),
          axisLabel: {
            ...commonConfig.xAxis.axisLabel,
            rotate: 45
          }
        },
        yAxis: {
          ...commonConfig.yAxis,
          type: 'value'
        },
        series: [
          {
            name: '入库金额',
            type: 'bar',
            data: Object.values(this.monthlyPurchaseData).map(item => item[0][0]),
            barWidth: '35%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                { offset: 0, color: '#667eea' },
                { offset: 1, color: '#764ba2' }
              ]),
              borderRadius: [8, 8, 0, 0],
              shadowBlur: 10,
              shadowColor: 'rgba(102, 126, 234, 0.5)',
              shadowOffsetY: 3
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 20,
                shadowColor: 'rgba(102, 126, 234, 0.8)'
              }
            }
          },
          {
            name: '出库金额',
            type: 'bar',
            data: Object.values(this.monthlyPurchaseData).map(item => item[1][0]),
            barWidth: '35%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                { offset: 0, color: '#4facfe' },
                { offset: 1, color: '#00f2fe' }
              ]),
              borderRadius: [8, 8, 0, 0],
              shadowBlur: 10,
              shadowColor: 'rgba(79, 172, 254, 0.5)',
              shadowOffsetY: 3
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 20,
                shadowColor: 'rgba(79, 172, 254, 0.8)'
              }
            }
          }
        ]
      };
      chart.setOption(option);
      this.charts.push(chart);
    },
    initSixMonthChart() {
      const chart = echarts.init(this.$refs.sixMonthChart);
      const commonConfig = this.getCommonChartConfig();
      const now = new Date();
      const currentMonth = now.getMonth();
      const months = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
      const xAxisData = Array.from({ length: 6 }, (_, i) => months[(currentMonth - i -1+ 12) % 12]);

      const option = {
        ...commonConfig,
        tooltip: {
          ...commonConfig.tooltip,
          axisPointer: {
            type: 'cross',
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.3)',
              type: 'dashed'
            }
          }
        },
        xAxis: {
          ...commonConfig.xAxis,
          type: 'category',
          boundaryGap: false,
          data: [...xAxisData].reverse()
        },
        yAxis: {
          ...commonConfig.yAxis,
          type: 'value'
        },
        series: [{
          data: [...this.sixMonthData].reverse(),
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 10,
          showSymbol: true,
          lineStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#4facfe' },
              { offset: 1, color: '#00f2fe' }
            ]),
            width: 4,
            shadowBlur: 15,
            shadowColor: 'rgba(79, 172, 254, 0.6)',
            shadowOffsetY: 5
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(79, 172, 254, 0.5)' },
              { offset: 1, color: 'rgba(79, 172, 254, 0.05)' }
            ])
          },
          itemStyle: {
            color: '#fff',
            borderColor: '#4facfe',
            borderWidth: 3,
            shadowBlur: 15,
            shadowColor: 'rgba(79, 172, 254, 1)'
          },
          emphasis: {
            scale: true,
            scaleSize: 15,
            itemStyle: {
              shadowBlur: 25,
              shadowColor: 'rgba(79, 172, 254, 1)'
            }
          }
        }]
      };
      chart.setOption(option);
      this.charts.push(chart);
    },
    initValueDistributionChart() {
      const chart = echarts.init(this.$refs.valueDistributionChart);
      const option = {
        series: [{
          type: 'treemap',
          data: [
            {
              name: '五金工具',
              value: 50,
              itemStyle: { color: '#4B96FF' }
            },
            {
              name: '通用电气',
              value: 15,
              itemStyle: { color: '#41D9D9' }
            },
            {
              name: '其他',
              value: 35,
              itemStyle: { color: '#63CF7E' }
            }
          ],
          label: {
            show: true,
            formatter: '{b}\n{c}%',
            color: '#fff'
          }
        }]
      };
      chart.setOption(option);
      this.charts.push(chart);
    },
    initMonthlyInOutChart() {
      const chart = echarts.init(this.$refs.monthlyInOutChart);
      const commonConfig = this.getCommonChartConfig();

      const option = {
        ...commonConfig,
        tooltip: {
          ...commonConfig.tooltip,
          axisPointer: {
            type: 'shadow',
            shadowStyle: {
              color: 'rgba(75, 150, 255, 0.1)'
            }
          }
        },
        legend: {
          data: ['入库金额', '出库金额'],
          textStyle: {
            color: '#fff',
            fontSize: 14
          },
          itemWidth: 20,
          itemHeight: 12,
          itemGap: 20
        },
        xAxis: {
          ...commonConfig.xAxis,
          type: 'category',
          data: Object.keys(this.monthlyInOutData),
          axisLabel: {
            ...commonConfig.xAxis.axisLabel,
            rotate: 45
          }
        },
        yAxis: {
          ...commonConfig.yAxis,
          type: 'value'
        },
        series: [
          {
            name: '入库金额',
            type: 'bar',
            data: Object.values(this.monthlyInOutData).map(item => item[1]),
            barWidth: '35%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                { offset: 0, color: '#43e97b' },
                { offset: 1, color: '#38f9d7' }
              ]),
              borderRadius: [8, 8, 0, 0],
              shadowBlur: 10,
              shadowColor: 'rgba(67, 233, 123, 0.5)',
              shadowOffsetY: 3
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 20,
                shadowColor: 'rgba(67, 233, 123, 0.8)'
              }
            }
          },
          {
            name: '出库金额',
            type: 'bar',
            data: Object.values(this.monthlyInOutData).map(item => item[0]),
            barWidth: '35%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                { offset: 0, color: '#f093fb' },
                { offset: 1, color: '#f5576c' }
              ]),
              borderRadius: [8, 8, 0, 0],
              shadowBlur: 10,
              shadowColor: 'rgba(240, 147, 251, 0.5)',
              shadowOffsetY: 3
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 20,
                shadowColor: 'rgba(240, 147, 251, 0.8)'
              }
            }
          }
        ]
      };
      chart.setOption(option);
      this.charts.push(chart);
    },
    initOutboundDistributionChart() {
      const chart = echarts.init(this.$refs.outboundDistributionChart);
      const keys = Object.keys(this.outboundDistributionData);
      const values = Object.values(this.outboundDistributionData);

      const option = {
        grid: {
          left: '20%',
          right: '5%',
          top: '10%',
          bottom: '10%'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'value',
          axisLine: {
            lineStyle: { color: '#ffffff30' }
          },
          splitLine: {
            lineStyle: { color: '#ffffff10' }
          }
        },
        yAxis: {
          type: 'category',
          data: keys,
          axisLine: {
            lineStyle: { color: '#ffffff30' }
          },
          axisLabel: {
            color: '#fff'
          }
        },
        series: [{
          type: 'bar',
          data: values,
          itemStyle: {
            color: '#4B96FF'
          }
        }]
      };
      chart.setOption(option);
      this.charts.push(chart);
    },
    initYearlyInventoryChart() {
      const chart = echarts.init(this.$refs.yearlyInventoryChart);

      const dataArray = Object.entries(this.tmiPie).map(([name, value]) => ({
        name,
        value
      }));
      const option = {
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(10, 22, 40, 0.95)',
          borderColor: 'rgba(75, 150, 255, 0.5)',
          borderWidth: 1,
          textStyle: {
            color: '#fff',
            fontSize: 14
          },
          padding: [12, 16],
          extraCssText: 'backdrop-filter: blur(10px); box-shadow: 0 4px 20px rgba(0,0,0,0.6); border-radius: 8px;',
          formatter: '{b}<br/>{c}万元 ({d}%)'
        },
        series: [
          {
            type: 'pie',
            radius: ['45%', '75%'],
            center: ['50%', '50%'],
            roseType: 'radius',
            itemStyle: {
              borderRadius: 10,
              borderColor: 'rgba(10, 22, 40, 0.5)',
              borderWidth: 3,
              shadowBlur: 20,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
              color: (params) => {
                const gradients = [
                  { start: '#667eea', end: '#764ba2' },
                  { start: '#4facfe', end: '#00f2fe' },
                  { start: '#43e97b', end: '#38f9d7' },
                  { start: '#fa709a', end: '#fee140' },
                  { start: '#30cfd0', end: '#330867' }
                ];
                const idx = params.dataIndex % gradients.length;
                return new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                  { offset: 0, color: gradients[idx].start },
                  { offset: 1, color: gradients[idx].end }
                ]);
              }
            },
            label: {
              color: '#fff',
              fontSize: 14,
              fontWeight: 600,
              formatter: '{b}\n{c}万元',
              lineHeight: 20,
              shadowBlur: 5,
              shadowColor: 'rgba(0, 0, 0, 0.8)'
            },
            labelLine: {
              lineStyle: {
                color: 'rgba(255, 255, 255, 0.4)',
                width: 2
              },
              smooth: 0.3,
              length: 20,
              length2: 30
            },
            emphasis: {
              scale: true,
              scaleSize: 10,
              itemStyle: {
                shadowBlur: 35,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.9)'
              },
              label: {
                fontSize: 16,
                fontWeight: 700
              }
            },
            data: dataArray
          }
        ],
        animation: true,
        animationDuration: 2000,
        animationEasing: 'cubicOut'
      };
      chart.setOption(option);
      this.charts.push(chart);
    },
    initInventoryTrendChart() {
      const chart = echarts.init(this.$refs.inventoryTrendChart);
      const now = new Date();
      const currentMonth = now.getMonth();
      const months = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
      const xAxisData = Array.from({ length: 6 }, (_, i) => months[(currentMonth - i - 1 + 12) % 12]);

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [...xAxisData].reverse(),
          axisLine: {
            lineStyle: { color: '#ffffff30' }
          },
          axisLabel: { color: '#fff' }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: { color: '#ffffff30' }
          },
          splitLine: {
            lineStyle: { color: '#ffffff10' }
          },
          axisLabel: { color: '#fff' }
        },
        series: [{
          data: [...this.tmi].reverse(),
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(75, 150, 255, 0.3)' },
              { offset: 1, color: 'rgba(75, 150, 255, 0)' }
            ])
          },
          lineStyle: {
            color: '#4B96FF',
            width: 3
          },
          itemStyle: {
            color: '#4B96FF'
          }
        }]
      };
      chart.setOption(option);
      this.charts.push(chart);
    },
    // 切换仓库类型
    changeWarehouse(type) {
      this.currentWarehouse = type;
      this.fetchData();
    },
    // 获取仓库类型名称
    getWarehouseTypeName() {
      switch(this.currentWarehouse) {
        case 'primary':
          return '一级库';
        case 'other':
          return '其他库';
        default:
          return '全局';
      }
    },
  }
}
</script>

<style scoped>
.dashboard {
  min-height: 100vh;
  background: linear-gradient(135deg, #0a1628 0%, #1a2744 50%, #0d1b2a 100%);
  color: #fff;
  padding: 24px;
  position: relative;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
}

.card {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0.03) 100%);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 12px;
  padding: 24px;
  height: auto;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.1);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  animation: fadeInUp 0.6s ease-out backwards;
  will-change: transform, opacity;
  transform: translateZ(0);
}

.card:nth-child(1) { animation-delay: 0.1s; }
.card:nth-child(2) { animation-delay: 0.2s; }
.card:nth-child(3) { animation-delay: 0.3s; }
.card:nth-child(4) { animation-delay: 0.4s; }
.card:nth-child(5) { animation-delay: 0.5s; }
.card:nth-child(6) { animation-delay: 0.6s; }
.card:nth-child(7) { animation-delay: 0.7s; }
.card:nth-child(8) { animation-delay: 0.8s; }
.card:nth-child(9) { animation-delay: 0.9s; }

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(40px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.card:hover {
  border-color: rgba(75, 150, 255, 0.6);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4), 0 0 30px rgba(75, 150, 255, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.2);
  transform: translateY(-3px);
}

/* 不支持毛玻璃效果的降级方案 */
@supports not (backdrop-filter: blur(12px)) {
  .card {
    background: rgba(255, 255, 255, 0.12);
  }
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  letter-spacing: 0.5px;
  position: relative;
  padding-left: 14px;
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.card-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background: linear-gradient(180deg, #4facfe 0%, #00f2fe 100%);
  border-radius: 2px;
  box-shadow: 0 0 10px rgba(79, 172, 254, 0.6);
}

.card-title::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 50px;
  height: 2px;
  background: linear-gradient(90deg, #4facfe 0%, transparent 100%);
  border-radius: 2px;
}

.progress-circles {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.progress-item {
  text-align: center;
}

.progress-chart {
  width: 60px;
  height: 60px;
  margin-bottom: 4px;
}

.center-name {
  font-size: 12px;
  color: #fff;
}

.stacked-bars {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  gap: 10px;
  padding-top: 24px;
  min-height: 220px;
}

.bar-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
}

.bar-group h2 {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 10px;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.bar-segment {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 11px;
  font-weight: 700;
  border-radius: 6px 6px 0 0;
  position: relative;
  min-height: 35px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.2);
  cursor: pointer;
}

.bar-segment::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: rgba(255, 255, 255, 0.4);
  border-radius: 6px 6px 0 0;
}

.bar-segment:hover {
  transform: scaleX(1.15) translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.3);
  z-index: 10;
  filter: brightness(1.2);
}

.overview-content {
  display: flex;
  gap: 10px;
}

.overview-stats {
  flex: 2;
  display: flex;
  flex-direction: column;
  gap: 70px;
}

.stat-group {
  display: flex;
  justify-content: flex-start;
}

.stat-item {
  display: flex;
  margin-right: 15px;
  flex-direction: column;
  gap: 4px;
}

.stat-label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  font-weight: 400;
  margin-bottom: 8px;
}

.stat-value {
  font-family: 'DIN Alternate', 'Roboto', 'Arial', sans-serif;
  font-size: 32px;
  font-weight: 700;
  letter-spacing: 1px;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  line-height: 1.2;
}

.budget-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.budget-info {
  display: flex;
  gap: 10px;
}

.budget-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.budget-label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  font-weight: 400;
}

.budget-value {
  font-family: 'DIN Alternate', 'Roboto', 'Arial', sans-serif;
  font-size: 32px;
  font-weight: 700;
  letter-spacing: 1px;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  line-height: 1.2;
}

.budget-gauge {
  width: 200px;
  height: 150px;
}

.chart {
  height: 250px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #0a1628 0%, #1a2744 100%);
  backdrop-filter: blur(10px);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  gap: 30px;
}

.loading-logo {
  animation: pulse 2s ease-in-out infinite;
}

.loading-logo img {
  height: 60px;
  filter: drop-shadow(0 0 20px rgba(79, 172, 254, 0.6));
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
}

.loading-spinner {
  position: relative;
  width: 100px;
  height: 100px;
}

.loading-spinner::before,
.loading-spinner::after {
  content: '';
  position: absolute;
  border-radius: 50%;
  border: 3px solid transparent;
  animation: spin 1.5s cubic-bezier(0.5, 0, 0.5, 1) infinite;
}

.loading-spinner::before {
  width: 100%;
  height: 100%;
  border-top-color: #4facfe;
  animation-delay: 0s;
}

.loading-spinner::after {
  width: 80%;
  height: 80%;
  top: 10%;
  left: 10%;
  border-top-color: #00f2fe;
  animation-delay: -0.3s;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: rgba(255, 255, 255, 0.9);
  font-size: 18px;
  letter-spacing: 2px;
  font-weight: 500;
}

.loading-text::after {
  content: '...';
  animation: loadingDots 1.5s steps(4) infinite;
}

@keyframes loadingDots {
  0%, 20% { content: '.'; }
  40% { content: '..'; }
  60%, 100% { content: '...'; }
}

/* 4K 大屏 (2560px+) */
@media screen and (min-width: 2560px) {
  .dashboard {
    padding: 40px 60px;
  }

  .grid-container {
    gap: 32px;
  }

  .card {
    padding: 32px;
  }

  .card-title {
    font-size: 22px;
  }

  .stat-value, .budget-value {
    font-size: 40px;
  }

  .chart {
    height: 350px;
  }
}

/* 全高清 (1920px - 2559px) - 桌面显示器主要场景 */
@media screen and (min-width: 1920px) and (max-width: 2559px) {
  .stat-value, .budget-value {
    font-size: 32px;
  }
}

/* 标准屏幕 (1366px - 1919px) - 桌面显示器常见尺寸 */
@media screen and (min-width: 1366px) and (max-width: 1919px) {
  .stat-value, .budget-value {
    font-size: 28px;
  }
}

/* 小屏幕 (1024px - 1365px) - 2列布局 */
@media screen and (max-width: 1365px) {
  .grid-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }

  .dashboard {
    padding: 16px;
  }

  .card {
    padding: 16px;
  }

  .card-title {
    font-size: 16px;
  }

  .stat-value, .budget-value {
    font-size: 24px;
  }
}

/* 平板 (< 1024px) - 1列布局 */
@media screen and (max-width: 1023px) {
  .grid-container {
    grid-template-columns: 1fr;
  }

  .overview-content {
    flex-direction: column;
  }

  .stat-group {
    flex-direction: column;
    align-items: flex-start;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.warehouse-toggle {
  display: flex;
  align-items: center;
  gap: 12px;
}

.toggle-button {
  padding: 6px 12px;
  height: auto;
  line-height: 1;
  color: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(75, 150, 255, 0.4);
  background: rgba(75, 150, 255, 0.15);
  border-radius: 6px;
  transition: all 0.3s ease;
}

.toggle-button:hover {
  background: rgba(75, 150, 255, 0.25);
  border-color: rgba(75, 150, 255, 0.6);
  box-shadow: 0 0 15px rgba(75, 150, 255, 0.3);
}

.toggle-button i {
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-size: 16px;
}

.toggle-button i.rotated {
  transform: rotate(90deg);
}

.button-group {
  display: flex;
  gap: 0;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  padding: 4px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.button-group .el-button {
  margin: 0;
  background: transparent;
  border: none;
  color: rgba(255, 255, 255, 0.6);
  border-radius: 8px;
  padding: 8px 16px;
  height: auto;
  line-height: 1;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.button-group .el-button.el-button--primary {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: #fff;
  box-shadow: 0 4px 15px rgba(79, 172, 254, 0.5);
  transform: scale(1.05);
}

.button-group .el-button:hover:not(.el-button--primary) {
  background: rgba(255, 255, 255, 0.15);
  color: rgba(255, 255, 255, 0.9);
  transform: translateY(-1px);
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>
