<template>
  <div id="container"></div>
</template>

<script setup>
// 移除对Cache的导入
import * as echarts from "echarts"
import { nextTick, onMounted, ref, onUnmounted, watch } from "vue"
import { cropToCircleAsync } from "@/utils/transform"
import normalNodeIcon from "@/assets/images/icon/opinion-leader-normal-node.png"
import bridgeNodeHoverBgImg from "@/assets/images/bridge_node_hoverbgimg.png"

const emit = defineEmits(["handle:openDialog"])
const props = defineProps({
  timestamp: {
    type: Number,
    default: 0
  },
  allLeaderData: {
    type: Array,
    default: () => []
  }
})

// node1是Hu Xijin 胡锡进
const node1Followers = [
  { name: "Mohamed Rashid Osman", avatar: normalNodeIcon },
  { name: "🎗🇯🇵🇺🇸🇹🇼🇺🇦", avatar: normalNodeIcon },
  { name: "Alex kennedy", avatar: normalNodeIcon },
  { name: "A.Dagasan", avatar: normalNodeIcon },
  { name: "Denali Pac", avatar: normalNodeIcon },
  { name: "chillon musk", avatar: normalNodeIcon },
  { name: "Quantum ✝️🇲🇽🇺🇸", avatar: normalNodeIcon },
  { name: "The_Real_Fly", avatar: normalNodeIcon },
  { name: "Tarzan", avatar: normalNodeIcon },
  { name: "Brad Ellis", avatar: normalNodeIcon },
  { name: "🤷🏻\u200d♂️⚗️🧙🏻\u200d♂️", avatar: normalNodeIcon },
  { name: "NeverTweet", avatar: normalNodeIcon },
  { name: "EndGameWW3 🇺🇸", avatar: normalNodeIcon },
  { name: "CLG News🐻💤", avatar: normalNodeIcon },
  { name: "Chen Yunzheng", avatar: normalNodeIcon },
  { name: "predrxla", avatar: normalNodeIcon },
  { name: "Spencer Brown", avatar: normalNodeIcon },
  { name: "sanjeev prabhaker", avatar: normalNodeIcon },
  { name: "Dexian Wang", avatar: normalNodeIcon },
  { name: "Donkey Kong", avatar: normalNodeIcon }
]

// node2: Levi Godman 的邻居
const node2Followers = [
  { name: "Iván J RS ⚜️", avatar: normalNodeIcon },
  { name: "Анка-пулемётчица", avatar: normalNodeIcon },
  { name: "Patrick Maina45", avatar: normalNodeIcon },
  { name: "Polina Pomorenko", avatar: normalNodeIcon },
  { name: "Johanna deMartin", avatar: normalNodeIcon },
  { name: "MM🇮🇳❤", avatar: normalNodeIcon },
  { name: "Александр", avatar: normalNodeIcon },
  { name: "नरेन्द्र जोशी 🇮🇳", avatar: normalNodeIcon },
  { name: "Jimmy Loh", avatar: normalNodeIcon },
  { name: "Dziwaczny Andrzej🖤💛🤍", avatar: normalNodeIcon },
  { name: "R", avatar: normalNodeIcon },
  { name: "Ionel Paun", avatar: normalNodeIcon },
  { name: "Dziwaczny Andrzej🖤💛🤍", avatar: normalNodeIcon },
  { name: "R", avatar: normalNodeIcon },
  { name: "Ionel Paun", avatar: normalNodeIcon },
  { name: "Marwa Osman || مروة عثمان", avatar: normalNodeIcon },
  { name: "Terry Liu", avatar: normalNodeIcon },
  { name: "синие краски", avatar: normalNodeIcon },
  { name: "#historischerJesus", avatar: normalNodeIcon },
  { name: "Baron of the Taiga", avatar: normalNodeIcon },
  { name: "Pierre B 🧐", avatar: normalNodeIcon },
  { name: "Marquise de Belgrade", avatar: normalNodeIcon },
  { name: "R.J.", avatar: normalNodeIcon }
]

// node3:bidishalolo的邻居节点
const node3Followers = [
  { name: "Ron Gilbert", avatar: normalNodeIcon },
  { name: "Lord Jesus Christ/ Prophet / Michael David Boyles", avatar: normalNodeIcon },
  { name: "Giovana Du 🇵🇪🇨🇭❤️", avatar: normalNodeIcon },
  { name: "Zongduo WEN", avatar: normalNodeIcon },
  { name: "Sabin 月光蜥蜴 🌙🦎", avatar: normalNodeIcon },
  { name: "小瑷", avatar: normalNodeIcon },
  { name: "baptista89", avatar: normalNodeIcon },
  { name: "Lisa👠（互fo秒回）", avatar: normalNodeIcon },
  { name: "Elvis ❤️ Animals ❤️ MJ ❤️", avatar: normalNodeIcon },
  { name: "Real Talk With Josh", avatar: normalNodeIcon },
  { name: "Sally McCowan", avatar: normalNodeIcon },
  { name: "MEECH OUT 💥", avatar: normalNodeIcon },
  { name: "Arun", avatar: normalNodeIcon },
  { name: "🍀Michael Raveles🕊🏴🚩🍀🌹🌵🌹🌵🌹🌵", avatar: normalNodeIcon },
  { name: "Luciano Silva", avatar: normalNodeIcon },
  { name: "Maira Inderyas", avatar: normalNodeIcon },
  { name: "Tim talks stocks and corruption", avatar: normalNodeIcon },
  { name: "Po'Boys Podcast", avatar: normalNodeIcon },
  { name: "Thomas", avatar: normalNodeIcon },
  { name: "Rick Kinseth", avatar: normalNodeIcon }
]

// node4:Indo-Pacific News 的邻居节点
const node4Followers = [
  { name: "KoiN", avatar: normalNodeIcon },
  { name: "Vinod Kumar", avatar: normalNodeIcon },
  { name: "SKELETON", avatar: normalNodeIcon },
  { name: "Mein Senf 🇩🇪🥔 (misanthropisch gewürzt)", avatar: normalNodeIcon },
  { name: "Iskandar Evergarden", avatar: normalNodeIcon },
  { name: "シューター神", avatar: normalNodeIcon },
  { name: "喜井\u3000薫", avatar: normalNodeIcon },
  { name: "Ministry of Otaku @ Anime Matsuri 2022", avatar: normalNodeIcon },
  { name: "Ti Bolyn", avatar: normalNodeIcon },
  { name: "Anindya Banerjee... #savethesoil 🇮🇳🇮🇳🇮🇳", avatar: normalNodeIcon },
  { name: "🇲🇳🕊〽️🅾️♓️Г🪙🧲 🕊🇺🇦", avatar: normalNodeIcon },
  { name: "Elías Euceda", avatar: normalNodeIcon },
  { name: "the stranger", avatar: normalNodeIcon },
  { name: "Panthera Tigris aka Tiger", avatar: normalNodeIcon },
  { name: "Rajesh Pattnaik ରାଜେଶ 🇮🇳", avatar: normalNodeIcon },
  { name: "69th Booster Shot", avatar: normalNodeIcon },
  { name: "XxIndoAngelxX", avatar: normalNodeIcon },
  { name: "Judas", avatar: normalNodeIcon },
  { name: "Make America Grunge🐸 Again", avatar: normalNodeIcon },
  { name: "Pankaj DP 🇮🇳", avatar: normalNodeIcon }
]

// node5: The Spectator Index的邻居节点
const node5Followers = [
  { name: "Un Corsaithe Jèrriais 🌸🇯🇪", avatar: normalNodeIcon },
  { name: "KokoCat", avatar: normalNodeIcon },
  { name: "penny collenette", avatar: normalNodeIcon },
  { name: "𝐝𝐨𝐧.𝐲𝐚𝐭𝐨𝐫", avatar: normalNodeIcon },
  { name: "🇺🇦Michael Kraft 🤯 Brainblow Warrior", avatar: normalNodeIcon },
  { name: "🍁RASTA MAN™🍁", avatar: normalNodeIcon },
  { name: "Pacifia💙", avatar: normalNodeIcon },
  { name: "Dowager Countess of Pirara", avatar: normalNodeIcon },
  { name: "Gipingers", avatar: normalNodeIcon },
  { name: "Saad", avatar: normalNodeIcon },
  { name: "Maarten Boone 🇪🇺🇺🇦", avatar: normalNodeIcon },
  { name: "funny", avatar: normalNodeIcon },
  { name: "KIONGOS UBL.", avatar: normalNodeIcon },
  { name: "sofia of sapphos", avatar: normalNodeIcon },
  { name: "T💜", avatar: normalNodeIcon },
  { name: "Gibby", avatar: normalNodeIcon },
  { name: "とりあえず..", avatar: normalNodeIcon },
  { name: "🏄\u200d♂️", avatar: normalNodeIcon },
  { name: "Kamila Dias", avatar: normalNodeIcon },
  { name: "Luna 🇵🇭", avatar: normalNodeIcon }
]

// node6: Reuters 的邻居节点
const node6Followers = [
  { name: "Bartlomiej Baudler", avatar: normalNodeIcon },
  { name: "ぼくはこへいた", avatar: normalNodeIcon },
  { name: "hyphee3030", avatar: normalNodeIcon },
  { name: "Harry", avatar: normalNodeIcon },
  { name: "ChristianHCooper.eth", avatar: normalNodeIcon },
  { name: "René Fernández", avatar: normalNodeIcon },
  { name: "forrikimaru_huaili", avatar: normalNodeIcon },
  { name: "Andi LI", avatar: normalNodeIcon },
  { name: "Siya", avatar: normalNodeIcon },
  { name: "Atish Dhale", avatar: normalNodeIcon },
  { name: "Angel Miguel 🇵🇾", avatar: normalNodeIcon },
  { name: "Daniel William Temov", avatar: normalNodeIcon },
  { name: "Mark Huang", avatar: normalNodeIcon },
  { name: "jerry", avatar: normalNodeIcon },
  { name: "Ernest", avatar: normalNodeIcon },
  { name: "ByronKAdamsX", avatar: normalNodeIcon },
  { name: "diana duran", avatar: normalNodeIcon },
  { name: "Robert Carl", avatar: normalNodeIcon },
  { name: "Intel Bkchor", avatar: normalNodeIcon },
  { name: "Justina", avatar: normalNodeIcon }
]

// node7: Mick Wallace的邻居节点
const node7Followers = [
  { name: "季艾欧", avatar: normalNodeIcon },
  { name: "宁爸", avatar: normalNodeIcon },
  { name: "Khizar Riaz Tanoli", avatar: normalNodeIcon },
  { name: "wooya", avatar: normalNodeIcon },
  { name: "Fathimah Qudse", avatar: normalNodeIcon },
  { name: "mike wood", avatar: normalNodeIcon },
  { name: "Ruby", avatar: normalNodeIcon },
  { name: "Anand Augustine Davison", avatar: normalNodeIcon },
  { name: "sseassonal", avatar: normalNodeIcon },
  { name: "It's Khan", avatar: normalNodeIcon },
  { name: "Faisal", avatar: normalNodeIcon },
  { name: "Peace sells", avatar: normalNodeIcon },
  { name: "Nishan Shan", avatar: normalNodeIcon },
  { name: "Jason", avatar: normalNodeIcon },
  { name: "فايز", avatar: normalNodeIcon },
  { name: "Rudolf", avatar: normalNodeIcon },
  { name: "qeveref", avatar: normalNodeIcon },
  { name: "Lee Sze Yuan", avatar: normalNodeIcon },
  { name: "NP", avatar: normalNodeIcon },
  { name: "🚩Ириска☭🦊🚩", avatar: normalNodeIcon }
]

// node8:Jiushiniya的邻居节点
const node8Followers = [
  { name: "Hello", avatar: normalNodeIcon },
  { name: "水明🇺🇸", avatar: normalNodeIcon },
  { name: "雪线飞音符", avatar: normalNodeIcon },
  { name: "Namzes", avatar: normalNodeIcon },
  { name: "Linda", avatar: normalNodeIcon },
  { name: "喵酱", avatar: normalNodeIcon },
  { name: "Dorie", avatar: normalNodeIcon },
  { name: "Allison 🕊", avatar: normalNodeIcon },
  { name: "Alice Cochrane", avatar: normalNodeIcon },
  { name: "Miguel Almeida", avatar: normalNodeIcon },
  { name: "尼亚加拉的蓝鸟-2Nnorthbluebird", avatar: normalNodeIcon },
  { name: "Joel Nsheijjah", avatar: normalNodeIcon },
  { name: "Alizeh A", avatar: normalNodeIcon },
  { name: "黄彬", avatar: normalNodeIcon },
  { name: "Jeff Ray", avatar: normalNodeIcon },
  { name: "Steven Sun", avatar: normalNodeIcon },
  { name: "Morin", avatar: normalNodeIcon },
  { name: "MReadY", avatar: normalNodeIcon },
  { name: "politician general", avatar: normalNodeIcon },
  { name: "mingPi588", avatar: normalNodeIcon }
]

// node9: 刘晓明的邻居节点
const node9Followers = [
  { name: "Emmy🌸互fo🌸", avatar: normalNodeIcon },
  { name: "深红爱国同盟🇨🇳", avatar: normalNodeIcon },
  { name: "Putin Huylo 🇺🇸🇺🇦", avatar: normalNodeIcon },
  { name: "蘸星光💞", avatar: normalNodeIcon },
  { name: "iLingcheng", avatar: normalNodeIcon },
  { name: "福嘟嘟(互fo)", avatar: normalNodeIcon },
  { name: "Kaming_MTL 枫子🇨🇦 🔥 🇨🇦", avatar: normalNodeIcon },
  { name: "Dyfao6", avatar: normalNodeIcon },
  { name: "DENABE", avatar: normalNodeIcon },
  { name: "idav", avatar: normalNodeIcon },
  { name: "陈晨", avatar: normalNodeIcon },
  { name: "de meowmeow", avatar: normalNodeIcon },
  { name: "Keilani", avatar: normalNodeIcon },
  { name: "斗之志1987", avatar: normalNodeIcon },
  { name: "Christian 老煙槍", avatar: normalNodeIcon },
  { name: "Zedekiyah", avatar: normalNodeIcon },
  { name: "JSH", avatar: normalNodeIcon },
  { name: "Andrés", avatar: normalNodeIcon },
  { name: "zhenyuanjia", avatar: normalNodeIcon },
  { name: "Beyea", avatar: normalNodeIcon }
]

// node10:indobosss的邻居节点
const node10Followers = [
  { name: "Grag Lee", avatar: normalNodeIcon },
  { name: "吴润林", avatar: normalNodeIcon },
  { name: "李龙", avatar: normalNodeIcon },
  { name: "SHAUN AJ RAMMUTLA", avatar: normalNodeIcon },
  { name: "Arsalan Khan", avatar: normalNodeIcon },
  { name: "亚特兰太", avatar: normalNodeIcon },
  { name: "Simon Wright", avatar: normalNodeIcon },
  { name: "ThanhBG888", avatar: normalNodeIcon },
  { name: "梦 嫣 是 我 🌈 ❤️", avatar: normalNodeIcon },
  { name: "Richard Paddington", avatar: normalNodeIcon },
  { name: "Koyo_Cabe", avatar: normalNodeIcon },
  { name: "Sir Tech", avatar: normalNodeIcon },
  { name: "Gábor Lukács", avatar: normalNodeIcon },
  { name: "Michael Schneider 🇩🇪 ☮️", avatar: normalNodeIcon },
  { name: "FrozenKK", avatar: normalNodeIcon },
  { name: "Dodi Banzon", avatar: normalNodeIcon },
  { name: "Hsih Hsiu Ling 🐓", avatar: normalNodeIcon },
  { name: "Meiguolao Watcher ☭", avatar: normalNodeIcon },
  { name: "Ryan Bridges", avatar: normalNodeIcon },
  { name: "Elia Bescotti", avatar: normalNodeIcon }
]

const allLeaderData = ref(props.allLeaderData)
let chart = null
const allGraphData = ref({ nodes: [], edges: [] })
const selectedLeaderId = ref(null)

// 创建一个映射数组作为内存缓存
const avatarCacheMap = ref(new Map())

// 修改getCircleAvatar函数，使用映射数组缓存
const getCircleAvatar = async (avatarUrl) => {
  // 使用映射数组检查缓存
  if (avatarCacheMap.value.has(avatarUrl)) {
    return avatarCacheMap.value.get(avatarUrl)
  }
  const base64 = await cropToCircleAsync(avatarUrl)
  // 存储到映射数组中
  avatarCacheMap.value.set(avatarUrl, base64)
  return base64
}

// 修改初始化所有节点和边的函数
const initAllGraphData = async () => {
  const nodes = []
  const edges = []
  // 创建一个Map用于存储已存在的节点名称，用于去重
  const existingNodes = new Map()

  // 创建一个映射，将意见领袖索引与对应的邻居节点数组关联起来
  const leaderFollowersMap = [
    node1Followers, // 第1个意见领袖的邻居节点
    node2Followers, // 第2个意见领袖的邻居节点
    node3Followers, // 第3个意见领袖的邻居节点
    node4Followers, // 第4个意见领袖的邻居节点
    node5Followers, // 第5个意见领袖的邻居节点
    node6Followers, // 第6个意见领袖的邻居节点
    node7Followers, // 第7个意见领袖的邻居节点
    node8Followers, // 第8个意见领袖的邻居节点
    node9Followers, // 第9个意见领袖的邻居节点
    node10Followers // 第10个意见领袖的邻居节点
  ]

  // 添加意见领袖节点
  for (const [leaderIndex, leader] of allLeaderData.value.entries()) {
    const avatar = await getCircleAvatar(leader.default_avatar)
    const leaderNode = {
      id: leader.id,
      name: leader.name,
      symbol: `image://${avatar}`,
      symbolSize: 80,
      category: 0,
      value: leader.followers,
      leaderOriginInfo: leader,
      label: { show: false }
    }
    nodes.push(leaderNode)
    existingNodes.set(leader.name, leader.id)

    // 为当前意见领袖节点添加对应的邻居节点
    if (leaderIndex < leaderFollowersMap.length) {
      const followers = leaderFollowersMap[leaderIndex]

      for (const [followerIndex, followerData] of followers.entries()) {
        const followerName = followerData.name

        // 检查节点是否已存在
        if (existingNodes.has(followerName)) {
          // 如果节点已存在，只创建边，不重复添加节点
          const existingNodeId = existingNodes.get(followerName)
          edges.push({
            source: leader.id,
            target: existingNodeId
          })
          continue
        }

        // 如果节点不存在，创建新节点和边
        const userId = `user_${leader.id}_${followerIndex}`

        try {
          const followerAvatar = await getCircleAvatar(followerData.avatar || normalNodeIcon)

          const followerNode = {
            id: userId,
            name: followerName,
            symbol: `image://${followerAvatar}`,
            symbolSize: 25,
            category: 1,
            value: "",
            label: { show: false }
          }

          nodes.push(followerNode)
          existingNodes.set(followerName, userId)

          // 创建从意见领袖到邻居节点的边
          edges.push({
            source: leader.id,
            target: userId
          })
        } catch (error) {
          // 即使头像处理失败，也添加节点（使用默认样式）
          const followerNode = {
            id: userId,
            name: followerName,
            symbol: "circle",
            symbolSize: 25,
            category: 1,
            value: "",
            label: { show: false },
            itemStyle: {
              color: {
                type: "linear",
                colorStops: [
                  { offset: 0, color: "#035e96" },
                  { offset: 1, color: "#34a7b0" }
                ]
              }
            }
          }

          nodes.push(followerNode)
          existingNodes.set(followerName, userId)

          // 创建从意见领袖到邻居节点的边
          edges.push({
            source: leader.id,
            target: userId
          })
        }
      }
    }
  }

  // 添加随机连边
  // 1. 生成意见领袖之间的连边（增加边数，提高网络密度）
  const leaderNodes = nodes.filter((node) => node.category === 0)
  const totalLeaders = leaderNodes.length
  const leaderEdgesToAdd = Math.max(10, Math.floor(totalLeaders * 0.2 * totalLeaders))

  // 存储已存在的边，避免重复
  const existingEdgeMap = new Set()
  edges.forEach((edge) => {
    existingEdgeMap.add(`${edge.source}_${edge.target}`)
    existingEdgeMap.add(`${edge.target}_${edge.source}`)
  })

  // 添加意见领袖之间的随机边
  for (let i = 0; i < leaderEdgesToAdd; i++) {
    const randomLeader1 = leaderNodes[Math.floor(Math.random() * totalLeaders)]
    let randomLeader2 = leaderNodes[Math.floor(Math.random() * totalLeaders)]

    // 确保不是同一个节点，且边不存在
    while (
      randomLeader1.id === randomLeader2.id ||
      existingEdgeMap.has(`${randomLeader1.id}_${randomLeader2.id}`)
    ) {
      randomLeader2 = leaderNodes[Math.floor(Math.random() * totalLeaders)]
    }

    edges.push({
      source: randomLeader1.id,
      target: randomLeader2.id
    })
    existingEdgeMap.add(`${randomLeader1.id}_${randomLeader2.id}`)
    existingEdgeMap.add(`${randomLeader2.id}_${randomLeader1.id}`)
  }

  // 2. 生成意见领袖与其他领袖的邻居节点之间的连边（大幅增加边数）
  const allUsers = nodes.filter((node) => node.category === 1)
  const totalUsers = allUsers.length
  const userLeaderEdgesToAdd = Math.max(50, Math.floor(totalUsers * 0.15))

  for (let i = 0; i < userLeaderEdgesToAdd; i++) {
    const randomUser = allUsers[Math.floor(Math.random() * totalUsers)]
    const randomLeader = leaderNodes[Math.floor(Math.random() * totalLeaders)]

    // 确保用户不是领袖的直接关注者，且边不存在
    if (
      !randomUser.id.includes(randomLeader.id) &&
      !existingEdgeMap.has(`${randomUser.id}_${randomLeader.id}`)
    ) {
      edges.push({
        source: randomLeader.id,
        target: randomUser.id
      })
      existingEdgeMap.add(`${randomUser.id}_${randomLeader.id}`)
      existingEdgeMap.add(`${randomLeader.id}_${randomUser.id}`)
    }
  }

  // 3. 生成不同领袖的邻居节点之间的连边（大幅增加边数）
  const userUserEdgesToAdd = Math.max(100, Math.floor(totalUsers * 0.2))

  for (let i = 0; i < userUserEdgesToAdd; i++) {
    const randomUser1 = allUsers[Math.floor(Math.random() * totalUsers)]
    let randomUser2 = allUsers[Math.floor(Math.random() * totalUsers)]

    // 确保不是同一个节点，不是来自同一个领袖，且边不存在
    while (
      randomUser1.id === randomUser2.id ||
      randomUser1.id.split("_")[1] === randomUser2.id.split("_")[1] ||
      existingEdgeMap.has(`${randomUser1.id}_${randomUser2.id}`)
    ) {
      randomUser2 = allUsers[Math.floor(Math.random() * totalUsers)]
    }

    edges.push({
      source: randomUser1.id,
      target: randomUser2.id
    })
    existingEdgeMap.add(`${randomUser1.id}_${randomUser2.id}`)
    existingEdgeMap.add(`${randomUser2.id}_${randomUser1.id}`)
  }

  allGraphData.value = { nodes, edges }
}

// 根据timestamp筛选要显示的节点和边 和散点
const getVisibleGraphData = () => {
  const leaders = allLeaderData.value.slice(0, props.timestamp)
  const leaderIds = new Set(leaders.map((l) => l.id))
  const nodes = []
  const edges = []
  for (const node of allGraphData.value.nodes) {
    let shouldShow = false
    // console.log('Node ID 类型:', typeof node.id, '值:', node.id);
    if (leaderIds.has(node.id) || node.id.startsWith("user_splattering_")) {
      shouldShow = true
    } else if (node.id.startsWith("user_")) {
      const parts = node.id.split("_")
      // Correctly handle parent IDs that contain underscores (e.g., 'levi_godman')
      const parentId = parts.slice(1, parts.length - 1).join("_")
      if (leaderIds.has(parentId)) {
        shouldShow = true
      }
    }

    if (shouldShow) {
      nodes.push(node)
    }
  }
  for (const edge of allGraphData.value.edges) {
    if (leaderIds.has(edge.source)) {
      edges.push(edge)
    }
  }
  return { nodes, edges }
}

const renderChart = () => {
  if (!chart) {
    chart = echarts.init(document.getElementById("container"))
  }
  const { nodes, edges } = getVisibleGraphData()
  const option = {
    tooltip: {
      trigger: "item",
      backgroundColor: "rgba(0,0,0,0)", // 透明背景
      borderColor: "rgba(0,0,0,0)", // 透明边框
      borderWidth: 0,
      extraCssText: "box-shadow:none;padding:0;",
      textStyle: {
        color: "#fff", // 设置字体颜色为白色
        fontSize: 14
      },
      formatter: (params) => {
        // 如果是边，则不显示提示框
        if (params.dataType === "edge") {
          return ""
        }
        if (params.data.category === 0) {
          return `
          <div
          style = "
            border-radius: 4px;
            background: url('${bridgeNodeHoverBgImg}');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            padding: 10px;
            justify-content: center;
            flex-direction: column;
          ">
            <div style="color:#fff;letter-spacing: 0.14px;">
              用户名:&nbsp;${params.data.name}<br/>

            </div>
            <div style="color:#fff;letter-spacing: 0.14px;">
              粉丝数:&nbsp;${params.data.value}
            </div>
          </div>`
        }
        return `
        <div
        style = "
        padding: 10px;
          border-radius: 4px;
          background: url('${bridgeNodeHoverBgImg}');
          background-size: cover;
          background-position: center;
          background-repeat: no-repeat;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-direction: column;
        ">
          <div style="color:#fff;letter-spacing: 0.14px;">
            用户名:&nbsp;${params.data.name}
          </div>
        </div>
        `
      }
    },
    legend: [
      {
        data: [
          {
            name: "意见领袖",
            icon: "circle",
            itemStyle: {
              color: new echarts.graphic.RadialGradient(0.98, 0.38, 0.9, [
                { offset: 1, color: "#4FAAD3" },
                { offset: 0.5, color: "#4FAAD3" },
                { offset: 0, color: "#4FAAD3" }
              ]),
              borderColor: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                { offset: 0, color: "rgba( 57,102,129,1)" },
                { offset: 1, color: "rgba( 57,102,129,1)" }
              ]),
              borderWidth: 3
            }
          },
          {
            name: "普通用户",
            icon: "circle",
            itemStyle: {
              // 使用与普通用户节点相同的径向渐变背景
              color: new echarts.graphic.RadialGradient(0.98, 0.38, 0.9, [
                { offset: 1, color: "#235D94" },
                { offset: 0.5, color: "#266B8F" },
                { offset: 0, color: "#56ABB2" }
              ]),
              // 使用与普通用户节点相同的边框样式
              borderColor: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                { offset: 0, color: "rgba(42,185,254,1)" },
                { offset: 1, color: "rgba(82,255,243,1)" }
              ]),
              borderWidth: 1
            }
          }
        ],
        right: 22,
        bottom: 20,
        icon: "circle",
        orient: "vertical",
        itemWidth: 16,
        itemHeight: 16,
        itemGap: 12,
        backgroundColor: "rgba(0,67,125,0.56)", // 半透明深蓝
        borderRadius: 8, // 圆角
        borderColor: "#c2f2ff", // 淡蓝色边框
        borderWidth: 0.3,
        padding: [12, 20, 12, 20], // 上右下左
        textStyle: {
          color: "#fff",
          fontSize: 16,
          fontWeight: "normal"
        }
      }
    ],
    series: [
      {
        type: "graph",
        layout: "force",
        roam: true,
        draggable: true,
        data: nodes.map((node) => {
          let symbol = node.symbol
          if (node.category === 0) {
            // 选中时用高亮头像，否则用普通头像
            symbol =
              selectedLeaderId.value === node.id
                ? `image://${node.leaderOriginInfo.active_avatar}`
                : `image://${node.leaderOriginInfo.default_avatar}`
          } else {
            // 普通用户节点使用圆形
            symbol = "circle"
          }

          // 设置普通用户节点的样式
          const baseStyle = {
            ...node,
            symbol,
            symbolKeepAspect: true
          }

          if (node.category === 1) {
            // 普通用户节点的样式
            baseStyle.itemStyle = {
              ...node.itemStyle,
              // 圆形背景色（使用ECharts的径向渐变配置）
              color: new echarts.graphic.RadialGradient(0.98, 0.38, 0.9, [
                { offset: 1, color: "#235D94" }, // 最左侧
                { offset: 0.5, color: "#266B8F" }, // 中间
                { offset: 0, color: "#56ABB2" } // 最右侧
              ]),
              // 边框样式（使用ECharts的线性渐变配置）
              borderColor: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                { offset: 0, color: "rgba(42,185,254,1)" },
                { offset: 1, color: "rgba(82,255,243,1)" }
              ]),
              borderWidth: 1,
              borderType: "solid"
            }
            baseStyle.emphasis = {
              itemStyle: {
                // 悬停时的样式
                shadowBlur: 20,
                shadowColor: "#c4a651",
                borderColor: "#fcd267",
                borderWidth: 2,
                borderType: "solid",
                // 悬停时的背景渐变
                color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                  { offset: 0, color: "rgba(0,157,255,1)" },
                  { offset: 1, color: "rgba(0,255,242,1)" }
                ])
              }
            }
          } else {
            // 意见领袖节点保持原有样式
            baseStyle.itemStyle = {
              ...node.itemStyle,
              shadowBlur: 10,
              shadowColor: "rgba(0,207,255,0.5)",
              borderWidth: 1,
              borderColor: "#32c6fc"
            }
            baseStyle.emphasis = {
              itemStyle: {
                shadowBlur: 20,
                shadowColor: "#c4a651",
                borderColor: "#fcd267",
                borderWidth: node.category === 0 ? 10 : 2,
                borderType: "solid"
              }
            }
          }

          return baseStyle
        }),
        links: edges,
        categories: [{ name: "意见领袖" }, { name: "普通用户" }],
        force: {
          // 增加排斥力使节点更分散
          repulsion: 300,
          // 增加边长度使节点间距更大
          edgeLength: 120,
          // 添加引力使整体布局更紧凑有序
          gravity: 0.1,
          // 开启动画使布局变化更平滑
          layoutAnimation: true,
          // 调整摩擦系数控制节点速度
          friction: 0.6
        },
        label: {
          position: "center"
        },
        // 添加以下配置让边连接到节点的边上而不是中心
        lineStyle: {
          curveness: 0, // 曲线弧度，0为直线
          type: "solid",
          width: 1.5,
          color: "#80c3ff",
          opacity: 0.5
        }
      }
    ]
  }
  chart.setOption(option)
}
const handleClickNode = () => {
  chart.on("click", (params) => {
    if (params.data && params.data.category === 0) {
      selectedLeaderId.value = params.data.id
      renderChart()
      emit("handle:openDialog", params.data)
    }
  })
}
// 监听窗口大小变化，重置图表
const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}
//echarts自适应方法
const resizeChart = () => {
  window.removeEventListener("resize", handleResize) //先移除旧的监听
  window.addEventListener("resize", handleResize)
}

onUnmounted(() => {
  window.removeEventListener("resize", handleResize)
  if (chart) {
    chart.dispose()
  }
})

onMounted(async () => {
  await nextTick()
  await initAllGraphData()
  renderChart()
  handleClickNode()
  resizeChart()
})

watch(
  () => props.timestamp,
  () => {
    renderChart()
  }
)

// 暴露 chart 实例或自定义方法
defineExpose({
  chart, // 直接暴露 chart 实例
  // 或者暴露自定义方法
  highlightNode(leaderId) {
    if (chart) {
      selectedLeaderId.value = leaderId
      renderChart()
    }
  }
})
</script>

<style scoped>
#container {
  width: 100%;
  height: 91%;
  backdrop-filter: blur(5px);
}
</style>
