
<template>
  <div>
    <div class="chart-header">
      <el-radio-group v-model="groupMode" @change="updateChart">
        <el-radio-button label="warehouse">按仓库汇总</el-radio-button>
        <el-radio-button label="item">按物品汇总</el-radio-button>
      </el-radio-group>
    </div>
    <div ref="chartContainer" style="width: 100%; height: 600px;"></div>
  </div>
</template>

<script>

import * as echarts from 'echarts';
import { listStock } from "@/api/wms/stock";
import { listWarehouse } from "@/api/wms/warehouse";

export default {
  name: "StockBox",
  data() {
    return {
      chart: null,
      stockData: [],
      warehouseData: [],
      groupMode: 'warehouse', // 默认按仓库汇总
      warehouseTreeData: []
    };
  },
  mounted() {
    this.initChart();
    this.loadData();
  },
  methods: {
    initChart() {
      if (this.chart) {
        this.chart.dispose();
      }
      this.chart = echarts.init(this.$refs.chartContainer);
      window.addEventListener('resize', this.handleResize);
    },
    handleResize() {
      this.chart && this.chart.resize();
    },
    async loadData() {
      try {
        // 并行加载仓库结构和库存数据
        const [warehouseRes, stockRes] = await Promise.all([
          listWarehouse(),
          listStock({ pageNum: 1, pageSize: 9999 })
        ]);
        
        this.warehouseTreeData = this.handleTree(warehouseRes.data, 'warehouseId', 'parentId');
        this.stockData = stockRes.rows;
        this.updateChart();
      } catch (error) {
        console.error('加载数据失败:', error);
      }
    },
    // 处理树结构
    handleTree(data, id, parentId) {
      const cloneData = JSON.parse(JSON.stringify(data));
      return cloneData.filter(father => {
        const branchArr = cloneData.filter(child => father[id] === child[parentId]);
        if (branchArr.length > 0) father.children = branchArr;
        return father[parentId] === 0 || father[parentId] === null;
      });
    },
    updateChart() {
      let treeData;
      if (this.groupMode === 'warehouse') {
        treeData = this.getWarehouseTreeData();
      } else {
        treeData = this.getItemTreeData();
      }

      const option = {
        tooltip: {
          formatter: (params) => {
            const data = params.data;
            if (data.stockInfo) {
              return this.formatTooltip(data);
            }
            return `${params.name}<br/>总数量: ${params.value || 0}`;
          }
        },
        series: [{
          type: 'treemap',
          data: treeData.children,
          label: {
            show: true,
            formatter: (params) => {
              const data = params.data;
              if (data.stockInfo) {
                return `${params.name}\n${params.value}${data.stockInfo.unit || ''}`;
              }
              return `${params.name}\n${params.value || ''}`;
            }
          },
          breadcrumb: {
            show: true
          },
          roam: false,
          levels: [
            {
              itemStyle: {
                borderColor: '#555',
                borderWidth: 4,
                gapWidth: 4
              }
            },
            {
              itemStyle: {
                borderColor: '#777',
                borderWidth: 2,
                gapWidth: 2
              }
            }
          ]
        }]
      };

      this.chart && this.chart.setOption(option);
    },
    getWarehouseTreeData() {
      const buildWarehouseTree = (warehouseNode) => {
        const stocks = this.stockData.filter(stock => stock.warehouseId === warehouseNode.warehouseId);
        const children = [];
        let totalQuantity = 0;

        // 处理当前仓库的库存
        stocks.forEach(stock => {
          const quantity = Number(stock.quantity) || 0;
          totalQuantity += quantity;
          children.push({
            name: this.getItemName(stock),
            value: quantity,
            stockInfo: {
              itemType: stock.itemType,
              itemCode: stock.itemCode,
              unit: stock.unit,
              batchNo: stock.batchNo
            }
          });
        });

        // 处理子仓库
        if (warehouseNode.children && warehouseNode.children.length > 0) {
          warehouseNode.children.forEach(child => {
            const childNode = buildWarehouseTree(child);
            if (childNode.value > 0) {
              children.push(childNode);
              totalQuantity += childNode.value;
            }
          });
        }

        return {
          name: warehouseNode.warehouseName,
          value: totalQuantity,
          children: children.length > 0 ? children : undefined
        };
      };

      return {
        name: '库存总览',
        children: this.warehouseTreeData.map(warehouse => buildWarehouseTree(warehouse))
      };
    },
    getItemTreeData() {
      // 按物品类型和物品分组
      const itemGroups = {};
      this.stockData.forEach(stock => {
        const itemType = this.getItemTypeName(stock.itemType);
        if (!itemGroups[itemType]) {
          itemGroups[itemType] = {};
        }
        
        const itemKey = stock.itemId + '_' + stock.itemName;
        if (!itemGroups[itemType][itemKey]) {
          itemGroups[itemType][itemKey] = {
            name: stock.itemName,
            value: 0,
            children: []
          };
        }

        const quantity = Number(stock.quantity) || 0;
        itemGroups[itemType][itemKey].value += quantity;
        itemGroups[itemType][itemKey].children.push({
          name: this.getWarehouseName(stock.warehouseId),
          value: quantity,
          stockInfo: {
            itemType: stock.itemType,
            itemCode: stock.itemCode,
            unit: stock.unit,
            batchNo: stock.batchNo
          }
        });
      });

      return {
        name: '库存总览',
        children: Object.entries(itemGroups).map(([type, items]) => ({
          name: type,
          children: Object.values(items)
        }))
      };
    },
    formatTooltip(data) {
      const stockInfo = data.stockInfo;
      return `${data.name}<br/>
              数量: ${data.value} ${stockInfo.unit || ''}<br/>
              类型: ${this.getItemTypeName(stockInfo.itemType)}<br/>
              编号: ${stockInfo.itemCode || '无'}<br/>
              批次: ${stockInfo.batchNo || '无'}`;
    },
    getItemTypeName(type) {
      const typeMap = {
        raw_material: '原材料',
        product: '产品',
      };
      return typeMap[type] || type;
    },
    getItemName(stock) {
      return stock.itemName || `${this.getItemTypeName(stock.itemType)}-${stock.itemCode}`;
    },
    getWarehouseName(warehouseId) {
      const findWarehouse = (warehouses) => {
        for (const warehouse of warehouses) {
          if (warehouse.warehouseId === warehouseId) {
            return warehouse.warehouseName;
          }
          if (warehouse.children) {
            const name = findWarehouse(warehouse.children);
            if (name) return name;
          }
        }
        return null;
      };
      return findWarehouse(this.warehouseTreeData) || '未知仓库';
    },
    refresh() {
      this.loadData();
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  }
};
</script>

<style scoped>
</style>
