import { Component } from '@angular/core';
import { CloudUser } from '../../lib/ncloud';
import { Router } from '@angular/router';

@Component({
  selector: 'app-tab5',
  templateUrl: 'tab5.page.html',
  styleUrls: ['tab5.page.scss'],
  standalone: false, // 确保 standalone 设置为 false，否则可能会导致错误发生
})
export class Tab5Page {
  user = new CloudUser();
  username = '';
  password = '';
  isLoggedIn = false;
  currentUser: any = null;

  // 新增注册相关变量
  registerUsername = '';
  registerPassword = '';
  registerEmail = '';

  // 新增用户信息编辑相关变量
  editMode = false; // 确保添加该属性
  editedUsername = '';
  editedEmail = '';

  constructor(private router: Router) {
    this.checkLoginStatus();
  }

  async checkLoginStatus() {
    this.currentUser = await this.user.current();
    this.isLoggedIn = !!this.currentUser;
  }

  async login() {
    if (!this.username || !this.password) {
      alert('请输入用户名和密码');
      return;
    }

    const result = await this.user.login(this.username, this.password);
    if (result) {
      this.isLoggedIn = true;
      this.currentUser = result;
      // 保存sessionToken到本地存储
      localStorage.setItem('sessionToken', this.user.sessionToken as string);
      this.router.navigate(['/tabs/tab5/user-dashboard']);
    } else {
      alert('登录失败，请检查用户名和密码');
    }
  }

  async logout() {
    const success = await this.user.logout();
    if (success) {
      this.isLoggedIn = false;
      this.currentUser = null;
      // 清除本地存储的sessionToken
      localStorage.removeItem('sessionToken');
      alert('登出成功');
    } else {
      alert('登出失败');
    }
  }

  goToRegister() {
    this.router.navigate(['/tabs/tab5/register']);
  }

  enterEditMode() {
    this.editMode = true;
    this.editedUsername = this.currentUser?.data?.username || '';
    this.editedEmail = this.currentUser?.data?.email || '';
  }

  async saveEdit() {
    if (!this.editedUsername || !this.editedEmail) {
      alert('请输入用户名和邮箱');
      return;
    }

    try {
      this.user.set({
        username: this.editedUsername,
        email: this.editedEmail
      });
      await this.user.save();
      this.currentUser = this.user;
      this.editMode = false;
      alert('用户信息更新成功');
    } catch (error) {
      console.error('更新用户信息失败:', error);
      alert('更新用户信息失败，请重试');
    }
  }

  cancelEdit() {
    this.editMode = false;
  }

  goToLogout() {
    this.router.navigate(['/tabs/tab5/logout']);
  }
}
