import { Component , OnInit} from '@angular/core';
import { ActivatedRoute } from '@angular/router';//xinzeng
import { HttpClient } from '@angular/common/http'; 

// 引用FmodeChatCompletion类
import { TestChatCompletion, TestChatMessage } from './class-test-chat-completion';
import { TestRxjsChatCompletion } from './class-rxjs-chat-completion';

import { ModalController } from '@ionic/angular';
import { ModalSuccessPage } from '../modal-success/modal-success.page';
import { AlertController } from '@ionic/angular';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page implements OnInit {

  transportType: 'recommend' | 'custom' = 'recommend';
  selectedCarrier: string = 'carrier1';
  selectedMethod: string = 'method1';
  //下面是从
  submittedData: any = null;

  messageList:Array<TestChatMessage> = []
  userInput:string = ""

  aiTransportAdvice: string = ''; // 用于存储AI的建议

  constructor(
    private route: ActivatedRoute,
    private http: HttpClient, // 注入HttpClient服务
    public modalCtrl: ModalController,
    private alertController: AlertController // 注入 AlertController
    ) {}

  ngOnInit() {
    // 使用 queryParams 来获取数据
    this.route.queryParams.subscribe(params => {
      const data = params['submittedData'];
      if (data) {
        this.submittedData = JSON.parse(decodeURIComponent(data));
      }
    });
  }

  confirmInfo() {
    console.log('信息已确认');
    // 确认信息的逻辑
  }

  async showAlert() {
    const alert = await this.alertController.create({
      header: '确认信息',
      message: '确认信息成功',
      mode: 'ios', // 可以根据需要选择 'md', 'ios'
      backdropDismiss: false, // 禁止点击背景关闭警告框
      buttons: [
        {
          text: '关闭',
          handler: () => {
            // 点击确定后的操作
          }
        }
      ],
      cssClass: 'custom-alert' // 自定义 CSS 类
    });
    await alert.present();
  }

  modifyInfo() {
    console.log('信息将被修改');
    // 修改信息的逻辑
  }
  AIadaptation(){
    let GuhiPromoptTemplate = `
你能够分析物品的类别，尺寸，发送地址和接受地址，找到最佳的现代运输方式。请根据以下信息找到最佳的一种的运输方式：
   ${JSON.stringify(this.submittedData)}。

请根据以上要求并且格式要严格。
请回答，并按照以下格式返回
你收到的物品信息：
运输公司:
运输方式:
预计花费时间:
    `
    this.messageList.push({
      role:"user",
      content: GuhiPromoptTemplate
    })
     // this.completion.createCompletionByStream()

    // messageList在competion内部，已经赋予了完整的message
    // 下方暴露出来的可订阅内容，主要是用于关键字过滤，或者其他开发逻辑的续写
    let testChatCompletion = new TestRxjsChatCompletion(this.messageList);
    testChatCompletion.createCompletionByStream().subscribe({
        next: ({ content, cumulativeContent, done }) => {
            console.log(`Content: ${content}`);
            console.log(`Cumulative Content: ${cumulativeContent}`);
            if (done) {
              this.aiTransportAdvice = cumulativeContent; // 更新aiTransportAdvice属性
                console.log('Stream completed');
            }
        },
        error: err => console.error(err),
        complete: () => console.log('Observable completed')
    });
    
  }
  
//点击确认跳转
  confirmTransport() {
    console.log('运输方式已确认');

    // 显示提交成功模态
    this.presentSuccessModal();
  
  }
  async presentSuccessModal() {
    const modal = await this.modalCtrl.create({
      component: ModalSuccessPage,
      cssClass: 'my-custom-class'
    });
    return await modal.present();
  }

  sendMessage(){
    this.messageList.push({
      role:"user",
      content: this.userInput
    })
    this.userInput = ""
    
    // this.completion.createCompletionByStream()

    // messageList在competion内部，已经赋予了完整的message
    // 下方暴露出来的可订阅内容，主要是用于关键字过滤，或者其他开发逻辑的续写
    let testChatCompletion = new TestRxjsChatCompletion(this.messageList);
    testChatCompletion.createCompletionByStream().subscribe({
        next: ({ content, cumulativeContent, done }) => {
            console.log(`Content: ${content}`);
            console.log(`Cumulative Content: ${cumulativeContent}`);
            if (done) {
                console.log('Stream completed');
            }
        },
        error: err => console.error(err),
        complete: () => console.log('Observable completed')
    });

  }

}
