import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AlertController } from '@ionic/angular';
import { CloudUser, CloudObject, CloudQuery } from 'src/lib/ncloud';

@Component({
  selector: 'app-dynamic-detail',
  templateUrl: './dynamic-detail.page.html',
  styleUrls: ['./dynamic-detail.page.scss'],
  standalone:false,
})
export class DynamicDetailPage implements OnInit {
  dynamic: any = null;
  currentUser: any = null;
  comments: any[] = [];
  isLiked = false;

  constructor(
    private route: ActivatedRoute,
    private alertController: AlertController
  ) {}

  async ngOnInit() {
    const dynamicId = this.route.snapshot.paramMap.get('id');
    //const dynamicId = this.route.snapshot.paramMap.get('id');
    if (!dynamicId) {
      // 处理id不存在的情况，比如重定向或显示错误
      console.error('Dynamic ID is missing');
      return;
    }
    this.currentUser = new CloudUser();
    await this.currentUser.current();
    
    await this.loadDynamic(dynamicId);
    await this.loadComments(dynamicId);
    await this.checkUserInteraction(dynamicId);
  }

  async loadDynamic(dynamicId: string) {
    const query = new CloudQuery("Dynamic");
    query.include("author");
    this.dynamic = await query.get(dynamicId);
  }

  async loadComments(dynamicId: string) {
    const query = new CloudQuery("Interaction");
    query.equalTo("dynamic", dynamicId);
    query.equalTo("type", "comment");
    query.include("user");
    query.include("targetUser");
    this.comments = await query.find();
  }

  async checkUserInteraction(dynamicId: string) {
    if (!this.currentUser.id) return;
    
    const query = new CloudQuery("Interaction");
    query.equalTo("user", this.currentUser.id);
    query.equalTo("dynamic", dynamicId);
    query.equalTo("type", "like");
    const likeInteraction = await query.first();
    this.isLiked = !!likeInteraction;
  }

  async toggleLike() {
    const dynamicId = this.dynamic.id;
    
    if (this.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();
      }
      
      this.dynamic.set({
        likeCount: this.dynamic.get('likeCount') - 1
      });
    } else {
      // 点赞
      const interaction = new CloudObject("Interaction");
      interaction.set({
        type: "like",
        user: this.currentUser.toPointer(),
        dynamic: this.dynamic.toPointer()
      });
      await interaction.save();
      
      this.dynamic.set({
        likeCount: this.dynamic.get('likeCount') + 1
      });
    }
    
    await this.dynamic.save();
    this.isLiked = !this.isLiked;
  }

  async addComment() {
    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: this.dynamic.toPointer()
              });
              await interaction.save();
              
              // 更新计数器
              this.dynamic.set({
                commentCount: this.dynamic.get('commentCount') + 1
              });
              await this.dynamic.save();
              
              // 刷新评论列表
              await this.loadComments(this.dynamic.id);
            }
          }
        }
      ]
    });

    await alert.present();
  }

  async shareDynamic() {
    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;
              
              const interaction = new CloudObject("Interaction");
              interaction.set({
                type: "share",
                user: this.currentUser.toPointer(),
                dynamic: this.dynamic.toPointer(),
                targetUser: targetUser.toPointer()
              });
              await interaction.save();
              
              this.dynamic.set({
                shareCount: this.dynamic.get('shareCount') + 1
              });
              await this.dynamic.save();
            }
          }
        }
      ]
    });

    await alert.present();
  }
}