import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { UserService } from '../services/user.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page implements OnInit {

  username: string = '';
  userAvatar: string | null = '../../assets/images/user-avatar.png'; // 允许 null
  userType: string = '普通用户';
  previewImage: string | null = null;
  private userInfoSubscription?: Subscription;

  // 状态变量
  hasUnreadHealthRecords = false; // 是否有未读健康记录
  hasPendingAppointments = false; // 是否有待处理预约
  hasNewPromotions = false; // 是否有新的优惠活动
  hasUnprocessedOrders = false; // 是否有待处理订单

  constructor(private navCtrl: NavController, private userService: UserService) {}

  ngOnInit() {
    this.loadUserInfo();
    this.checkStatuses(); // 初始化时检查状态
  }

  ionViewWillEnter() {
    this.loadUserInfo();
    this.checkStatuses(); // 每次进入页面时检查状态
  }

  ngOnDestroy() {
    if (this.userInfoSubscription) {
      this.userInfoSubscription.unsubscribe();
    }
  }

  private loadUserInfo() {
    // 取消之前的订阅（如果有）
    if (this.userInfoSubscription) {
      this.userInfoSubscription.unsubscribe();
    }
    // 订阅最新的用户信息
    this.userInfoSubscription = this.userService.getUserInfo().subscribe(userInfo => {
      if (userInfo) {
        this.username = userInfo.username ?? this.username;
        this.userAvatar = userInfo.userAvatar ?? null; // 确保预览图像是最新的头像或默认值
        this.userType = userInfo.userType ?? '普通用户';
        this.previewImage = userInfo.userAvatar ?? null; // 设置预览图像
      } else {
        this.userAvatar = '../../assets/images/user-avatar.png'; // 如果没有用户信息，使用默认头像
        this.previewImage = null;
      }
    });
  }

  private checkStatuses() {
    // 模拟检查各个功能区的状态
    // 实际应用中应从服务器获取最新状态
    this.hasUnreadHealthRecords = true;
    this.hasPendingAppointments = true;
    this.hasNewPromotions = true;
    this.hasUnprocessedOrders = true;
  }

  editProfile() {
    console.log('编辑用户资料');
    this.navCtrl.navigateForward('/edit-profile');
  }

  viewHealthRecord() {
    console.log('查看/编辑健康档案');
    this.navCtrl.navigateForward('/health-record');
  }

  viewMedicalServices() {
    console.log('查看医疗服务');
    this.navCtrl.navigateForward('/medical-services');
  }

  viewPointsAndCoupons() {
    console.log('查看积分与优惠');
    this.navCtrl.navigateForward('/points-and-coupons');
  }

  viewOrders() {
    console.log('查看订单管理');
    this.navCtrl.navigateForward('/orders');
  }

  goToFaq() {
    console.log('跳转到常见问题页面');
    this.navCtrl.navigateForward('/faq');
  }

  goToFeedback() {
    console.log('跳转到意见反馈页面');
    this.navCtrl.navigateForward('/feedback');
  }

  inviteFriends() {
    console.log('邀请好友');
    this.navCtrl.navigateForward('/invite-friends');
  }

  manageFamily() {
    console.log('家人管理');
    this.navCtrl.navigateForward('/manage-family');
  }
}