import { Component, AfterViewInit } from '@angular/core';
import { Router } from '@angular/router';
import { ModalController, NavController, ToastController } from '@ionic/angular';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { throwError } from 'rxjs';

interface User {
  username: string;
  password: string;
}

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page implements AfterViewInit {

  doctors = [
    {
      avatar: '../../assets/images/doctor.png',
      name: '张医生',
      specialty: '心血管科'
    },
    {
      avatar: '../../assets/images/doctor.png',
      name: '李医生',
      specialty: '神经科'
    },
    {
      avatar: '../../assets/images/doctor.png',
      name: '王医生',
      specialty: '儿科'
    },
    {
      avatar: '../../assets/images/doctor.png',
      name: '赵医生',
      specialty: '外科'
    },
    {
      avatar: '../../assets/images/doctor.png',
      name: '陈医生',
      specialty: '内科'
    }
  ];

  // 功能按钮数据
  functionItems1 = [
    { label: '我的病历', icon: 'document-text', route: '/medical-records' },
    { label: '在线问诊', icon: 'chatbubbles', route: '/online-consultation' },
    { label: '健康档案', icon: 'person', route: '/health-profile' },
    { label: '预约挂号', icon: 'calendar', route: '/appointment' },
    { label: '健康资讯', icon: 'newspaper', route: '/health-news' }
  ];

  functionItems2 = [
    { label: '药品购买', icon: 'medkit', route: '/medicine-purchase' },
    { label: '体检套餐', icon: 'clipboard', route: '/checkup-packages' },
    { label: '专家讲座', icon: 'podium', route: '/expert-lectures' },
    { label: '远程医疗', icon: 'videocam', route: '/telemedicine' },
    { label: '健康社区', icon: 'people', route: '/health-community' }
  ];

  currentIndex = 0;
  startX: number = 0;
  endX: number = 0;
  isDragging: boolean = false;
  currentTranslate: number = 0;
  cardWidth = 216; // 每个卡片的宽度加上间距 (200 + 16)
  isCyclic: boolean = true;
  errorMessage: string = ''; // 错误消息
  isLoginModalOpen = false;
  user: User = { username: '', password: '' };

  constructor(
    private router: Router,
    private modalController: ModalController,
    private navCtrl: NavController,
    private http: HttpClient,
    private toastController: ToastController // 添加 ToastController 注入
  ) {}

  // 实现 AfterViewInit 接口的 ngAfterViewInit 方法
  ngAfterViewInit(): void {
    this.ngAfterViewInitLogic();
  }

  // 将初始化逻辑移到单独的方法中，以保持代码清晰
  private ngAfterViewInitLogic() {
    this.updateCarousel();
    this.calculateCardWidth();
  }

  calculateCardWidth() {
    const container = document.getElementById('carousel');
    if (container && container.children.length > 0) {
      const firstCard = container.children[0] as HTMLElement;
      this.cardWidth = firstCard.offsetWidth + 16; // 加上间距
    }
  }

  updateCarousel() {
    this.currentTranslate = -this.currentIndex * this.cardWidth;
    this.updateCarouselPosition();
  }

  updateCarouselPosition() {
    const container = document.getElementById('carousel');
    if (container) {
      container.style.transform = `translateX(${this.currentTranslate}px)`;
    }
  }

  onTouchStart(event: TouchEvent) {
    this.startX = event.touches[0].clientX;
    this.isDragging = true;
  }

  onTouchMove(event: TouchEvent) {
    if (this.isDragging) {
      const touchX = event.touches[0].clientX;
      const deltaX = touchX - this.startX;
      this.currentTranslate = -this.currentIndex * this.cardWidth + deltaX;

      const maxTranslate = -(this.doctors.length - 1) * this.cardWidth;
      this.currentTranslate = Math.max(Math.min(this.currentTranslate, 0), maxTranslate);

      this.updateCarouselPosition();
    }
  }

  onTouchEnd(event: TouchEvent) {
    this.endX = event.changedTouches[0].clientX;
    this.isDragging = false;

    const swipeThreshold = 50;
    const deltaX = this.startX - this.endX;

    if (deltaX > swipeThreshold) {
      this.nextSlide();
    } else if (deltaX < -swipeThreshold) {
      this.prevSlide();
    } else {
      this.snapToNearestCard();
    }
  }

  prevSlide() {
    if (this.isCyclic) {
      this.currentIndex = (this.currentIndex - 1 + this.doctors.length) % this.doctors.length;
    } else if (this.currentIndex > 0) {
      this.currentIndex--;
    }
    this.updateCarousel();
  }

  nextSlide() {
    if (this.isCyclic) {
      this.currentIndex = (this.currentIndex + 1) % this.doctors.length;
    } else if (this.currentIndex < this.doctors.length - 1) {
      this.currentIndex++;
    }
    this.updateCarousel();
  }

  snapToNearestCard() {
    const cardIndex = Math.round(-this.currentTranslate / this.cardWidth);
    this.currentIndex = Math.max(0, Math.min(cardIndex, this.doctors.length - 1));
    this.updateCarousel();
  }

  onConsultNow() {
    console.log(`立即咨询`);
    this.router.navigate(['/consultation']);
  }

  onlineConsultNow(doctor: any) {
    console.log(`在线咨询: ${doctor.name}`);
    this.router.navigate(['/consultation'], { state: { doctor: doctor } });
  }

  navigateTo(route: string) {
    this.router.navigate([route]);
  }

  publishHealthInfo() {
    console.log('发布求医信息');
  }

  openLoginModal() {
    this.isLoginModalOpen = true;
    console.log('打开登录/注册模态框');
  }

  closeLoginModal() {
    this.isLoginModalOpen = false;
    console.log('关闭登录/注册模态框');
  }

  onLoginModalDismissed(event: any) {
    this.isLoginModalOpen = false;
    console.log('登录/注册模态框已关闭');
  }

  async onLoginFormSubmit(formValue: any) {
    console.log('登录表单提交:', formValue);

    // 验证用户名和密码长度
    if (formValue.username.length < 3) {
      await this.presentToast('用户名至少需要3位字符', 'danger');
      return;
    }

    if (formValue.password.length < 6) {
      await this.presentToast('密码至少需要6位字符', 'danger');
      return;
    }

    this.loginUser(formValue.username, formValue.password)
      .subscribe(
        async (response) => {
          console.log('登录成功:', response);
          await this.presentToast('登录成功', 'success');
          this.closeLoginModal();
        },
        async (error) => {
          console.error('登录失败:', error);
          await this.presentToast('登录失败，请检查用户名和密码', 'danger');
        }
      );
  }

  registerUser() {
    if (!this.user.username || !this.user.password) {
      console.error('用户名或密码为空');
      this.presentToast('用户名和密码不能为空，请输入完整信息', 'danger');
      return;
    }

    // 验证用户名和密码长度
    if (this.user.username.length < 3) {
      this.presentToast('用户名至少需要3位字符', 'danger');
      return;
    }

    if (this.user.password.length < 6) {
      this.presentToast('密码至少需要6位字符', 'danger');
      return;
    }

    console.log('注册用户:', JSON.stringify(this.user, null, 2));

    this.registerNewUser(this.user)
      .subscribe(
        async (response) => {
          console.log('注册成功:', response);
          await this.presentToast('注册成功', 'success');
          this.closeLoginModal();
        },
        async (error) => {
          console.error('注册失败:', error);
          if (error.error && error.error.message.includes('cannot be null')) {
            await this.presentToast('密码不能为空，请输入密码', 'danger');
          } else {
            await this.presentToast('注册失败，请稍后再试', 'danger');
          }
        }
      );
  }

  private loginUser(username: string, password: string): Observable<any> {
    const loginUrl = 'http://localhost:8080/api/login'; // 替换为你的登录 API 端点
    return this.http.post(loginUrl, { username, password }, {
      withCredentials: true,
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    }).pipe(
      map(response => response),
      catchError(error => {
        console.error('登录请求出错:', error);
        return throwError(() => new Error('登录失败'));
      })
    );
  }

  private registerNewUser(user: User): Observable<any> {
    const registerUrl = 'http://localhost:8080/api/register'; // 替换为你的注册 API 端点
    return this.http.post(registerUrl, user)
      .pipe(
        map(response => response),
        catchError(error => {
          throw error;
        })
      );
  }

  onLearnMore() {
    this.navCtrl.navigateForward('/details');
  }

  async presentToast(message: string, color: string) {
    const toast = await this.toastController.create({
      message: message,
      duration: 2000,
      color: color,
      position: 'top',
    });
    toast.present();
  }
}



