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 = 'src/assets/images/user.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() {
    this.userAvatar = '/assets/images/user.png'; // 立即设置默认头像
  
    // 取消之前的订阅（如果有）
    if (this.userInfoSubscription) {
      this.userInfoSubscription.unsubscribe();
    }
  
    // 订阅最新的用户信息
    this.userInfoSubscription = this.userService.getUserInfo().subscribe(userInfo => {
      if (userInfo && userInfo.userAvatar) {
        this.userAvatar = userInfo.userAvatar;
        this.previewImage = userInfo.userAvatar;
      }
      // 如果 userInfo 为 null 或 undefined，保持默认头像不变
    });
  }

  private checkStatuses() {
    // 尝试从 localStorage 加载状态
  const savedStates = JSON.parse(localStorage.getItem('userStatuses') || '{}');

  this.hasUnreadHealthRecords = savedStates.hasUnreadHealthRecords ?? false;
  this.hasPendingAppointments = savedStates.hasPendingAppointments ?? false;
  this.hasNewPromotions = savedStates.hasNewPromotions ?? false;
  this.hasUnprocessedOrders = savedStates.hasUnprocessedOrders ?? false;
  }

  private saveStatuses() {
    const userStatuses = {
      hasUnreadHealthRecords: this.hasUnreadHealthRecords,
      hasPendingAppointments: this.hasPendingAppointments,
      hasNewPromotions: this.hasNewPromotions,
      hasUnprocessedOrders: this.hasUnprocessedOrders
    };
  
    localStorage.setItem('userStatuses', JSON.stringify(userStatuses));
  }

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

  viewHealthRecord() {
    console.log('查看/编辑健康档案');
    this.navCtrl.navigateForward('/health-record');
    this.hasUnreadHealthRecords = false; // 标记为已读
    this.saveStatuses(); // 保存状态
  }

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

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

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

  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');
  }
}