
import { FmodeChatCompletion } from 'fmode-ng';
import { FlowTask } from '../../lib/flow.task';


// triage.task.ts
import { ModalController } from '@ionic/angular/standalone';
import { Subject, takeUntil } from 'rxjs';
import { SymptomInputModalComponent } from './symptom-input/symptom-input.modal';
import { inject } from '@angular/core';

export class TriageTask extends FlowTask {
  private modalCtrl: ModalController;
  private destroy$ = new Subject<void>();

  constructor(options: { modalCtrl: ModalController }) {
    super({
      title: '智能分诊',
      output: [
        { name: 'department', type: 'string', required: true },
        { name: 'symptomDescription', type: 'string' },
        { name: 'triageReason', type: 'string' }
      ]
    });

    this.modalCtrl = options?.modalCtrl
  }

  override async handle() {
    // 1. 通过模态框获取用户输入
    const symptom = await this.getSymptomDescription();
    if (!symptom) throw new Error('症状描述不能为空');

    this.updateData('symptomDescription', symptom);

    // 2. 调用大模型进行分诊
    await this.generateTriageResult(symptom);
  }

  onDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }

  private async getSymptomDescription(): Promise<string> {
    const modal = await this.modalCtrl.create({
      component: SymptomInputModalComponent,
      backdropDismiss: false
    });

    await modal.present();
    const { data } = await modal.onDidDismiss();
    return data || '';
  }

  private generateTriageResult(symptom: string): Promise<void> {
    return new Promise((resolve, reject) => {
      const prompt = [
        {
          role: "user",
          content: `您是一名专业的分诊护士，根据患者描述推荐最合适的科室。严格按照以下JSON格式返回：
          {
            "department": "科室名称",
            "reason": "分诊理由(50字以内)"
          }`+ `患者主诉：${symptom}`
        }
      ];

      let completion = new FmodeChatCompletion(prompt);

      completion.sendCompletion({
        onComplete: (message: any) => {
          console.log("onComplete", message)
        }
      })
        // .pipe(takeUntil(this.destroy$))
        .subscribe((message: any) => {
          // 处理流式响应
          if (message.content && typeof message.content === 'string') {
            this.setProgress(0.5 + (message.content.length / 200) * 0.5); // 模拟进度
          }
          // console.log(message)
          if (message.complete == true) {
            console.log(message)
            try {
              const result = this.parseTriageResponse(message.content);
              console.log("result", result)
              this.updateData('department', result.department)
                .updateData('triageReason', result.reason);
              this.setProgress(1);
              resolve();
            } catch (e) {
              reject(e);
            }
          }
        });
    });
  }

  private parseTriageResponse(response: string): { department: string; reason: string } {
    try {
      // 尝试提取JSON部分（处理可能的非JSON前缀）
      const jsonStart = response.indexOf('{');
      const jsonEnd = response.lastIndexOf('}') + 1;
      const jsonStr = response.slice(jsonStart, jsonEnd);

      console.log("jsonStr", jsonStr)
      const result = JSON.parse(jsonStr);
      if (!result.department) throw new Error('缺少科室信息');

      return {
        department: result.department.trim(),
        reason: result.reason || '根据症状描述判断'
      };
    } catch (e) {
      throw new Error(`分诊结果解析失败: ${response}`);
    }
  }
}
