import { Component } from '@angular/core';
import { ModalController } from '@ionic/angular/standalone';
import { IonicModule } from '@ionic/angular';
import { FlowExecutor } from '../lib/flow.executor';
import { MockProgressTask, MockRetryTask, MockSuccessTask } from './mock-tasks/mock-tasks';
import { FlowDisplayComponent } from '../lib/flow-display/flow-display.component';
import { TriageResultComponent } from './consult-tasks/triage-result/triage-result.component';
import { TriageTask } from './consult-tasks/consult-tasks';
import { SymptomInputModalComponent } from './consult-tasks/symptom-input/symptom-input.modal';
import { getUserForm } from '../lib/tasks/task-user-form/get-user-form';
import { JobIntentionTask, UserBasicInfoTask, UserInterestsTask } from './job-workflow/task.job';
import { TaskUserForm } from '../lib/tasks/task-user-form/task-user-form';
import { TaskCompletionJson } from '../lib/tasks/task-completion-json/task-completion-json';
import { TaskCompletionText } from '../lib/tasks/task-completion-text/task-completion-text';

@Component({
  selector: 'app-page-flow-test',
  templateUrl: './page-flow-test.component.html',
  styleUrls: ['./page-flow-test.component.scss'],
  imports: [
    IonicModule,
    FlowDisplayComponent,
    TriageResultComponent,
    SymptomInputModalComponent
  ],
  standalone: true,
})
export class PageFlowTestComponent {

  private executor = new FlowExecutor(3, true);

  constructor(
    private modalCtrl: ModalController
  ) {

  }

  async farmWorkflow() {
    const collectProblemTask = new TaskUserForm({
      title: '农业问题描述采集',
      input: [], // 初始任务不需要输入
      output: [
        { name: 'cropType', type: 'string', required: true },
        { name: 'growthStage', type: 'string', required: false },
        { name: 'problemDesc', type: 'string', required: true },
        { name: 'symptoms', type: 'string', required: false },
        { name: 'urgency', type: 'number', required: false }
      ],
      modalCtrl: this.modalCtrl,
      fieldList: [
        {
          type: "String",
          key: "cropType",
          name: "作物种类",
          required: true,
          placeholder: "如：水稻、玉米、西红柿"
        },
        {
          type: "Select",
          key: "growthStage",
          name: "生长阶段",
          options: [
            { label: "育苗期", value: "seedling" },
            { label: "生长期", value: "growth" },
            { label: "开花期", value: "blooming" },
            { label: "结果期", value: "fruiting" }
          ]
        },
        {
          type: "Textarea",
          key: "problemDesc",
          name: "问题描述",
          required: true,
          placeholder: "请详细描述作物异常情况..."
        },
        {
          type: "Textarea",
          key: "symptoms",
          name: "症状表现",
          options: [
            { label: "叶片发黄", value: "yellowing" },
            { label: "枯萎", value: "wilting" },
            { label: "病斑", value: "spots" },
            { label: "虫害痕迹", value: "pests" },
            { label: "霉变", value: "mold" }
          ]
        },
        {
          type: "Radio",
          key: "urgency",
          name: "紧急程度",
          options: [
            { label: "轻微观察", value: 1 },
            { label: "需要处理", value: 2 },
            { label: "紧急", value: 3 }
          ]
        }
      ]
    });

    const problemClassificationTask = new TaskCompletionJson({
      title: '农业问题分类',
      input: [
        { name: 'cropType', type: 'string', required: true },
        { name: 'growthStage', type: 'string', required: false },
        { name: 'problemDesc', type: 'string', required: true },
        { name: 'symptoms', type: 'string', required: false }
      ],
      output: [
        { name: 'problemDesc', type: 'string', required: true },
        { name: 'symptoms', type: 'string', required: true },
        { name: 'cropType', type: 'string', required: false }
      ],
      promptTemplate: `作为农业专家，请分析问题并返回JSON：
      {
        "problemType": ["病虫害|营养缺乏|种植技术|气候影响"],
        "confidence": "置信度(0-1)",
        "tags": ["关键词标签"]
      }
      输入数据：{{problemDesc}} {{symptoms}} {{growthStage}} {{cropType}} {{urgency}}`,
    });

    const solutionGenerationTask = new TaskCompletionText({
      title: '农业解决方案生成',
      input: [
        { name: 'cropType', type: 'string', required: true },
        { name: 'problemType', type: 'array', required: true },
        { name: 'symptoms', type: 'string', required: false }
      ],
      output: [
        { name: 'solution', type: 'string', required: true }
      ],
      promptTemplate: `根据以下信息生成解决方案：
      **作物**：{{cropType}}
      **问题类型**：{{problemType}}
      **症状**：{{symptoms}}
      
      要求：
      1. 分步骤说明处理措施
      2. 包含安全注意事项
      3. 语言通俗易懂`,
      outputProperty: 'solution'
    });

    const pesticideRecommendationTask = new TaskCompletionJson({
      title: '安全农药推荐',
      input: [
        { name: 'cropType', type: 'string', required: true },
        { name: 'problemType', type: 'array', required: true }
      ],
      output: [
        {
          name: 'recommendations',
          type: 'array',
          required: true,
          description: '推荐的农药列表'
        }
      ],
      promptTemplate: `推荐合规农药（返回JSON）：
      {
        "recommendations": [{
          "name": "农药名称",
          "type": "杀虫剂|杀菌剂|除草剂",
          "dosage": "每亩用量",
          "safetyLevel": "低毒|中毒|高毒"
        }]
      }
      作物：{{cropType}}
      病虫害：{{problemType}}`
    });
    // 创建工作流
    let workflow = {
      title: '农业咨询工作流',
      desc: '农业种植问题',
      taskList: [collectProblemTask, problemClassificationTask, solutionGenerationTask, pesticideRecommendationTask]
    };

    this.executor.setWorkflow(workflow);
    const modal = await this.modalCtrl.create({
      component: FlowDisplayComponent,
      componentProps: { executor: this.executor }
    });

    await modal.present();
    await this.executor.start();

  }

  async getForm() {
    const fieldList = [
      { type: "String", key: "name", name: "姓名", required: true },
      { type: "String", key: "mobile", name: "手机", required: true },
      {
        type: "Radio", key: "gender", name: "性别", required: false, options: [
          { label: "男", value: "male" },
          { label: "女", value: "female" }
        ]
      }
    ];

    try {
      const result = await getUserForm({ modalCtrl: this.modalCtrl, fieldList });
      console.log('Collected data:', result);
      return result;
    } catch (error) {
      console.error('Form error:', error);
      return null;
    }
  }

  async consultWorkflow() {
    const tasks = [
      // 描述病情任务（用户信息采集）
      new TaskUserForm({
        title: '病情描述',
        modalCtrl: this.modalCtrl,
        fieldList: [
          {
            type: "String",
            key: "userDesc",
            name: "病情描述",
            required: true,
            placeholder: "请详细描述您的症状、持续时间和不适感"
          },
          {
            type: "String",
            key: "duration",
            name: "持续时间",
            required: false,
            placeholder: "例如：3天、2周等"
          },
          {
            type: "Radio",
            key: "painLevel",
            name: "疼痛程度",
            required: false,
            options: [
              { label: "无疼痛", value: "none" },
              { label: "轻度", value: "mild" },
              { label: "中度", value: "moderate" },
              { label: "重度", value: "severe" }
            ]
          }
        ],
        initialData: {}
      }),

      // 智能分诊任务（AI分析）
      new TaskCompletionJson({
        title: '智能分诊',
        promptTemplate: `您是一名专业的分诊护士，根据患者描述推荐最合适的科室。严格按照以下JSON格式返回：
        {
          "department": "科室名称",
          "reason": "分诊理由(50字以内)"
        }
        患者主诉：{{userDesc}}
        持续时间：{{duration}}
        疼痛程度：{{painLevel}}`,
        input: [
          { name: 'userDesc', type: 'string', required: true },
          { name: 'duration', type: 'string', required: false },
          { name: 'painLevel', type: 'string', required: false }
        ],
        output: [
          { name: 'department', type: 'string', required: true },
          { name: 'reason', type: 'string' }
        ]
      }),
      // 2. 问诊信息收集
      new TaskUserForm({
        title: '详细问诊',
        modalCtrl: this.modalCtrl,
        fieldList: [
          {
            type: "TextArea", key: "symptoms", name: "详细症状", required: true,
            placeholder: "请详细描述您的症状、部位、性质和变化情况"
          },
          { type: "String", key: "medicalHistory", name: "既往病史", required: false },
          { type: "String", key: "allergies", name: "过敏史", required: false },
          { type: "String", key: "medications", name: "当前用药", required: false },
          {
            type: "Radio", key: "needTests", name: "是否需要检查", required: true,
            options: [
              { label: "需要", value: true },
              { label: "不需要", value: false }
            ]
          }
        ],
        initialData: {}
      }),

      // 3. 检查建议生成（条件性任务）
      new TaskCompletionText({
        title: '检查建议',
        promptTemplate: `作为专业医生，根据以下问诊信息为患者推荐适当的检查项目：
    症状描述：{{symptoms}}
    既往病史：{{medicalHistory || '无'}}
    过敏史：{{allergies || '无'}}
    当前用药：{{medications || '无'}}
    
    请列出建议的检查项目，说明每项检查的目的，并用通俗语言解释检查过程。`,
        outputProperty: "testRecommendations",
        inputVariables: ["symptoms", "medicalHistory", "allergies", "medications"],
        modelOptions: {
          temperature: 0.3,
          maxTokens: 300
        }
      }),

      new TaskUserForm({
        title: '检查结果录入',
        modalCtrl: this.modalCtrl,
        fieldList: [
          {
            type: "TextArea",
            key: "testResults",
            name: "检查结果",
            required: true,
            placeholder: "请粘贴或输入您的检查报告结果（包括各项指标和参考值）"
          },
          {
            type: "DatePicker",
            key: "testDate",
            name: "检查日期",
            required: true,
            default: new Date()
          }
        ]
      }),
      // 4. 诊断与处方生成
      new TaskCompletionJson({
        title: '诊断与处方',
        promptTemplate: `作为主治医生，请根据以下信息给出诊断结果和治疗方案：
        ## 患者信息
        主诉：{{userDesc}}
        详细症状：{{symptoms}}
        {{#if medicalHistory}}既往病史：{{medicalHistory}}{{/if}}
        {{#if allergies}}过敏史：{{allergies}}{{/if}}
        {{#if medications}}当前用药：{{medications}}{{/if}}
        ## 检查信息
        检查日期：{{testDate}}
        检查结果：{{testResults}}
        
        请按照以下JSON格式返回...`, // 保持原有JSON格式要求
        input: [
          { name: 'userDesc', type: 'string', required: true },
          { name: 'symptoms', type: 'string', required: true },
          { name: 'medicalHistory', type: 'string', required: false },
          { name: 'allergies', type: 'string', required: false },
          { name: 'medications', type: 'string', required: false },
          { name: 'testResults', type: 'string', required: false }
        ],
        output: [
          { name: 'diagnosis', type: 'string', required: true },
          { name: 'treatmentPlan', type: 'string', required: true },
          { name: 'medications', type: 'string', required: false },
          { name: 'followUp', type: 'string', required: false },
          { name: 'notes', type: 'string', required: false }
        ],
        modelOptions: {
          temperature: 0.1, // 低随机性确保医疗准确性
          maxTokens: 500
        }
      }),

      // 5. 患者教育材料生成（可选任务）
      new TaskCompletionText({
        title: '患者教育',
        promptTemplate: `根据以下诊断和治疗方案，生成患者友好的教育材料：
    诊断：{{diagnosis}}
    治疗方案：{{treatmentPlan}}
    用药指导：{{#each medications}}- {{this.name}}: {{this.dosage}}, 用药{{this.duration}}{{/each}}
    
    请用通俗易懂的语言解释：
    1. 疾病的基本知识
    2. 为什么需要这个治疗方案
    3. 用药注意事项
    4. 日常生活建议
    5. 何时需要紧急就医`,
        outputProperty: "patientEducation",
        inputVariables: ["diagnosis", "treatmentPlan", "medications"],
        modelOptions: {
          temperature: 0.5, // 中等随机性使语言更自然
          maxTokens: 600
        }
      })
    ];

    // 创建工作流
    const workflow = {
      title: '门诊问诊工作流',
      desc: '1.导诊',
      taskList: tasks
    };

    this.executor.setWorkflow(workflow);
    const modal = await this.modalCtrl.create({
      component: FlowDisplayComponent,
      componentProps: { executor: this.executor }
    });

    await modal.present();
    await this.executor.start();
  }
  async jobWorkflow() {
    // 创建工作流
    const workflow = {
      title: '求职信息收集',
      desc: '请填写您的求职相关信息',
      taskList: [
        new UserBasicInfoTask(this.modalCtrl),
        new JobIntentionTask(this.modalCtrl),
        // new UserInterestsTask(this.modalCtrl)
      ]
    };

    this.executor.setWorkflow(workflow);
    const modal = await this.modalCtrl.create({
      component: FlowDisplayComponent,
      componentProps: { executor: this.executor }
    });

    await modal.present();
    await this.executor.start();
  }
  async startWorkflow() {
    // 创建工作流
    const workflow = {
      title: '示例工作流',
      desc: '演示工作流执行过程',
      taskList: [
        new MockSuccessTask(),
        new MockRetryTask(),
        new MockProgressTask()
      ]
    };

    this.executor.setWorkflow(workflow);
    const modal = await this.modalCtrl.create({
      component: FlowDisplayComponent,
      componentProps: { executor: this.executor }
    });

    await modal.present();
    await this.executor.start();
  }

  // 问诊任务
  async startTriage() {
    this.executor.setWorkflow({
      title: '医疗分诊流程',
      taskList: [new TriageTask({ modalCtrl: this.modalCtrl })]
    });

    this.executor.taskSuccess$.subscribe(task => {
      if (task instanceof TriageTask) {
        this.showTriageResult(task);
      }
    });

    await this.executor.start();
  }

  private async showTriageResult(task: TriageTask) {
    const modal = await this.modalCtrl.create({
      component: TriageResultComponent,
      componentProps: {
        symptom: task.getData('symptomDescription'),
        department: task.getData('department'),
        reason: task.getData('triageReason')
      }
    });

    await modal.present();
  }
}
