import { router } from '@kit.ArkUI';
import settingsService from '../common/SettingsService';
import logManager, { LogCategory, LogEventType } from '../common/logtext';

// 粒子信息类型
class ParticleInfo {
  x: number = 0;
  y: number = 0;
  size: number = 0;
  opacity: number = 0;
  speed: number = 0;
  color: string = '#ffffff';
  
  constructor(x: number = 0, 
              y: number = 0, 
              size: number = 0, 
              opacity: number = 0, 
              speed: number = 0, 
              color: string = '#ffffff') {
    this.x = x;
    this.y = y;
    this.size = size;
    this.opacity = opacity;
    this.speed = speed;
    this.color = color;
  }
}

@Entry
@Component
struct TransitionPage {
  @State userName: string = '';
  @State welcomeMessage: string = '欢迎使用智慧教室管理系统';
  @State contentOpacity: number = 0;
  @State scaleValue: number = 0.8;
  @State rotationAngle: number = -10;
  @State translateYValue: number = 100;
  
  // 为粒子动画定义状态
  @State particles: ParticleInfo[] = [];
  private particleCount: number = 30; // 降低粒子数量避免性能问题
  private particleTimer: number = 0;
  private bgColorStop: number = 0;
  @State backgroundGradient: string = 'linear-gradient(45deg, #4c71f2, #42a7f0)';
  
  // 创建粒子
  private createParticles() {
    let newParticles: ParticleInfo[] = [];
    for (let i = 0; i < this.particleCount; i++) {
      let particle = new ParticleInfo(
        Math.random() * 100,        // x位置 (百分比)
        Math.random() * 100,        // y位置 (百分比)
        Math.random() * 8 + 2,      // 粒子大小
        Math.random() * 0.6 + 0.1,  // 初始透明度
        Math.random() * 0.5 + 0.1,  // 移动速度
        i % 3 === 0 ? '#ffffff' : (i % 3 === 1 ? '#aaccff' : '#77aaff') // 随机颜色
      );
      newParticles.push(particle);
    }
    this.particles = newParticles;
  }
  
  // 更新粒子动画
  private updateParticles() {
    this.particleTimer = setInterval(() => {
      let updatedParticles: ParticleInfo[] = [];
      
      for (let i = 0; i < this.particles.length; i++) {
        let p = this.particles[i];
        // 更新位置
        let newY = p.y - p.speed;
        if (newY < -5) {
          newY = 105; // 当粒子移出屏幕顶部时，从底部重新进入
          p.x = Math.random() * 100;
        }
        
        let newOpacity = p.opacity + (Math.random() * 0.1 - 0.05);
        // 确保透明度在合理范围内
        if (newOpacity < 0.1) newOpacity = 0.1;
        if (newOpacity > 0.8) newOpacity = 0.8;
        
        // 创建更新后的粒子对象
        let updatedParticle = new ParticleInfo(
          p.x,
          newY,
          p.size,
          newOpacity,
          p.speed,
          p.color
        );
        
        updatedParticles.push(updatedParticle);
      }
      
      this.particles = updatedParticles;
      
      // 更新背景渐变
      this.bgColorStop = (this.bgColorStop + 0.005) % 1;
      const hue1 = Math.floor((220 + Math.sin(this.bgColorStop * Math.PI * 2) * 20) % 360);
      const hue2 = Math.floor((190 + Math.cos(this.bgColorStop * Math.PI * 2) * 20) % 360);
      this.backgroundGradient = `linear-gradient(45deg, hsl(${hue1}, 70%, 60%), hsl(${hue2}, 70%, 60%))`;
      
    }, 50);
  }
  
  aboutToAppear() {
    // 设置用户名称
    this.userName = settingsService.getUserNickname();
    
    // 创建并开始粒子动画
    this.createParticles();
    this.updateParticles();
    
    // 第一阶段动画：元素进入
    animateTo({ duration: 1000, curve: Curve.Ease }, () => {
      this.contentOpacity = 1;
      this.scaleValue = 1;
      this.rotationAngle = 0;
      this.translateYValue = 0;
    });
    
    // 3秒后开始退出动画
    setTimeout(() => {
      // 第二阶段动画：放大效果
      animateTo({ duration: 300, curve: Curve.EaseIn }, () => {
        this.scaleValue = 1.1;
        this.rotationAngle = 0;
      });
      
      // 第三阶段动画：淡出效果
      setTimeout(() => {
        animateTo({ duration: 700, curve: Curve.EaseOut }, () => {
          this.contentOpacity = 0;
          this.scaleValue = 0.5;
          this.translateYValue = -50;
        });
        
        // 等待动画结束后跳转
        setTimeout(() => {
          // 停止粒子动画定时器
          clearInterval(this.particleTimer);
          router.pushUrl({
            url: 'pages/HomePage'
          });
        }, 700);
      }, 300);
    }, 3000);
    
    // 记录过渡
    this.Log_Event('aboutToAppear');
  }
  
  aboutToDisappear() {
    // 清除粒子动画定时器
    if (this.particleTimer) {
      clearInterval(this.particleTimer);
    }
    this.Log_Event('aboutToDisappear');
  }

  build() {
    Column() {
      // 粒子动画层
      Stack() {
        // 渐变背景
        Column()
          .width('100%')
          .height('100%')
          .backgroundImage(this.backgroundGradient)
        
        // 粒子效果
        ForEach(this.particles, (item: ParticleInfo) => {
          Circle()
            .fill(item.color)
            .width(item.size)
            .height(item.size)
            .position({ x: `${item.x}%`, y: `${item.y}%` })
            .opacity(item.opacity)
        })
        
        // 内容层
        Column() {
          Image('http://139.155.155.67:2342/images/default_avatar.png')
            .width(120)
            .height(120)
            .borderRadius(60)
            .margin({ bottom: 40 })
          
          Text(this.userName)
            .fontSize(42)
            .fontWeight(FontWeight.Bold)
            .fontColor('#FFFFFF')
            .margin({ bottom: 20 })
          
          Text(this.welcomeMessage)
            .fontSize(26)
            .fontColor('rgba(255, 255, 255, 0.9)')
          
          Row()
            .width(150)
            .height(4)
            .backgroundColor('#FFFFFF')
            .borderRadius(2)
            .margin({ top: 30 })
            .opacity(0.7)
        }
        .width('100%')
        .height('100%')
        .alignItems(HorizontalAlign.Center)
        .justifyContent(FlexAlign.Center)
        .opacity(this.contentOpacity)
        .scale({ x: this.scaleValue, y: this.scaleValue })
        .rotate({ angle: this.rotationAngle })
        .translate({ y: this.translateYValue })
      }
      .width('100%')
      .height('100%')
    }
    .width('100%')
    .height('100%')
  }
  
  // 页面生命周期方法
  onPageShow(): void {
    this.Log_Event('onPageShow');
  }

  onPageHide(): void {
    this.Log_Event('onPageHide');
  }

  onBackPress(): boolean {
    this.Log_Event('onBackPress');
    return true; // 防止返回
  }

  // 日志记录方法
  public Log_Event(eventName: string): void {
    // 根据事件名称选择合适的日志事件类型
    switch (eventName) {
      case 'aboutToAppear':
        logManager.info(LogCategory.USER, LogEventType.PAGE_APPEAR, 'TransitionPage');
        break;
      case 'aboutToDisappear':
        logManager.info(LogCategory.USER, LogEventType.PAGE_DISAPPEAR, 'TransitionPage');
        break;
      case 'onPageShow':
        logManager.info(LogCategory.USER, LogEventType.PAGE_SHOW, 'TransitionPage');
        break;
      case 'onPageHide':
        logManager.info(LogCategory.USER, LogEventType.PAGE_HIDE, 'TransitionPage');
        break;
      case 'onBackPress':
        logManager.info(LogCategory.USER, LogEventType.PAGE_BACK, 'TransitionPage');
        break;
      default:
        logManager.info(LogCategory.USER, LogEventType.SYSTEM_INFO, `TransitionPage: ${eventName}`);
    }
  }
} 