import { Component } from '@angular/core';
import {
  IonButton,
  IonCard,
  IonCardContent,
  IonCardHeader,
  IonCardSubtitle,
  IonCardTitle,
  IonContent,
  IonHeader,
  IonIcon,
  IonItem,
  IonList,
  IonProgressBar,
  IonTitle,
  IonToolbar,
  ModalController,
} from '@ionic/angular/standalone';
import { AgentTaskStep } from 'src/app/agent/agent.task';
import { addIcons } from 'ionicons';
import {
  checkmarkCircleOutline,
  closeCircleOutline,
  ellipseOutline,
  reloadCircleOutline,
} from 'ionicons/icons';
import { AgentUserinputComponent } from 'src/app/agent/agent-userinput/agent-userinput.component';
import { DalleOptions, FmodeChatCompletion, ImagineWork } from 'fmode-ng';
import { DecimalPipe } from '@angular/common';
addIcons({
  ellipseOutline,
  checkmarkCircleOutline,
  reloadCircleOutline,
  closeCircleOutline,
});

@Component({
  selector: 'app-taskchain-page',
  templateUrl: './taskchain-page.component.html',
  styleUrls: ['./taskchain-page.component.scss'],
  standalone: true,
  imports: [
    IonButton,
    IonHeader,
    IonToolbar,
    IonTitle,
    IonContent,
    IonItem,
    IonCard,
    IonCardHeader,
    IonCardTitle,
    IonCardSubtitle,
    IonCardContent,
    IonProgressBar,
    IonIcon,
    IonList,
    DecimalPipe,
  ],
})
export class TaskchainPageComponent {
  constructor(private modalCtrl: ModalController) {}
  // constructor() {}

  taskList: AgentTaskStep[] = [];
  wait(duration: number = 1000) {
    return new Promise((resolve) => {
      setInterval(() => {
        resolve(true);
      }, duration);
    });
  }

  // 组件用户输入
  async userInput(options: { fieldsArray: any }) {
    const modal = await this.modalCtrl.create({
      component: AgentUserinputComponent,
      componentProps: {
        fieldsArray: options.fieldsArray,
      },
    });
    modal.present();
    const { data, role } = await modal.onWillDismiss();
    if (role === 'confirm') {
      return data;
    }
  }

  // 创建任务集
  shareData: any = {};
  createTask() {
    // task1
    let task1 = new AgentTaskStep({
      title: 'AI扩展更多信息',
      shareData: this.shareData,
    });
    task1.handle = () => {
      return new Promise(async (resolve) => {
        // await this.wait(5000);
        console.log('AI扩展更多信息,执行中...');
        let userInput = await this.userInput({
          fieldsArray: [
            {
              name: '绘图要求',
              type: 'text',
              placeholder: '主题+元素+风格',
            },
            {
              name: '图片类型',
              type: 'text',
              placeholder: 'logo/普通图片/海报',
            },
          ],
        });
        // console.log(userInput);
        // console.log(userInput['图片类型']);

        // 输入内容不能为空，为空则停止执行
        if (!userInput?.['绘图要求'] || !userInput?.['图片类型']) {
          task1.error = '绘图要求或者图片类型不能为空';
          resolve(false);
        }
        // ai生成更详细的内容
        let PromptTemplate = `请您作为一名专业的美术大家，请根据以下需求给出更详细的补充，用最少的文字表达出来。需求有：${userInput['绘图要求']} + ${userInput['图片类型']}`;
        console.log(PromptTemplate);

        let completion = new FmodeChatCompletion([
          { role: 'system', content: '' },
          { role: 'user', content: PromptTemplate },
        ]);

        completion.sendCompletion().subscribe((message: any) => {
          // 打印消息体
          // console.log(message.content);

          //进度
          if (task1.progress < 0.5) {
            task1.progress += 0.1;
          }
          if (task1.progress >= 0.5 && task1.progress < 1) {
            task1.progress += 0.01;
          }
          // 赋值消息内容给组件内属性
          this.shareData.PictureDescResult = message.content;
          if (message?.complete) {
            task1.progress = 1;
            resolve(true);
          }
        });
      });
    };

    // task2
    let task2 = new AgentTaskStep({
      title: 'AI生成图片',
      shareData: this.shareData,
    });
    task2.handle = () => {
      return new Promise(async (resolve) => {
        // await this.wait(3000);

        // 上一task执行结果不为空，为空则停止执行
        if (!this.shareData.PictureDescResult) {
          task2.error = '图片描述不存在';
          resolve(false);
        }

        console.log('AI生成图片,执行中...');

        let imagineWork = new ImagineWork();
        let PicturePrompt = `${task1.shareData.PictureDescResult}风格，画面不带任何文字。`;
        let options: DalleOptions = { prompt: PicturePrompt };
        imagineWork?.draw(options).subscribe((work: any) => {
          // console.log('imagineWork', work?.toJSON());
          // console.log('images', work?.get('images'));

          // 进度
          let schedule = setInterval(() => {
            if (task2.progress < 0.5) {
              task2.progress += 0.1;
            }
            if (task2.progress >= 0.5 && task2.progress < 1) {
              task2.progress += 0.01;
            }
          }, 1000);
          if (work?.get('images')?.length) {
            this.shareData.images = work?.get('images');
            task2.progress = 1;
            clearInterval(schedule);
            resolve(true);
          }
        });
      });
    };

    //taskList
    this.taskList = [task1, task2];
    this.AngentExecutor(this.taskList);
  }

  /**
   * 任务执行函数
   */
  async AngentExecutor(taskStepList: AgentTaskStep[]) {
    for (let index = 0; index < taskStepList.length; index++) {
      let step = taskStepList[index];
      let result = await step.handle();
      if (result == false) {
        break;
      }
      if (step.error) {
        break;
      }
      if (!step.error) {
      }
    }
  }
}
