<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">
        <h3 class="card-title">仓库总览</h3>
        <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-spinner"></div>
    </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: ['#4B96FF', '#41D9D9', '#de8226', '#FFC442','#c5229f','#63CF7E','#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0'],
      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
      }
    }
  },
  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]}%`;
    },
    async fetchData() {
      try {
        const [
          maintenanceCenters,
          inventoryTrend,
          yearlyInventory,
          sixMonthChart,
          monthlyInOut,
          monthlyPurchase,
          outboundDistribution,
          overviewStats
        ] = await Promise.all([
          axios.get('/dev-api/system/LargeScreen/ys'),
          axios.get('/dev-api/system/LargeScreen/tmistock'),
          axios.get('/dev-api/system/LargeScreen/tmistockPie'),
          axios.get('/dev-api/system/LargeScreen/tCk'),
          axios.get('/dev-api/system/LargeScreen/sendTotal'),
          axios.get('/dev-api/system/LargeScreen/CLMoney'),
          axios.get('/dev-api/system/LargeScreen/Outbound'),
          axios.get('/dev-api/system/LargeScreen/tmistockTotal')
        ]);

        this.maintenanceCenters = maintenanceCenters.data;

        this.tmiPie = yearlyInventory.data;
        this.sixMonthData = sixMonthChart.data;
        this.monthlyInOutData = monthlyInOut.data;
        this.monthlyPurchaseData = monthlyPurchase.data;
        this.outboundDistributionData = outboundDistribution.data;

        const [totalValue, monthlyOutbound, monthlyInbound, warehouseCount, usedBudget ,yearBudget ] = overviewStats.data;
        this.monthlyOutbound = monthlyOutbound;
        this.monthlyInbound = monthlyInbound;
        this.totalValue =  totalValue ;
        this.warehouseCount = warehouseCount;
        this.usedBudget = usedBudget;
        this.yearBudget = yearBudget;
        this.tmi = inventoryTrend.data;
        // Set all data loaded flags to true
        for (let key in this.dataLoaded) {
          this.dataLoaded[key] = true;
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        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: '#4B96FF'
              }
            },
            axisLine: {
              lineStyle: {
                width: 8,
                color: [[1, 'rgba(75, 150, 255, 0.1)']]
              }
            },
            splitLine: {show: false},
            axisTick: {show: false},
            axisLabel: {show: false},
            data: [{
              value: center.rate,
              detail: {
                valueAnimation: true,
                offsetCenter: ['0%', '0%']
              }
            }],
            detail: {
              fontSize: 14,
              color: '#fff',
              formatter: '{value}%'
            }
          }]
        };
        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: 18,
            itemStyle: {
              color: '#4B96FF'
            }
          },
          pointer: { show: false },
          axisLine: {
            lineStyle: {
              width: 18,
              color: [[1, 'rgba(75, 150, 255, 0.1)']]
            }
          },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: { show: false },
          detail: {
            valueAnimation: true,
            formatter: '{value}%',
            color: '#fff',
            fontSize: 24,
            offsetCenter: [0, '20%']
          },
          data: [{
            value: data,
            name: '预算使用率',
            title: {
              offsetCenter: [0, '80%']
            }
          }]
        }]
      };
      chart.setOption(option);
      this.charts.push(chart);
    },
    initMonthlyPurchaseChart() {
      const chart = echarts.init(this.$refs.monthlyPurchaseChart);
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['入库金额', '出库金额'],
          textStyle: { color: '#fff' }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: Object.keys(this.monthlyPurchaseData),
          axisLine: {
            lineStyle: { color: '#ffffff30' }
          },
          axisLabel: {
            color: '#fff',
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: { color: '#ffffff30' }
          },
          splitLine: {
            lineStyle: { color: '#ffffff10' }
          },
          axisLabel: { color: '#fff' }
        },
        series: [
          {
            name: '入库金额',
            type: 'bar',
            data: Object.values(this.monthlyPurchaseData).map(item => item[0][0]),
            itemStyle: { color: '#4B96FF' }
          },
          {
            name: '出库金额',
            type: 'bar',
            data: Object.values(this.monthlyPurchaseData).map(item => item[1][0]),
            itemStyle: { color: '#41D9D9' }
          }
        ]
      };
      chart.setOption(option);
      this.charts.push(chart);
    },
    initSixMonthChart() {
      const chart = echarts.init(this.$refs.sixMonthChart);
      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.sixMonthData.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);
    },
    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 option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['入库金额', '出库金额'],
          textStyle: { color: '#fff' }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: Object.keys(this.monthlyInOutData),
          axisLine: {
            lineStyle: { color: '#ffffff30' }
          },
          axisLabel: {
            color: '#fff',
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: { color: '#ffffff30' }
          },
          splitLine: {
            lineStyle: { color: '#ffffff10' }
          },
          axisLabel: { color: '#fff' }
        },
        series: [
          {
            name: '入库金额',
            type: 'bar',
            data: Object.values(this.monthlyInOutData).map(item => item[1]),
            itemStyle: { color: '#4B96FF' }
          },
          {
            name: '出库金额',
            type: 'bar',
            data: Object.values(this.monthlyInOutData).map(item => item[0]),
            itemStyle: { color: '#41D9D9' }
          }
        ]
      };
      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'
        },
        // legend: {
        //   orient: 'vertical',
        //   right: '5%',
        //   top: 'center',
        //   textStyle: { color: '#fff' }
        // },
        series: [
          {
            type: 'pie',
            radius: ['50%', '90%'],
            center: ['50%', '50%'],
            data: dataArray,
            itemStyle: {
              color: function(params) {
                const colors = ['#4B96FF', '#41D9D9', '#63CF7E', '#FFC442', '#FF7D7D'];
                return colors[params.dataIndex % colors.length];
              }
            },
            label: {
              color: '#fff',
              formatter: '{b}: {c}',
            }
          }
        ]
      };
      chart.setOption(option);
      this.charts.push(chart);
    },
    initInventoryTrendChart() {
      // 将图表初始化代码放在 .then() 回调函数中
      const chart = echarts.init(this.$refs.inventoryTrendChart);
      // this.tmi[0] = (this.totalValue + this.monthlyOutbound - this.monthlyInbound).toFixed(2);
      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);
    }
  }
}
</script>

<style scoped>
.dashboard {
  min-height: 100vh;
  background-color: #004ea2;
  color: #fff;
  padding: 15px;
}

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

.card {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 15px;
  height: auto;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.02);
}

.card-title {
  color: #fff;
  font-size: 14px;
  margin-bottom: 10px;
  font-weight: 500;
}

.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;
  /* Removed height to allow flex-grow */
  /* padding-top: 20px; */  /* Optional for additional spacing */
  align-items: flex-end;
}

.bar-group {
  width: 50px;
  display: flex;
  flex-direction: column;
}

.bar-segment {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 8px;
  transition: all 0.3s;
}

.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: #ffffff;
  font-size: 20px;
}

.stat-value {
  color: #4B96FF;
  font-size: 20px;
  font-weight: bold;
}

.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: #ffffff;
  font-size: 20px;
}

.budget-value {
  color: #4B96FF;
  font-size: 20px;
  font-weight: bold;
}

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

.chart {
  height: 250px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #fff;
  border-top: 3px solid #4B96FF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

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

@media screen and (max-width: 1366px) {
  .grid-container {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media screen and (max-width: 1024px) {
  .grid-container {
    grid-template-columns: 1fr;
  }
}
</style>
