import { Component, OnInit } from '@angular/core';
import { EditTagComponent } from '../components/edit-tag/edit-tag.component';
import { IonList } from '@ionic/angular/standalone';
import { IonItem, IonTextarea,IonButton } from '@ionic/angular/standalone';
import { TestChatCompletion } from './test-chat-completion';
// import { FmodeChatCompletion } from "fmode-ng";
@Component({
  selector: 'app-page-dream-analysis',
  templateUrl: './page-dream-analysis.component.html',
  styleUrls: ['./page-dream-analysis.component.scss'],
  imports:[
    EditTagComponent,
    IonList,IonItem,IonTextarea,IonButton
  ],
  standalone: true,
})
export class PageDreamAnalysisComponent  implements OnInit {


  // 梦境关键词
  dreamTags:Array<string> = []
  setTagsValue(ev:any){
    this.dreamTags = ev;
  }
  // 梦境描述
  dreamDesc:string = ""
  userInput(ev:any){
    this.dreamDesc = ev.detail.value
  }

  // 梦境结果
  dreamResult:string = ""

  // 解析梦境
  async analysisDream(){
    console.log("关键词",this.dreamTags)
    console.log("描述",this.dreamDesc)
    console.log("开始解析梦境")
    let prompt = `您作为一名专业的梦境解析大师，请帮我解析以下梦境。关键词：${this.dreamTags.join(",")}，梦境描述：${this.dreamDesc}`

    let TOKEN = `r:e20ef91b23e2c21d45cb50cd5ec1a122`;
    localStorage.setItem("token",TOKEN)

    let messageList:any = [
      {
        role:"system",content:`${new Date().toLocaleString()}`
      },
      {
        role:"user",content:prompt
      }
    ]

    // 创建并发起一条新的消息补全
    let completion = new TestChatCompletion(messageList)
    // 持续更新事件推送的消息体内容绑定至消息变量
    completion.createCompletionByStream()

    setInterval(()=>{
      console.log(messageList)
      this.dreamDesc = messageList[messageList.length-1]?.content;
    },1000)
    // 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"
    // });
    // if(response && response.body){

    //   let reader = response.body.getReader();

    //   if (!reader) {
    //     throw new Error("Failed to get the response reader.");
    //   }

    //   let decoder = new TextDecoder();
    
    //   while (true) {
    //     let { done, value } = await reader.read();
    //     if (done) {
    //       break;
    //     }
    
    //     let data = decoder.decode(value);
    //     /**
    //       data: {"id":"chatcmpl-AXgfsaapykrm9oEBVQTwRZAVRQHj7","object":"chat.completion.chunk","created":1732592228,"model":"gpt-4o-mini-2024-07-18","system_fingerprint":"fp_0705bf87c0","choices":[{"index":0,"delta":{"content":"！"},"logprobs":null,"finish_reason":null}],"usage":null}
    //       data: {"id":"chatcmpl-AXgfsaapykrm9oEBVQTwRZAVRQHj7","object":"chat.completion.chunk","created":1732592228,"model":"gpt-4o-mini-2024-07-18","system_fingerprint":"fp_0705bf87c0","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}
    //       data: {"id":"chatcmpl-AXgfsaapykrm9oEBVQTwRZAVRQHj7","object":"chat.completion.chunk","created":1732592228,"model":"gpt-4o-mini-2024-07-18","system_fingerprint":"fp_0705bf87c0","choices":[],"usage":{"prompt_tokens":110,"completion_tokens":240,"total_tokens":350,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":0,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}
    //       data: [DONE]
    //      */
    //     let messages = data.split("\n");
    //     messages.forEach(message=>{
    //       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
    //           console.log(content)
    //           this.dreamResult =  this.dreamResult + content
    //         }catch(err){}
    //       }
    //     })

    //   }
    // }
  }

  constructor() { }

  ngOnInit() {}

}
