import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
    
import { IonContent,IonButton,IonSegment,IonSegmentButton,IonLabel,IonList,IonItem,IonTextarea } from "@ionic/angular/standalone";
import { AgentStory, EmbedQuery, RetriveAllDocument } from '../../../lib/story';
import { CloudApi } from 'src/lib/ncloud';
import { FmodeChatCompletion,MarkdownPreviewModule } from 'fmode-ng';

@Component({
  selector: 'app-page-hangzhou',
  templateUrl: './page-hangzhou.component.html',
  styleUrls: ['./page-hangzhou.component.scss'],
  standalone: true,
    imports:[
      CommonModule,
      IonContent,IonButton,
      IonSegment,IonSegmentButton,IonLabel,
      IonList,IonItem,IonTextarea,
      MarkdownPreviewModule
    ]
})
export class PageHangzhouComponent  implements OnInit {
  tab:string = "vector"
  tabChange(ev:any){
    this.tab = ev.detail.value
  }
  constructor() { }

  ngOnInit() {
    this.loader(this.fileList[0]);
  }

  /**
   * 文档加载、分割、向量存储
   */
  fileList:Array<any> = [
    {
      title:`市委办公厅 市政府办公厅印发《关于服务保障“抓防控促发展”落实“人才生态37条”的补充意见》的通知`,
      tags:["杭州","人才政策"],
      url:`https://app.fmode.cn/dev/jxnu/case/2020%E5%B9%B4%E6%9D%AD%E5%B7%9E%E5%B8%82%E4%BA%BA%E6%89%8D37%E6%9D%A1.docx`
    },
    {
      title:"杭州市余杭区服务保障高层次人才创新创业政策实施细则",
      tags:["杭州","余杭","人才政策","创新创业","双创"],
      url:"https://app.fmode.cn/dev/jxnu/case/2022年杭州余杭.docx"
    }
  ]
  storyMap:any = {}
  preview(file:any){
    window.open(file.url,"_blank")
  }
  async loader(file:any){
    let story = new AgentStory(file);
    await story.loader(file.url);
    console.log(story);
    this.storyMap[file?.url] = story;
  }
  async splitter(story:AgentStory){
    await story.splitter();
  }
  async embedings(story:AgentStory){
    await story.embedings()
  }

  /**
   * 文本向量检索
   */
  userInput:string = "";
  searchDocList:Array<any> = []
  inputChange(ev:any){
    this.userInput = ev.detail.value
  }
  async retriveFrontEnd(){
    let storyList = Object.values(this.storyMap);
    let docList:any = []
    storyList.forEach((story:any)=>{
      docList = docList.concat(story.docList)
    })
    let vector512 = await EmbedQuery(this.userInput)
    console.log(this.userInput,vector512)
    console.log(docList)
    this.searchDocList = RetriveAllDocument(vector512,docList)
    console.log("searchDocList",this.searchDocList)
  }

  async retriveBackEnd(){
    let vector512 = await EmbedQuery(this.userInput)
    console.log(this.userInput,vector512)

    let api = new CloudApi()
    let result = await api.fetch("agent/retrive",{
      vector512:vector512
    })
    console.log(result)
    this.searchDocList = result?.data || result;
  }

  /**
   * 知识库问答
   */
  messageInput:string = "";
  messageResult:any;
  isComplete:boolean = false;
  messageChange(ev:any){
    this.messageInput = ev.detail.value
  }
  async sendMessage(){
    // 通过RAG检索相关文本块
    let vector512 = await EmbedQuery(this.userInput)
    let api = new CloudApi()
    let result = await api.fetch("agent/retrive",{
      vector512:vector512
    })
    this.searchDocList = result?.data || result;
    let top10Doc = this.searchDocList.slice(0,10);
    let docInsertion = `# 知识库文档\n${top10Doc.map(item=>item.pageContent).join("\n")}`
    
    let PromptTemplate = `
    ${docInsertion}
    您是一名专业的人力资源顾问，帮助应届大学生解答当地政策问题，从政策及知识库文档中中寻找学生所需，并给予建议。
    以下是学生的问题：${this.messageInput}
   `
    let completion = new FmodeChatCompletion([
      {role:"system",content:""},
      {role:"user",content:PromptTemplate}
      ])
      completion.sendCompletion().subscribe((message:any)=>{
          this.messageResult = message
          if(message?.complete){
            this.isComplete = true;
          }
      })
  }

}
