// flow-display.component.ts
import { Component, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { ModalController } from '@ionic/angular';
import { FlowExecutor } from '../flow.executor';

@Component({
  standalone: true,
  imports: [CommonModule, IonicModule],
  selector: 'app-flow-display',
  template: `
    <ion-header>
      <ion-toolbar>
        <ion-title>{{executor?.workflow?.title}} <ion-button (click)="dismiss()">返回</ion-button></ion-title>
        <ion-progress-bar [value]="executor?.currentProgress"></ion-progress-bar>
      </ion-toolbar>
    </ion-header>

    <ion-content>
      <ion-list>
        <ion-item *ngFor="let task of executor?.workflow?.taskList; let i = index">
          <ion-label (click)="toggleExpand(i)">
            <h2>{{task.title}}</h2>
            <p>{{task.getData('description')}}</p>

            <div *ngIf="expandedTasks[i]" class="task-details">
              <ion-text color="medium">
                <p>状态: {{task.status}}</p>
                <p>进度: {{task.progress * 100 | number:'1.0-0'}}%</p>
                <p>开始时间: {{taskTimers[i]?.start | date:'mediumTime'}}</p>
                <p>持续时间: {{calculateDuration(i) | number:'1.1-1'}}秒</p>
                <pre *ngIf="task.output">输出参数{{task.output | json}}</pre>
                <pre *ngIf="task.data">共享数据{{task.data | json}}</pre>
              </ion-text>
            </div>
          </ion-label>

          <ion-badge slot="end" [color]="getStatusColor(task.status)">
            {{task.status}} ({{task.progress * 100 | number:'1.0-0'}}%)
          </ion-badge>
        </ion-item>
      </ion-list>
      <ion-card>共享数据
      {{executor?.sharedData|json}}
      </ion-card>

      <ion-footer *ngIf="executor?.status === 'failed'">
        <ion-toolbar color="danger">
          <ion-buttons slot="start">
            <ion-button (click)="retryFailedTask()">
              <ion-icon slot="start" name="refresh"></ion-icon>
              重试失败任务
            </ion-button>
          </ion-buttons>
          <ion-title>工作流执行失败</ion-title>
          <ion-buttons slot="end">
            <ion-button (click)="retryAll()">
              <ion-icon slot="start" name="reload"></ion-icon>
              全部重试
            </ion-button>
          </ion-buttons>
        </ion-toolbar>
      </ion-footer>
    </ion-content>
  `,
  styles: [`
    ion-progress-bar {
      height: 4px;
    }
    ion-item {
      --padding-start: 16px;
      --inner-padding-end: 16px;
    }
    ion-badge {
      margin-inline-start: 12px;
    }
    .task-details {
      margin-top: 8px;
      padding: 8px;
      background: var(--ion-color-light);
      border-radius: 4px;
    }
    pre {
      white-space: pre-wrap;
      font-size: 12px;
    }
  `]
})
export class FlowDisplayComponent {
  @Input() executor?: FlowExecutor;
  expandedTasks: boolean[] = [];
  taskTimers: { start?: Date, end?: Date }[] = [];

  dismiss() {
    this.modalCtrl.dismiss();
  }
  constructor(
    private modalCtrl: ModalController
  ) {
    // 监听任务状态变化
    this.executor?.taskStart$.subscribe((task) => {
      const index = this.executor!.workflow!.taskList.indexOf(task);
      this.taskTimers[index] = { start: new Date() };
    });

    this.executor?.taskSuccess$.subscribe((task) => {
      const index = this.executor!.workflow!.taskList.indexOf(task);
      this.taskTimers[index].end = new Date();
    });
  }

  // 切换任务详情展开状态
  toggleExpand(index: number) {
    this.expandedTasks[index] = !this.expandedTasks[index];
  }

  // 计算任务持续时间
  calculateDuration(index: number): number {
    const timer = this.taskTimers[index];
    if (!timer?.start) return 0;
    const end = timer.end || new Date();
    return (end.getTime() - timer.start.getTime()) / 1000;
  }

  // 重试失败的任务
  async retryFailedTask() {
    const failedIndex = this.executor?.failedTaskIndex;
    if (failedIndex !== null && failedIndex !== undefined) {
      await this.executor?.retryFromTask(failedIndex);
    }
  }

  // 重试全部任务
  async retryAll() {
    await this.executor?.retryFromTask(0);
  }

  getStatusColor(status: string): string {
    switch (status) {
      case 'success': return 'success';
      case 'failed': return 'danger';
      case 'running': return 'primary';
      default: return 'medium';
    }
  }
}
