import { Component, OnInit, } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonContent, IonHeader,IonItem,IonList, IonThumbnail,IonTitle, IonToolbar,IonFooter, IonButtons,IonButton, IonBackButton, IonIcon } from '@ionic/angular/standalone';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';

@Component({
  selector: 'app-card-detail',
  templateUrl: './card-detail.page.html',
  styleUrls: ['./card-detail.page.scss'],
  standalone: true,
  imports: [IonIcon, IonContent, IonHeader,IonThumbnail,IonList, IonTitle,IonItem,IonFooter, IonToolbar,IonButtons,IonButton, IonBackButton, CommonModule, FormsModule]
})
export class CardDetailPage implements OnInit {

  content: CloudObject | null = null; // 用于存储当前内容的数据
  loading: boolean = true; // 添加加载状态
  error: string | null = null; // 添加错误状态
  prevContentData: CloudObject | null = null; // 前一篇文章
  nextContentData: CloudObject | null = null; // 后一篇文章
  contentsList: CloudObject[] = []; // 存储相同类型的文章列表
  currentUser: CloudUser | undefined;
  constructor(private activatedRoute: ActivatedRoute, private router: Router) { this.currentUser = new CloudUser();}

  ngOnInit() {
    // 获取传递的 ID
    const id = this.activatedRoute.snapshot.queryParamMap.get('id');
    if (id) {
      this.loadContentById(id);
    } else {
      this.error = '内容ID未找到';
      this.loading = false;
    }
  }

  async loadContentById(id: string) {
    try {
      let query = new CloudQuery("PL_Contents");
      query.equalTo('objectId', id); // 根据 ID 查询内容
      const results = await query.find();
      console.log('Loaded content:', results);
      if (results.length > 0) {
        this.content = results[0];
        if (this.content) {
          await this.loadContentsList(this.content.get('type')); // 加载内容列表
          this.findPrevAndNextContent(); // 在这里调用
        }
      } else {
        this.error = '内容未找到';
      }
    } catch (err) {
      this.error = '加载内容时出错';
      console.error(err);
    } finally {
      this.loading = false;
    }
  }

  async loadContentsList(type: string) {
    try {
      let query = new CloudQuery("PL_Contents");
      query.equalTo('type', type); // 根据类型查询内容
      query.orderByAscending('issue'); // 按 issue 升序排序
      this.contentsList = await query.find();
      console.log('Loaded contents list:', this.contentsList);
      this.findPrevAndNextContent(); // 确保在此调用
    } catch (err) {
      console.error('加载内容列表时出错:', err);
    }
  }

  findPrevAndNextContent() {
    if (!this.content || !this.contentsList) return;

    const contentId = this.content?.get('objectId');
    if (!contentId) return;

    const currentIndex = this.contentsList.findIndex(item => item.get('objectId') === contentId);
    console.log('Current index:', currentIndex);
    if (currentIndex > 0) {
      this.prevContentData = this.contentsList[currentIndex - 1];
    } else {
      this.prevContentData = null; // 如果没有上一篇，确保设置为null
    }
    if (currentIndex < this.contentsList.length - 1) {
      this.nextContentData = this.contentsList[currentIndex + 1];
    } else {
      this.nextContentData = null; // 如果没有下一篇，确保设置为null
    }

    console.log('Prev content:', this.prevContentData);
    console.log('Next content:', this.nextContentData);
  }

  prevContent() {
    if (this.prevContentData) {
      this.router.navigate(['/tabs/tab1/card-detail'], { queryParams: { id: this.prevContentData.get('objectId') } });
    }
  }

  nextContent() {
    if (this.nextContentData) {
      const nextId = this.nextContentData.get('objectId');
      console.log('Navigating to next content with ID:', nextId); // 添加日志以调试
      this.router.navigate(['/tabs/tab1/card-detail'], { queryParams: { id: nextId } });
    }
  }

  goBack() {
    this.router.navigate(['/tabs/tab1']); // 返回到 Tab1
  }

  async toggleLike() {
    if (!this.content || !this.currentUser?.id) {
      this.error = '请先登录';
      alert('请先登录');
      return;
    }
    try {
      const contentId = this.content.get('objectId');
      const userId = this.currentUser.id;
      let query = new CloudQuery("PL_UserRelation");
      query.equalTo('user_id', this.currentUser.toPointer());
      query.equalTo('article_id', this.content.toPointer());
      const results = await query.find();
      if (results.length > 0) {
        const relation = results[0];
        const isLiked = relation.get('is_liked');
        relation.set('is_liked', !relation.get('is_liked'));

        relation.set({
          'is_liked': !isLiked
        });

        await relation.save();

        this.content.set({
          'is_liked': !isLiked
        });

      } else {
        let newRelation = new CloudObject("PL_UserRelation");
        newRelation.set({
          'user_id': this.currentUser.toPointer(),
          'article_id': this.content.toPointer(),
          'is_liked': true,
          'is_favorite': false
        });
        await newRelation.save();

        this.content.set({
          'is_liked': true
        });

      }
      //this.content.set({'is_liked':!this.content.get('is_liked')});
    } catch (err) {
      this.error = '操作失败';
      console.error(err);
    }
  }

  async toggleFavorite() {
    if (!this.content || !this.currentUser?.id) {
      this.error = '请先登录';
      return;
    }
    try {
      const contentId = this.content.get('objectId');
      const userId = this.currentUser.id;
      let query = new CloudQuery("PL_UserRelation");
      query.equalTo('user_id', this.currentUser.toPointer());
      query.equalTo('article_id', this.content.toPointer());
      const results = await query.find();
      if (results.length > 0) {
        const relation = results[0];

        const isFavorite = relation.get('is_favorite');

        relation.set({
          'is_favorite': !isFavorite
        });
        await relation.save();
        this.content.set({
          'is_favorite': !isFavorite
        });
      } else {
        let newRelation = new CloudObject("PL_UserRelation");
        newRelation.set({
          'user_id': this.currentUser.toPointer(),
          'article_id': this.content.toPointer(),
          'is_liked': false,
          'is_favorite': true
        });
        await newRelation.save();
        this.content.set({
          'is_favorite': true
        });
      }
      //this.content.set({'is_favorite': !this.content.get('is_favorite')});
    } catch (err) {
      this.error = '操作失败';
      console.error(err);
    }
  }
}
