import { Component, OnInit } from '@angular/core';
import {
  ModalController,
  IonModal,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonList,
  IonItem,
  IonLabel,
  IonAvatar,
  IonButton,
  IonSegment,
  IonSegmentButton,
  IonSegmentContent,
  IonSegmentView,
  IonCardContent,
  IonCardTitle,
  IonCardHeader,
  IonCard,
  IonIcon,
  IonButtons,
  IonInput,
  IonRefresherContent,
  IonRefresher,
  LoadingController,
  IonSpinner,
  IonGrid,
  IonRow,
  IonCol,
  IonBackButton
} from '@ionic/angular/standalone'; // 确保导入自 '@ionic/angular/standalone'

import { addIcons } from 'ionicons';
import { airplane, bluetooth, call, wifi, arrowBackOutline, menuOutline, personOutline, businessOutline, medicalOutline, documentTextOutline, folderOpenOutline } from 'ionicons/icons';
import { CommonModule } from '@angular/common';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
import { Router } from '@angular/router';
addIcons({ airplane, bluetooth, call, wifi });

// 定义对话消息的接口
interface Message {
  role: 'user' | 'assistant' | string;
  content: string;
}

// 定义医生信息的接口
interface Doctor {
  name: string;
  // 根据实际情况添加其他属性，例如：
  // title: string;
  // desc: string;
  // qualifications: string[];
  // avatar?: string;
}

// 定义部门信息的接口
interface Depart {
  name: string;
  // 根据实际情况添加其他属性，例如：
  // description: string;
}

// 定义 Consultation 数据的接口
interface ConsultationData {
  doctor: Doctor;
  depart: Depart;
  title: string;
  allContent: Message[];
}

// 定义 Consultation 对象的接口
interface Consultation {
  id: string; // 确保为 string 类型
  updatedAt: Date;
  data: ConsultationData;
}

@Component({
  selector: 'page-my-health',
  templateUrl: './page-my-health.component.html',
  styleUrls: ['./page-my-health.component.scss'],
  standalone: true,
  imports: [
    IonHeader,
    IonToolbar,
    IonTitle,
    IonContent,
    IonLabel,
    IonItem,
    IonList,
    IonAvatar,
    CommonModule,
    IonButton,
    IonSegment,
    IonSegmentButton,
    IonSegmentContent,
    IonSegmentView,
    IonCardContent,
    IonCardTitle,
    IonCardHeader,
    IonCard,
    IonModal,
    IonIcon,
    IonButtons,
    IonInput,
    IonRefresher,
    IonRefresherContent,
    IonSpinner,
    IonGrid,
    IonRow,
    IonCol,IonBackButton
    // 如果需要，可以取消注释以下行
    // FmMarkdownPreview,
  ]
})
export class PageMyHealthComponent implements OnInit {
  allMessage: Consultation[] = []; // 使用 Consultation 接口
  isLoading: boolean = false;
  errorMessage: string = "";

  avatar: string = "../assets/imgs/avatar.png"; // 默认头像
  currentUser: CloudUser | undefined;
  objectId: string = "";
  userName: string = "";

  back: string = "back";

  // 备用头像 URL
  fallbackAvatarUrl: string = 'https://app.fmode.cn/dev/jxnu/202226701019/头像示例.png';

  // 用于跟踪展开的问诊记录 ID
  expandedConsultations: Set<string> = new Set<string>();

  constructor(
    private router: Router,
    private loadingController: LoadingController
  ) {
    this.currentUser = new CloudUser();
    this.avatar = this.currentUser.data["avatar"] || this.fallbackAvatarUrl;
    this.objectId = this.currentUser.data['objectId'] ?? ''; // 使用空字符串作为默认值
    this.userName = this.currentUser.data["realname"] || "用户";
  }

  ngOnInit() {
    this.loadData();
  }

  /**
   * 加载问诊数据
   */
  async loadData() {
    this.isLoading = true;
    const loading = await this.loadingController.create({
      message: '加载中...',
    });
    await loading.present();

    try {
      let query = new CloudQuery('Consultation');
      query.include("doctor", "depart");
      query.equalTo("user", { "__type": "Pointer", "className": "_User", "objectId": this.objectId });

      const messages = await query.find();
      console.log("allMessage", messages);

      // 映射数据到 Consultation 接口，确保 id 为 string
      this.allMessage = messages.map(message => ({
        id: message.id ?? 'unknown', // 如果 id 为 null 或 undefined，则使用 'unknown'
        updatedAt: new Date(message.updatedAt), // 确保 updatedAt 为 Date 类型
        data: {
          doctor: message.data["doctor"],
          depart: message.data["depart"],
          title: message.data["title"],
          allContent: Array.isArray(message.data["allContent"]) ? message.data["allContent"] : []
        }
      }));
    } catch (error) {
      console.error("加载数据失败:", error);
      this.errorMessage = "数据加载失败，请稍后再试。";
    } finally {
      this.isLoading = false;
      await loading.dismiss();
    }
  }

  /**
   * 处理下拉刷新
   * @param event 下拉刷新事件
   */
  handleRefresh(event: any) {
    setTimeout(() => {
      this.allMessage = [];
      this.loadData().then(() => {
        event.target.complete();
      });
    }, 2000);
  }

  /**
   * 返回首页
   */
  backHome() {
    this.router.navigate(['/tabs/tab1']);
  }

  /**
   * 跳转到用户页面
   */
  gotouser() {
    // 用户相关逻辑
  }

  /**
   * 处理图片加载错误，设置备用图片
   */
  handleImageError() {
    this.avatar = this.fallbackAvatarUrl;
  }

  /**
   * 根据角色获取标签
   * @param role 角色标识
   * @returns 角色标签
   */
  getRoleLabel(role: string): string {
    if (role === 'user') return '病人';
    if (role === 'assistant') return '医生';
    return role;
  }

  /**
   * 根据角色获取图标名称
   * @param role 角色标识
   * @returns 图标名称
   */
  getIcon(role: string): string {
    if (role === 'user') return 'person-outline';
    if (role === 'assistant') return 'medkit';
    return 'person-outline';
  }

  /**
   * 切换问诊记录的展开状态
   * @param consultationId 问诊记录的 ID
   */
  toggleConsultation(consultationId: string) {
    if (this.expandedConsultations.has(consultationId)) {
      this.expandedConsultations.delete(consultationId);
    } else {
      this.expandedConsultations.add(consultationId);
    }
  }

  /**
   * 检查问诊记录是否展开
   * @param consultationId 问诊记录的 ID
   * @returns 是否展开
   */
  isConsultationExpanded(consultationId: string): boolean {
    return this.expandedConsultations.has(consultationId);
  }
}