import { Component, AfterViewInit, ViewChild, ElementRef, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import * as echarts from 'echarts';

@Component({
  selector: 'app-page-association',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './page-association.html',
  styleUrls: ['./page-association.scss']
})
export class PageAssociation implements AfterViewInit, OnDestroy {
  @ViewChild('orgChart') orgChartElement!: ElementRef;
  @ViewChild('academicCalendar') academicCalendarElement!: ElementRef;

  // 课程数据
  courses = [
    { 
      title: '江西古建筑数字化保护', 
      description: '学习古建筑三维扫描、数字建模与修复技术',
      duration: '32课时',
      students: '1,245人',
      imageUrl: 'public/images/jianzu.jpg'
    },
    { 
      title: '非遗技艺数字化传承', 
      description: '探索传统技艺的数字化记录与创新应用',
      duration: '24课时',
      students: '986人',
      imageUrl: 'public/images/wenhua.jpg'
    },
    { 
      title: '红色文化XR应用开发', 
      description: '利用XR技术重现江西革命历史场景',
      duration: '40课时',
      students: '1,532人',
      imageUrl: 'public/images/hongse.jpg'
    },
    { 
      title: '智慧旅游系统设计', 
      description: '学习旅游动线策划与智能导览系统开发',
      duration: '28课时',
      students: '875人',
      imageUrl: 'public/images/lvyou.jpg'
    }
  ];

  // 用于存储销毁钩子
  private destroyHooks: (() => void)[] = [];

  ngAfterViewInit(): void {
    this.initOrgChart();
    this.initAcademicCalendar();
  }

  initOrgChart(): void {
    const orgChart = echarts.init(this.orgChartElement.nativeElement);
    orgChart.setOption({
      tooltip: {
        trigger: 'item',
        triggerOn: 'mousemove'
      },
      series: [
        {
          type: 'tree',
          data: [{
            name: '协会主席',
            children: [{
              name: '常务副主席',
              children: [
                { name: '会员服务部' },
                { name: '人才培养部' }
              ]
            }, {
              name: '秘书长',
              children: [
                { name: '技术研发中心' },
                { name: '平台建设部' }
              ]
            }, {
              name: '学术委员会',
              children: [
                { name: '红色文化研究所' },
                { name: '非遗研究中心' },
                { name: '数字技术实验室' }
              ]
            }]
          }],
          top: '5%',
          left: '10%',
          bottom: '5%',
          right: '20%',
          symbolSize: 20,
          symbol: 'circle',
          orient: 'vertical',
          expandAndCollapse: true,
          initialTreeDepth: 2,
          lineStyle: {
            width: 2,
            color: '#8B4513'
          },
          label: {
            position: 'top',
            verticalAlign: 'middle',
            align: 'middle',
            fontSize: 14,
            fontWeight: 'bold',
            color: '#8B4513'
          },
          itemStyle: {
            color: '#DEB887',
            borderColor: '#8B4513',
            borderWidth: 2
          },
          emphasis: {
            itemStyle: {
              color: '#e8c34d',
              borderColor: '#8B4513'
            }
          },
          leaves: {
            label: {
              position: 'right',
              verticalAlign: 'middle',
              align: 'left'
            },
            itemStyle: {
              color: '#f0e6d2',
              borderColor: '#8B4513'
            }
          }
        }
      ]
    });
    
    // 监听窗口大小变化，重绘图表
    const resizeHandler = () => orgChart.resize();
    window.addEventListener('resize', resizeHandler);
    
    // 添加销毁钩子
    this.addDestroyHook(() => {
      window.removeEventListener('resize', resizeHandler);
      orgChart.dispose();
    });
  }

  initAcademicCalendar(): void {
    const academicCalendar = echarts.init(this.academicCalendarElement.nativeElement);
    
    // 学术活动数据
    const calendarData = [
      { date: '2023-06-05', value: 35, event: '数字文化论坛', location: '南昌' },
      { date: '2023-06-08', value: 65, event: '非遗保护研讨会', location: '景德镇' },
      { date: '2023-06-12', value: 45, event: '青年学者交流会', location: '九江' },
      { date: '2023-06-15', value: 85, event: '红色文化数字展', location: '井冈山' },
      { date: '2023-06-18', value: 25, event: '会员技术培训', location: '赣州' },
      { date: '2023-06-22', value: 75, event: '数字艺术创作大赛', location: '南昌' },
      { date: '2023-06-25', value: 55, event: '智慧旅游研讨会', location: '上饶' },
      { date: '2023-06-28', value: 95, event: '年度学术大会', location: '南昌' }
    ];

    academicCalendar.setOption({
      tooltip: {
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        borderColor: '#8B4513',
        borderWidth: 1,
        textStyle: {
          color: '#333',
          fontFamily: 'Microsoft YaHei'
        },
        formatter: function(params: any) {
          const dataItem = calendarData[params.dataIndex];
          return `<div style="font-weight: bold; color: #8B4513;">${dataItem.event}</div>
                  <div>日期: ${dataItem.date}</div>
                  <div>热度: ${dataItem.value}</div>
                  <div>地点: ${dataItem.location}</div>`;
        }
      },
      visualMap: {
        show: true,
        type: 'continuous',
        min: 0,
        max: 100,
        orient: 'horizontal',
        left: 'center',
        bottom: 10,
        text: ['高', '低'],
        textStyle: {
          color: '#8B4513'
        },
        inRange: {
          color: ['#f0e6d2', '#DEB887', '#A0522D', '#8B4513']
        }
      },
      calendar: {
        top: 30,
        left: 30,
        right: 30,
        bottom: 60, // 为视觉映射留出空间
        cellSize: ['auto', 25],
        range: '2023-06',
        itemStyle: {
          borderWidth: 1,
          borderColor: '#e8e0d0'
        },
        dayLabel: {
          color: '#8B4513',
          fontSize: 12
        },
        monthLabel: {
          color: '#8B4513',
          fontWeight: 'bold',
          fontSize: 14
        },
        yearLabel: { show: false }
      },
      series: {
        type: 'heatmap',
        coordinateSystem: 'calendar',
        data: calendarData.map(item => [item.date, item.value]),
        label: {
          show: false
        },
        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        }
      }
    });
    
    // 监听窗口大小变化，重绘图表
    const resizeHandler = () => academicCalendar.resize();
    window.addEventListener('resize', resizeHandler);
    
    // 添加销毁钩子
    this.addDestroyHook(() => {
      window.removeEventListener('resize', resizeHandler);
      academicCalendar.dispose();
    });
  }

  highlightSearch(searchTerm: string): void {
    if (searchTerm) {
      const content = document.querySelector('.constitution-content');
      if (content) {
        const text = content.innerHTML;
        const regex = new RegExp(searchTerm, 'gi');
        const highlighted = text.replace(regex, match => 
          `<span class="highlight">${match}</span>`
        );
        content.innerHTML = highlighted;
      }
    }
  }

  highlightVersion(event: MouseEvent, type: 'diff' | 'new'): void {
    const elements = document.querySelectorAll(`.${type}-highlight`);
    elements.forEach(el => {
      el.classList.add('active-highlight');
    });
    
    const handler = () => {
      elements.forEach(el => {
        el.classList.remove('active-highlight');
      });
      document.removeEventListener('mouseup', handler);
    };
    
    document.addEventListener('mouseup', handler);
  }

  // 添加销毁钩子函数
  private addDestroyHook(hook: () => void) {
    this.destroyHooks.push(hook);
  }

  // 组件销毁时执行所有钩子
  ngOnDestroy() {
    this.destroyHooks.forEach(hook => hook());
  }
}