import { Component, OnInit } from '@angular/core';
import { ModalController, AlertController } from '@ionic/angular';
import { NewPostPage } from '../new-post/new-post.page'; // 假设我们有一个新帖子页面
import { UserService } from '../services/user.service'; // 导入 UserService
import { Subscription, forkJoin, firstValueFrom } from 'rxjs';

@Component({
  selector: 'app-health-community',
  templateUrl: './health-community.page.html',
  styleUrls: ['./health-community.page.scss'],
})
export class HealthCommunityPage implements OnInit {
  posts = [
    {
      id: 1,
      title: '如何保持健康的饮食习惯',
      author: '张三',
      date: new Date('2024-12-18'),
      content: '保持健康的饮食习惯对于维持良好的身体状态非常重要...',
      imageUrl: '../../assets/images/user1.jpg', // 确保图片路径正确
      authorAvatar: '' // 添加作者头像属性，默认为空字符串
    },
    {
      id: 2,
      title: '运动的好处及建议',
      author: '李四',
      date: new Date('2024-12-17'),
      content: '适量的运动不仅有助于增强体质，还能改善心情...',
      imageUrl: '../../assets/images/user2.jpg', // 确保图片路径正确
      authorAvatar: '' // 添加作者头像属性，默认为空字符串
    },
    // 添加更多帖子...
  ];
  private userSubscription: Subscription | undefined;
  currentUser: string | null = null; // 存储当前用户名

  constructor(
    private modalCtrl: ModalController,
    private userService: UserService, // 注入 UserService
    private alertController: AlertController, // 注入 AlertController
  ) {}

  isCurrentUser(author: string): boolean {
    return this.currentUser === author;
  }

  async confirmDeletePost(index: number) {
    const alert = await this.alertController.create({
      header: '确认删除',
      message: '确定要删除这条帖子吗？',
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary'
        },
        {
          text: '确定',
          handler: () => {
            this.deletePost(index);
          }
        }
      ]
    });

    await alert.present();
  }

  deletePost(index: number) {
    // 从帖子数组中移除指定索引的帖子
    this.posts.splice(index, 1);

    // 更新本地存储中的帖子数据
    localStorage.setItem('posts', JSON.stringify(this.posts));

    console.log('Post deleted:', index);
  }

  ngOnInit() {
    // 加载本地存储中的帖子数据
    const savedPosts = localStorage.getItem('posts');
    if (savedPosts) {
      this.posts = JSON.parse(savedPosts);
    }
  
    // 获取当前用户的用户名
    this.userService.getUserInfo().subscribe(userInfo => {
      if (userInfo) {
        this.currentUser = userInfo.username || '当前用户'; // 根据实际情况设置默认值
        // 更新当前用户自己的帖子的作者头像
        this.posts.forEach(post => {
          if (post.author === this.currentUser) {
            post.authorAvatar = userInfo.userAvatar || '';
          }
        });
      }
    });
  }

  goToPostDetail(post: any) {
    // 这里可以实现导航到详细页面的逻辑
    console.log('Go to post detail:', post);
  }

  async openNewPost() {
    const modal = await this.modalCtrl.create({
      component: NewPostPage,
      cssClass: 'my-custom-class'
    });

    try {
      await modal.present();

      const data = await modal.onDidDismiss();

      if (data && data.data) {
        // 在创建新帖子之前获取当前用户的头像
        const currentUserInfo = await firstValueFrom(this.userService.getUserInfo());
        const authorAvatar = currentUserInfo?.userAvatar || '../../assets/images/user.png';

        const newPost = {
          id: this.posts.length + 1,
          title: data.data.title,
          author: this.currentUser || '当前用户', // 使用当前用户名
          date: new Date(),
          content: data.data.content,
          imageUrl: data.data.imageUrl || '../assets/images/user3.jpg', // 根据实际需求设置默认图片或允许上传图片
          authorAvatar: authorAvatar // 添加作者头像
        };
        this.posts.unshift(newPost); // 将新帖子添加到最前面
        // 保存更新后的帖子列表到本地存储
        localStorage.setItem('posts', JSON.stringify(this.posts));
      }
    } catch (error) {
      console.error('Error presenting modal or handling dismissal:', error);
    }
  }
}