import { Component, OnInit } from '@angular/core';
import { IonModal, IonHeader, IonToolbar, IonTitle, IonContent, IonList, IonItem, IonLabel, IonAvatar, IonButton, IonChip, IonIcon, IonBadge, IonText, IonCard, IonSegmentButton, IonSegment, IonCol, IonRow, IonGrid, IonButtons, IonFooter, ToastController, IonBackButton, AlertController } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { airplane, bluetooth, call, wifi, star, checkmarkCircle } from 'ionicons/icons';
import { Router } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';

addIcons({ airplane, bluetooth, call, wifi, star, checkmarkCircle });

interface Doctor {
  avatar: string;
  name: string;
  title: string;
  department: string;
  hospital: string;
  hospitalLevel: string;
  hospitalType: string;
  expertise: string;
  rating: number;
  consultations: string;
  recommendations: number;
  tags?: string[];
  prices: {
    text: number;
    voice: number;
    video: number;
  }
  isVerified?: boolean;
  isExpert?: boolean;
}

interface ConsultOption {
  id: number;
  title: string;
  icon: string;
  price: number;
  unit: string;
  isAvailable: boolean; // 是否可用
  isSelected?: boolean; // 是否被选中
}

@Component({
  selector: 'inquiry-human',
  templateUrl: './inquiry-human.component.html',
  styleUrls: ['./inquiry-human.component.scss'],
  standalone: true,
  imports: [
    IonHeader, IonToolbar, IonTitle, IonContent, CommonModule,
    IonLabel, IonItem, IonList, IonAvatar, IonButton, IonChip, IonIcon, IonBadge,
    IonText, IonCard, IonSegment, IonSegmentButton, FormsModule, IonCol, IonRow, IonGrid,
    IonModal, IonButtons, IonFooter, IonBackButton
  ]
})
export class InquiryHumanComponent implements OnInit {
  options: ConsultOption[] = [
    {
      id: 1,
      title: '图文咨询',
      icon: 'chatbubbles',
      price: 100,
      unit: '次',
      isAvailable: true,
      isSelected: true
    },
    {
      id: 2,
      title: '电话咨询',
      icon: 'call',
      price: 150,
      unit: '次起',
      isAvailable: true
    },
    {
      id: 3,
      title: '视频问诊',
      icon: 'videocam',
      price: 300,
      unit: '次起',
      isAvailable: true
    },
    {
      id: 4,
      title: '私人医生',
      icon: 'person',
      price: 0,
      unit: '',
      isAvailable: false
    },
    {
      id: 5,
      title: '预约',
      icon: 'calendar',
      price: 0,
      unit: '',
      isAvailable: false
    }
  ];

  type:string = "图文咨询"
  selectOption(option: ConsultOption) {
    if (!option.isAvailable) return;
    this.options.forEach(opt => opt.isSelected = false);
    option.isSelected = true;
    this.type = option.title
  }

  isModalOpen = false;
  isPaymentModalOpen = false; // 新增状态变量

  currentUser: CloudUser;

  constructor(
    private alertController: AlertController,
    private router: Router,
    private toastController: ToastController // 注入 ToastController
  ) {
    this.currentUser = new CloudUser();
    this.loadDoctors();
  }

  ngOnInit() { }

  // 顶部导航栏
  selectedSegment = '全部';
  segments = ['全部', '妇产科', '儿科', '皮肤性病科', '内科'];

  // 选择科室
  async segmentChanged(event: any) {
    this.selectedSegment = event.detail.value;
    await this.loadDoctors();
    console.log(this.selectedSegment);
  }

  // 医生列表
  doctors: Array<CloudObject> = [];
  async loadDoctors() {
    let query = new CloudQuery('Doctor1');
    if (this.selectedSegment != '全部'){
      query.equalTo('specialty', this.selectedSegment);
    }
    this.doctors = await query.find();
    console.log(this.doctors);
  }

  doctor1: any;

  // 打开医生详情模态框
  openDetailModal(doctor: any) {
    this.isModalOpen = true; // 打开模态框
    this.doctor1 = doctor; // 传递医生信息
  }

  closeDetailModal() {
    this.isModalOpen = false; // 关闭模态框
    this.doctor1 = null; // 清空医生信息
  }

  selectedOption: ConsultOption | undefined;

  async openConsult(){
    this.selectedOption = this.options.find(option => option.isSelected);
    if (!this.selectedOption) {
      // 显示 Toast 提示用户选择咨询方式
      const toast = await this.toastController.create({
        message: '请先选择咨询方式',
        duration: 2000,
        position: 'bottom'
      });
      toast.present();
      return;
    }

    if (this.selectedOption.title === '图文咨询' || this.selectedOption.title === '电话咨询') {
      this.isPaymentModalOpen = true;
    } else {
      // 处理其他选项（如需要）
    }
  }

  closePaymentModal() {
    this.isPaymentModalOpen = false;
  }

  num: number = 1;

  // 立即预约 Appointment Doctor User 
  async appoint(){
    let user = new CloudUser();
    console.log("this.doctor1",this.doctor1);
    let alert = await this.alertController.create({
      header: '温馨提示',
      subHeader: 'Tips',
      message: '预约成功，请等待医生回复',
      buttons: ['好的'],
    });
    let alert1 = await this.alertController.create({
      header: '温馨提示',
      subHeader: 'Tips',
      message: '已预约，不要重复预约',
      buttons: ['好的'],
    });
    let alert2 = await this.alertController.create({
      header: '温馨提示',
      subHeader: 'Tips',
      message: '您的个人信息不完整，请先完善个人信息（电话，姓名）',
      buttons: ['好的'],
    });
    if(this.num == 0){
      await alert1.present();
      return;
    }
    if(!user?.data["phone"] || !user?.data["realname"]){
      await alert2.present();
      return;
    }
    if(!user?.data["phone"] || !user?.data["realname"]){
      await alert2.present()
      return
    }
    if(this.num == 1){
      console.log("立即预约我的医生");
      let appointment = new CloudObject('appointment');
      appointment.set({
        doctor: {
          __type:"Pointer",
          className:"doctor",
          objectId:this.doctor1?.data["user"]?.objectId
        },
        doctorName: this.doctor1.data["name"],
        user: {
          __type:"Pointer",
          className:"user",
          objectId:user.id
        },
        type: this.type, // 咨询类型
        userPhone: user?.data["phone"], // 获取当前用户的手机号
        username : user?.data["realname"], // 获取当前用户的姓名
      });
      console.log("type",this.type)
      appointment.save();
      this.num = 0;
      console.log(appointment);
      await alert.present();
    }
  }
}