<template>
  <a-modal
    :visible="visible"
    :title="title"
    :width="1000"
    :footer="null"
    @cancel="handleCancel"
  >
    <div class="tree-container">
      <v-chart
        ref="chartRef"
        class="chart"
        :option="chartOption"
        :loading="loading"
        autoresize
      />
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, watch, computed } from 'vue';
  import { use } from 'echarts/core';
  import { CanvasRenderer } from 'echarts/renderers';
  import { TreeChart } from 'echarts/charts';
  import { TooltipComponent, TitleComponent } from 'echarts/components';
  import VChart from 'vue-echarts';
  import type { ShopDealerReferee } from '@/api/shop/shopDealerReferee/model';

  // 注册 echarts 组件
  use([CanvasRenderer, TreeChart, TooltipComponent, TitleComponent]);

  // 定义组件属性
  const props = withDefaults(
    defineProps<{
      visible: boolean;
      data?: ShopDealerReferee[];
      title?: string;
    }>(),
    {
      visible: false,
      data: () => [],
      title: '推荐关系树'
    }
  );

  // 定义事件
  const emit = defineEmits<{
    (e: 'update:visible', value: boolean): void;
    (e: 'cancel'): void;
  }>();

  // 图表引用
  const chartRef = ref<InstanceType<typeof VChart> | null>(null);

  // 加载状态
  const loading = ref(false);

  // 处理取消事件
  const handleCancel = () => {
    emit('update:visible', false);
    emit('cancel');
  };

  // 转换数据为树形结构
  const transformToTreeData = (data: ShopDealerReferee[]) => {
    if (!data || data.length === 0) {
      return { name: '暂无数据', children: [] };
    }

    // 构建节点映射
    const nodeMap = new Map<number, any>();
    const rootNodes: any[] = [];

    // 创建所有节点
    data.forEach((item) => {
      // 推荐人节点
      if (item.dealerId && !nodeMap.has(item.dealerId)) {
        nodeMap.set(item.dealerId, {
          id: item.dealerId,
          name: `推荐人\nID:${item.dealerId}\n${item.dealerName || ''}`,
          level: 'dealer',
          children: []
        });
      }

      // 被推荐人节点
      if (item.userId && !nodeMap.has(item.userId)) {
        nodeMap.set(item.userId, {
          id: item.userId,
          name: `被推荐人\nID:${item.userId}\n${item.nickname || ''}`,
          level: 'user',
          children: []
        });
      }
    });

    // 构建关系树
    data.forEach((item) => {
      if (!item.dealerId || !item.userId) return;

      const dealerNode = nodeMap.get(item.dealerId);
      const userNode = nodeMap.get(item.userId);

      if (dealerNode && userNode) {
        // 添加层级标签
        const levelText =
          { 1: '一级', 2: '二级', 3: '三级' }[item.level || 0] ||
          `${item.level || 0}级`;
        userNode.name += `\n${levelText}推荐`;
        dealerNode.children.push(userNode);
      }
    });

    // 查找根节点（没有被推荐关系的节点）
    const referencedIds = new Set(
      data.map((item) => item.userId).filter((id) => id)
    );
    data.forEach((item) => {
      if (item.dealerId && !referencedIds.has(item.dealerId)) {
        const rootNode = nodeMap.get(item.dealerId);
        if (rootNode) {
          rootNodes.push(rootNode);
        }
      }
    });

    // 如果没有明确的根节点，使用第一个节点作为根
    if (rootNodes.length === 0 && data.length > 0 && data[0].dealerId) {
      const firstNode = nodeMap.get(data[0].dealerId);
      if (firstNode) {
        rootNodes.push(firstNode);
      }
    }

    // 如果还是没有根节点，返回默认节点
    if (rootNodes.length === 0) {
      return { name: '暂无数据', children: [] };
    }

    return rootNodes[0];
  };

  // 图表配置
  const chartOption = computed(() => {
    const treeData = transformToTreeData(props.data || []);

    return {
      tooltip: {
        trigger: 'item',
        triggerOn: 'mousemove'
      },
      series: [
        {
          type: 'tree',
          data: [treeData],
          top: '1%',
          left: '7%',
          bottom: '1%',
          right: '20%',
          symbolSize: 12,
          symbol: 'circle',
          orient: 'LR', // 从左到右
          expandAndCollapse: true,
          label: {
            position: 'left',
            verticalAlign: 'middle',
            align: 'right',
            fontSize: 12,
            backgroundColor: '#fff',
            padding: [2, 4],
            borderRadius: 4,
            borderWidth: 1,
            borderColor: '#ccc'
          },
          leaves: {
            label: {
              position: 'right',
              verticalAlign: 'middle',
              align: 'left'
            }
          },
          emphasis: {
            focus: 'descendant'
          },
          animationDuration: 500,
          animationDurationUpdate: 750
        }
      ]
    };
  });
</script>

<style lang="less" scoped>
  .tree-container {
    height: 600px;
    width: 100%;
  }

  .chart {
    height: 100%;
    width: 100%;
  }
</style>
