import { Component , AfterViewInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import Swiper from 'swiper';
import { Network, DataSet, Node, Edge } from 'vis-network/standalone';
// 扩展 Node 和 Edge 类型以支持自定义属性
interface CustomNode extends Node {
  details: string;
}
@Component({
  selector: 'app-tab1',
  templateUrl: './tab1.page.html',
  styleUrls: ['./tab1.page.scss'],
})

export class Tab1Page implements AfterViewInit{
  // 定义 slides 属性，数组中的每个对象代表一个轮播图项目
  slides = [
    { image: '/assets/images/slide1.jpg', title: 'Slide 1' },
    { image: '/assets/images/slide2.jpg', title: 'Slide 2' },
    { image: '/assets/images/slide3.jpg', title: 'Slide 3' },
    { image: '/assets/images/slide4.jpg', title: 'Slide 4' }
  ];
  selectedNodeDetails: string | null = null;
  position = { top: '100px', left: '100px' }; // 消息框初始位置
  isDragging = false;
  dragOffset = { x: 0, y: 0 };
  searchQuery: string = '';  // 搜索框的绑定变量
  searchResults: any[] = []; // 存放搜索结果的数组
  constructor(private http: HttpClient) {}
  navigateToLink() {
    // 替换为吉州窑小程序的实际链接
    console.log("吉州窑小程序")
  }
  
  ngAfterViewInit() {
    // 初始化 Swiper
    const swiper = new Swiper('.swiper-container', {
      autoplay: {
        delay: 3000,
        disableOnInteraction: false,
      },
      loop: true,
      pagination: {
        el: '.swiper-pagination',
        clickable: true,
      },
    });
    console.log('Swiper initialized');
    // 初始化知识图谱
    this.createGraph();
  }
  // 创建知识图谱的函数
  createGraph() {
    // 从 JSON 文件加载数据
    this.http.get('/assets/json/graph.json').subscribe({
      next: (data: any) => {
        // 使用 DataSet 包装数据
        const nodes = new DataSet<CustomNode>(data.nodes);
        const edges = new DataSet<Edge>(data.edges);
        // 获取容器
        const container = document.getElementById('graph-container') as HTMLElement;
        // 定义图表配置
        const options = {
          autoResize: true,
          height: '100%',
          width: '100%',
          nodes: {
            shape: 'circle',
            size: 12,
            color: {
              background: '#d7ccc8',
              border: '#6d4c41',
              highlight: {
                background: '#bcaaa4',
                border: '#5d4037',
              },
            },
            font: {
              size: 12,
              color: '#3e2723',
              face: 'serif',
            },
            borderWidth: 3,
            borderWidthSelected: 5,
          },
          edges: {
            width: 2,
            color: {
              color: '#795548',
              highlight: '#5d4037',
              hover: '#6d4c41',
            },
            font: {
              size: 14,
              color: '#5d4037',
              face: 'serif',
              align: 'middle',
            },
            smooth: {
              enabled: true,
              type: 'continuous',
              roundness: 0.3,
            },
            arrows: {
              to: {
                enabled: true,
                scaleFactor: 1.2,
                type: 'vee',
              },
            },
          },
          physics: {
            enabled: true,
            solver: 'forceAtlas2Based',
            barnesHut: {
              gravitationalConstant: -1500,
              centralGravity: 0.2,
              springLength: 100,
            },
          },
        };
        // 创建网络图
        const network = new Network(container, { nodes, edges }, options);
        // 点击事件：获取被点击节点的详细信息
        network.on('click', (event: { nodes: number[]; pointer: { DOM: { x: number; y: number } } }) => {
          if (event.nodes.length > 0) {
            const clickedNodeId = event.nodes[0]; // 获取点击的节点 ID
            const clickedNode = nodes.get(clickedNodeId); // 从 DataSet 中获取节点
            if (clickedNode) {
              this.selectedNodeDetails = clickedNode.details; // 获取节点的详细信息
              console.log(this.selectedNodeDetails);
              // 计算消息框的位置
              const containerRect = container.getBoundingClientRect();
              const clickX = Math.min(
                Math.max(event.pointer.DOM.x - containerRect.left, 0),
                containerRect.width - 300
              );
              const clickY = Math.min(
                Math.max(event.pointer.DOM.y - containerRect.top, 0),
                containerRect.height - 200
              );
              this.position = {
                top: `${clickY}px`,
                left: `${clickX}px`,
              };
            }
          }
        });
      },
      error: (err) => {
        console.error('Error loading graph data:', err);
      },
    });
  }
  // 关闭消息框
  closeMessageBox() {
    this.selectedNodeDetails = null;
  }
  // 处理搜索的函数
  onSearch() {
    if (this.searchQuery.trim() === '') {
      this.searchResults = [];
      return;
    }
  // 调用百度搜索
  this.fetchBaiduSearchResults(this.searchQuery);
  }
  // 使用百度搜索
  fetchBaiduSearchResults(query: string) {
    // 使用百度的搜索 URL
    const url = `http://localhost:3000/search?q=${encodeURIComponent(query)}`;
    const headers = new HttpHeaders({
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
      'Referer': 'https://www.baidu.com',
      'Accept-Language': 'zh-CN,zh;q=0.9',
      'Connection': 'keep-alive',
    });
    // 发起 HTTP 请求获取搜索结果（可以使用第三方代理来避免跨域问题）
    this.http.get(url, { responseType: 'text' }).subscribe(response => {
      // 处理搜索结果
      this.parseBaiduSearchResults(response);
      console.log(response)
    });
  }
  // 简单的解析百度搜索结果（这里只是展示了一个基础的解析方式）
  parseBaiduSearchResults(response: string) {
    // 通过正则解析百度返回的 HTML 获取搜索结果标题和链接
    const resultPattern = /<h3 class="t"><a href="([^"]+)"[^>]*>(.*?)<\/a><\/h3>/g;
    let match;
    const results = [];
    // 使用正则匹配搜索结果
    while ((match = resultPattern.exec(response)) !== null) {
      results.push({
        title: match[2],  // 搜索结果标题
        link: match[1],   // 搜索结果链接
      });
    }
    // 更新搜索结果数组
    this.searchResults = results;
  }
}
