import testNapi from 'libentry.so';

@Entry
@Component
struct ContinuousLogPage {
  @State message: string = '大量持续日志输出';
  @State isRunning: boolean = false;
  @State elapsedTime: number = 0; // 经过的秒数
  private logTimer: number = -1; // 日志定时器 ID（100ms）
  private displayTimer: number = -1; // 显示定时器 ID（1s）

  aboutToAppear() {
    // 初始化状态
    this.isRunning = false;
    this.elapsedTime = 0;
  }

  aboutToDisappear() {
    // 清理定时器
    this.stopAllTimers();
  }

  startContinuousLog() {
    if (this.isRunning) {
      return;
    }

    this.isRunning = true;
    this.elapsedTime = 0;

    // 每 100ms 调用一次 printRandomHiLog
    this.logTimer = setInterval(() => {
      testNapi.pirntRandomHiLog();
    }, 100);

    // 每秒更新一次显示
    this.displayTimer = setInterval(() => {
      this.elapsedTime++;
    }, 1000);
  }

  stopContinuousLog() {
    this.stopAllTimers();
    this.isRunning = false;
    this.elapsedTime = 0;
  }

  stopAllTimers() {
    if (this.logTimer !== -1) {
      clearInterval(this.logTimer);
      this.logTimer = -1;
    }
    if (this.displayTimer !== -1) {
      clearInterval(this.displayTimer);
      this.displayTimer = -1;
    }
  }

  build() {
    Column() {
      // 标题
      Text('大量持续日志输出')
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 50, bottom: 30 })
      
      // 说明文字
      Text('点击开始后每 100ms 生成一条随机日志')
        .fontSize(16)
        .fontColor('#666666')
        .margin({ bottom: 30 })
      
      // 计时器显示
      Text(`已运行：${this.elapsedTime} 秒`)
        .fontSize(20)
        .fontColor('#007DFF')
        .fontWeight(FontWeight.Medium)
        .margin({ bottom: 50 })
      
      // 状态显示
      Text(this.isRunning ? '正在输出日志...' : '已停止')
        .fontSize(18)
        .fontColor(this.isRunning ? '#FF4444' : '#666666')
        .margin({ bottom: 50 })
      
      // 按钮行
      Row() {
        // 开始按钮
        Button('开始')
          .width('40%')
          .height(50)
          .backgroundColor('#00D900')
          .enabled(!this.isRunning)
          .onClick(() => {
            this.startContinuousLog();
          })
        
        // 停止按钮
        Button('停止')
          .width('40%')
          .height(50)
          .backgroundColor('#FF4444')
          .enabled(this.isRunning)
          .onClick(() => {
            this.stopContinuousLog();
          })
      }
      .width('80%')
      .justifyContent(FlexAlign.SpaceEvenly)
      .margin({ top: 20 })
    }
    .width('100%')
    .height('100%')
  }
}
