import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonContent, IonHeader, IonTitle, IonToolbar, IonButton, IonInput, IonTextarea, IonItem, IonList } from '@ionic/angular/standalone';
import { TestChatCompletion } from './test-chat-completion';
import { EditTagComponent } from '../edit-tag/edit-tag.component';
import { FmodeChatCompletion, MarkdownPreviewModule } from 'fmode-ng';
import { DalleOptions, ImagineWork } from 'fmode-ng';
@Component({
  selector: 'app-customization',
  templateUrl: './customization.page.html',
  styleUrls: ['./customization.page.scss'],
  standalone: true,
  imports: [IonContent, IonHeader, IonTitle, IonToolbar, CommonModule, FormsModule, IonButton, IonInput, EditTagComponent, IonTextarea, IonItem, IonList, MarkdownPreviewModule,]
})
export class CustomizationPage implements OnInit {
  public isComplete: boolean = false;
  public inputValue = ""
  public gptre = ""
  area: string = ""
  editTags: Array<string> = []
  onInput(event: any) {
    console.log(event.detail.value);

  }
  setTags(ev: any) {
    console.log(ev);
    this.editTags = ev
  }
  onInputarea(event: any) {
    this.area = event.detail.value;
    console.log(this.area);

  }
  ngOnInit() {
  }


  async printInputValue() {
    console.log("create")
    let promt = `您作为一名专业的服装推荐师，请帮我推荐具体的某件衣服,不要鞋子裤子，帽子，我只要你推荐某个具体服装，风格是：${this.editTags.join(",")},需要的衣服功能是：${this.area}`
    let completion = new FmodeChatCompletion([
      { role: "system", content: "" },
      { role: "user", content: promt }
    ])
    completion.sendCompletion().subscribe((message: any) => {
      // 打印消息体
      console.log(message.content)
      // 赋值消息内容给组件内属性
      this.gptre = message.content
      if (message?.complete) {
        this.isComplete = true
      }
    })








    // console.log("开始解析");
    // console.log(this.inputValue);

    // let token = "r:16cd8f27084ff647fcdb5308a6783c4c"
    // localStorage.setItem("token",token)
    // let promt=`您作为一名专业的服装推荐师，请帮我推荐具体的某件衣服，风格是：${this.editTags.join(",")},需要的衣服功能是：${this.area}`
    // let messageList: any = [
    //   {
    //     role: "system", content: `${new Date().toLocaleString}`
    //   },
    //   {
    //     role: "user", content: promt
    //   }
    // ]

    // let completion=new TestChatCompletion(messageList)
    // completion.createCompletionByStream()
    // setInterval(()=>{
    //   console.log(messageList);
    //   if(messageList.length!=1){
    //     this.gptre=messageList[messageList.length-1].content

    //   }
    // },2000)


    // let bodyJson = {
    //   "token": `Bearer ${token}`,
    //   "messages": messageList,
    //   "model": "fmode-4.5-128k",
    //   "temperature": 0.5,
    //   "presence_penalty": 0,
    //   "frequency_penalty": 0,
    //   "top_p": 1,
    //   "stream": true
    // };

    // let response = await fetch("https://test.fmode.cn/api/apig/aigc/gpt/v1/chat/completions", {
    //   "headers": {
    //     "accept": "text/event-stream",
    //   },
    //   "body": JSON.stringify(bodyJson),
    //   "method": "POST",
    //   "mode": "cors",
    //   "credentials": "omit"
    // });
    // let reader = response.body?.getReader()
    // if (!reader) {
    //   throw new Error("Failed to get the response reader.");
    // }

    // let decoder = new TextDecoder();
    // let buffer = "";

    // while (true) {
    //   let { done, value } = await reader.read();
    //   if (done) {
    //     break;
    //   }
    //   let data = decoder.decode(value);
    //   let messages = data.split("\n");
    //   console.log(messages);

    //   for (let i = 0; i < messages.length - 1; i++) {
    //     let message = messages[i];
    //     console.log(message);
    //     let dataStr: string = message.split("data: ")[1]
    //     if (dataStr && dataStr.startsWith("{")) {
    //       try {
    //         let json = JSON.parse(dataStr);
    //         let content = json.choices[0].delta.content
    //         this.gptre = this.gptre + content
    //       } catch (err) { }
    //     }


    //   }
    // }


  }

  userPrompt: string = ""
  promptInput(ev: any) {
    this.userPrompt = ev.detail.value;
  }
  imagineWork: ImagineWork | undefined
  images: Array<string> = []
  constructor(
  ) {
    // 示例任务，自己生成图片后请存储新的ID
    console.log('ImagineWork instance:', this.imagineWork);
    this.imagineWork = new ImagineWork("EXOVSbrmMK");
    this.imagineWork.fetchTask().then(work => {
      this.images = this.imagineWork?.images || [];
    })
  }
  picdetail: string = ""
  async createImage() {
    let promotTemplate = `您是一名专业的美术画家，请您根据服装描述内容，将其描述的服装细节描述出来,服装描述如下：${this.gptre}`
    let completion = new FmodeChatCompletion([
      { role: "system", content: "" },
      { role: "user", content: promotTemplate }
    ])

    completion.sendCompletion().subscribe((message: any) => {
      // 打印消息体
      console.log(message.content)
      // 赋值消息内容给组件内属性
      this.picdetail = message.content
      if (message?.complete) {
        this.imagineWork = new ImagineWork();
        let options: DalleOptions = { prompt: this.picdetail }
        this.imagineWork.draw(options).subscribe(work => {
          console.log("imagineWork", work?.toJSON())
          console.log("images", work?.get("images"))
          if (work?.get("images")?.length) {
            this.images = work?.get("images");
          }
        })
      }
    })



  }
}
