import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { ActivatedRoute, Router } from '@angular/router'; 
import { CloudUser, CloudObject, CloudQuery } from 'src/lib/ncloud';
import { importTestData } from 'src/lib/import-data';
import { AlertController } from '@ionic/angular';
@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss'],
  standalone: false,
})
export class Tab2Page implements OnInit {

  isLoading = true; // 添加加载状态变量
  currentUser: any = null;
  dynamics: any[] = [];
  userInteractions: Record<string, any> = {}; // 记录用户对每个动态的互动状态
  // 在组件类中添加
  tabs = [
    { id: 0, title: '推荐' },
    { id: 1, title: '关注' },
    { id: 2, title: '话题' }
  ];
  activeTab = 0;

  switchTab(tabId: number) {
    this.activeTab = tabId;
    // 这里可以添加切换内容的逻辑
  }
  constructor(
    private navCtrl:NavController,
    private router: Router,
    private alertController: AlertController,
    private activatedRoute: ActivatedRoute
  ) {
    //this.chaXun()
    this.activatedRoute.params.subscribe(()=>{
      this.loadData();
    })
  }

  goToManage(){
    this.navCtrl.navigateForward(["tabs","tab2","management"])
  }

  // async chaXun(){
  //   //获取当前用户
  //   let user:any =new CloudUser();
  //   console.log(user)
  //   //user = user.current();
  //   let query =new CloudQuery("Dynamic")
  //   query.equalTo("user",user.id)
  //   //query.include("dynamic");
  //   console.log(await query.find())
  // }

  async ngOnInit() {
     await this.loadData();
  }

  goToDynamic(dynamicId:string){
    this.navCtrl.navigateForward(["tabs","tab2","dynamic-detail",dynamicId])
    //this.router.navigate(['/dynamic-detail', dynamicId]);
  }

  addDynamic(){
    this.navCtrl.navigateForward(["tabs","tab2","dynamic-create"])
  }

  async loadData() {
    
    this.isLoading = true; // 开始加载
    try {
    // 获取当前用户
    this.currentUser = new CloudUser();
    const user = await this.currentUser.current();
    if (!user) {
      console.log('用户未登录');
      return;
    }

    // 查询所有公开动态
    const dynamicQuery = new CloudQuery("Dynamic");
    dynamicQuery.equalTo("isPublic", true);
    dynamicQuery.include("author");
    this.dynamics = await dynamicQuery.find();

    // 查询当前用户的互动
    const interactionQuery = new CloudQuery("Interaction");
    interactionQuery.equalTo("user", this.currentUser.id);
    interactionQuery.include("user"); // 包含互动用户信息
    const interactions = await interactionQuery.find();

    // 初始化互动状态
    this.userInteractions = {};
    interactions.forEach((interaction: any) => {
      const dynamicId = interaction.get('dynamic')?.objectId;
      if (dynamicId) {
        this.userInteractions[dynamicId] = {
          liked: interaction.get('type') === 'like',
          commented: interaction.get('type') === 'comment',
          shared: interaction.get('type') === 'share'
        };
      }
    });
  }catch (error) {
      console.error('加载动态失败:', error);
    } finally {
      this.isLoading = false; // 结束加载
    }
  }

  // 点赞/取消点赞
  async toggleLike(dynamic: any) {
    const dynamicId = dynamic.id;
    const isLiked = this.userInteractions[dynamicId]?.liked;

    const interaction = new CloudObject("Interaction");
    
    if (isLiked) {
      // 取消点赞 - 删除互动记录
      const query = new CloudQuery("Interaction");
      query.equalTo("user", this.currentUser.id);
      query.equalTo("dynamic", dynamicId);
      query.equalTo("type", "like");
      const likeInteraction = await query.first();
      
      if (likeInteraction) {
        await likeInteraction.destroy();
      }
      
      // 更新计数器
      dynamic.set({
        likeCount: dynamic.get('likeCount') - 1
      });
    } else {
      // 点赞 - 创建互动记录
      interaction.set({
        type: "like",
        user: this.currentUser.toPointer(),
        dynamic: dynamic.toPointer()
      });
      await interaction.save();
      
      // 更新计数器
      dynamic.set({
        likeCount: dynamic.get('likeCount') + 1
      });
    }
    
    await dynamic.save();
    await this.loadData(); // 刷新数据
  }

  // 评论
  async addComment(dynamic: any) {
    const alert = await this.alertController.create({
      header: '添加评论',
      inputs: [
        {
          name: 'comment',
          type: 'text',
          placeholder: '输入评论内容'
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '提交',
          handler: async (data) => {
            if (data.comment) {
              const interaction = new CloudObject("Interaction");
              interaction.set({
                type: "comment",
                content: data.comment,
                user: this.currentUser.toPointer(),
                dynamic: dynamic.toPointer()
              });
              await interaction.save();
              
              // 更新计数器
              dynamic.set({
                commentCount: (dynamic.get('commentCount') + 1)
              });
              await dynamic.save();
              
              await this.loadData(); // 刷新数据
            }
          }
        }
      ]
    });

    await alert.present();
  }

  // 分享
  async shareDynamic(dynamic: any) {
    const alert = await this.alertController.create({
      header: '分享动态',
      message: '选择要分享给的用户',
      inputs: [
        {
          name: 'user1',
          type: 'radio',
          label: '用户1',
          value: 'user1',
          checked: true
        },
        {
          name: 'user2',
          type: 'radio',
          label: '用户2',
          value: 'user2'
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '分享',
          handler: async (data) => {
            if (data) {
              // 这里简化处理，实际应该查询目标用户
              const targetUser = new CloudObject("_User");
              targetUser.id = data; // 实际应该使用用户ID
              
              const interaction = new CloudObject("Interaction");
              interaction.set({
                type: "share",
                user: this.currentUser.toPointer(),
                dynamic: dynamic.toPointer(),
                targetUser: targetUser.toPointer()
              });
              await interaction.save();
              
              // 更新计数器
              dynamic.set({
                shareCount: (dynamic.get('shareCount') + 1)
              });
              await dynamic.save();
              
              await this.loadData(); // 刷新数据
            }
          }
        }
      ]
    });

    await alert.present();
  }


  importData(){
    importTestData();
  }

  goThankslist(thanks?:string){
    this.navCtrl.navigateForward(["tabs","tab2","thanks"],{
      
    })
  }
  navigateToDetail() { // 定义一个方法用于导航到详情页面
    if (this.router.url !== '/detail') { // 检查当前 URL 是否不是目标页面
      this.router.navigateByUrl('/detail').then(() => { // 如果不是，则导航到详情页面
        console.log('Navigation completed.'); // 导航完成后打印日志
      }).catch(error => { // 捕获并处理可能发生的错误
        console.error('Navigation failed:', error); // 打印错误信息
      });
    } else { // 如果已经是目标页面
      console.warn('Already on the detail page, no need to navigate.'); // 打印警告信息
    }
  } 
}
