import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ExploreContainerComponent } from '../explore-container/explore-container.component';
import { IonicModule } from '@ionic/angular';
import { CommonModule } from '@angular/common';
import { addIcons } from 'ionicons';
import { bookmarkOutline, cartOutline, documentTextOutline, downloadOutline, ellipsisHorizontal, heartOutline, imageOutline, imagesOutline, search, timeOutline, walletOutline } from 'ionicons/icons';
import { EnvironmentInjector, inject } from '@angular/core';
import { openUserEditModal } from 'src/lib/user/modal-user-edit/modal-user-edit.component';
import { openUserLoginModal } from 'src/lib/user/modal-user-login/modal-user-login.component';
import { CloudObject, CloudQuery, CloudUser } from 'src/lib/ncloud';
import { ModalController } from '@ionic/angular/standalone';
import { AlertController } from '@ionic/angular/standalone'; // 导入所需的模块

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss'],
  standalone: true,
  imports: [ExploreContainerComponent, IonicModule, CommonModule],
})
export class Tab3Page implements OnInit{
  profile = {
    vipStatus: true,
    avatar: '../../assets/image/07/1.jpg', // 默认头像路径
    // buttons: [
    //   { icon: 'time-outline', text: '浏览记录' },
    //   { icon: 'download-outline', text: '我的下载' },
    //   { icon: 'cart-outline', text: '我的购买' },
    //   { icon: 'wallet-outline', text: '我的钱包' }
    // ],
    tabs: [
      { icon: 'images-outline', text: '全部' },
      { icon: 'image-outline', text: '图文' },
      { icon: 'document-text-outline', text: '文章' }
    ]
  };

  showTabs = false;
  activeTab: string | null = null; // 初始状态为null
  public environmentInjector = inject(EnvironmentInjector);

  currentUser: CloudUser | undefined;
  // 创建用于存储喜欢或收藏的文章内容的属性
  favoriteOrLikedContents: Array<CloudObject> = [];
  error:string|null = null;
  loading: boolean = false;
  constructor(
    private router: Router,
    private alertController: AlertController,
    private modalCtrl: ModalController
  ) {
    this.currentUser = new CloudUser();
    addIcons({ 
      search, ellipsisHorizontal, timeOutline, downloadOutline, cartOutline, walletOutline, 
      heartOutline, bookmarkOutline, imageOutline, imagesOutline, documentTextOutline 
    });
  }

  toggleTabs(action: string) {
    this.showTabs = !this.showTabs;
    if (action === 'like') {
      this.setActiveTab('like'); // 设置为 'like'
    } else if (action === 'collect') {
      this.setActiveTab('collect'); // 设置为 'collect'
    }
  }

  ngOnInit() {
    // 生命周期
    this.loadPLContentsList();
    if(this.currentUser?.id){
      this.loadFavoriteOrLikedContents(this.currentUser.id);
    }else {
      console.log('未登录');
    }
  }

  // 创建用于数据列表存储的属性
  PLContentsList:Array<CloudObject> = []

  async loadPLContentsList(){
    let query = new CloudQuery("PL_Contents");
    this.PLContentsList = await query.find()
  }
  setActiveTab(tab: string | null) {
    this.activeTab = tab;
    this.updateContent();
  }

  updateContent() {
    const contentContainer = document.getElementById('content-container');
    if (!contentContainer) return;
  
    if (!this.showTabs || this.activeTab === null) {
      contentContainer.innerHTML = '';
      return;
    }
  
    // 第一次筛选：根据 like 和 favorite 进行筛选
    let filteredContents: CloudObject[] = [];
    switch (this.activeTab) {
      case 'like':
        filteredContents = this.favoriteOrLikedContents.filter(content => content.get('is_liked') === true);
        break;
      case 'collect':
        filteredContents = this.favoriteOrLikedContents.filter(content => content.get('is_favorite') === true);
        break;
      default:
        filteredContents = this.favoriteOrLikedContents;
    }
  
    // 第二次筛选：根据 all、image 和 document 进行进一步的筛选
    switch (this.activeTab) {
      case 'all':
        // 不需要进一步筛选，保持 filteredContents 不变
        break;
      case 'image':
        filteredContents = filteredContents.filter(content => content.get('type') === '图文');
        break;
      case 'document':
        filteredContents = filteredContents.filter(content => content.get('type') === '故诗');
        break;
    }
  
    // 渲染内容
    if (filteredContents.length > 0) {
      contentContainer.innerHTML = filteredContents.map(content => `
        <div class="content-item">
          <h2>${content.get('title')}</h2>
          <p>${content.get('snippet')}</p>
          <p>类型: ${content.get('type')}</p>
          <p>发布时间: ${content.get('time')}</p>
          <img src="${content.get('image')}" alt="${content.get('title')} 图片" />
        </div>
      `).join('');
    } else {
      contentContainer.innerHTML = `<p>暂时还没有相关内容呢，快去添加吧。</p>`;
    }
  }
  navigateToLogin() {
    this.router.navigate(['/tabs/login']);
  }

  openVipPage() {
    alert("不允许你花钱！！！");
  }

  onFileSelected(event: Event) {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      const file = input.files[0];
      const reader = new FileReader();

      reader.onload = (e: any) => {
        this.profile.avatar = e.target.result; // 将读取的图片设置为头像
      };

      reader.readAsDataURL(file); // 读取文件为Data URL
    }
  }

  async login() {
    // 弹出登录窗口
    let user = await openUserLoginModal(this.modalCtrl);
    if (user?.id) {
      this.currentUser = user;
    }
  }

  async signup() {
    // 弹出注册窗口
    let user = await openUserLoginModal(this.modalCtrl, "signup");
    if (user?.id) {
      this.currentUser = user;
    }
  }

  logout() {
    this.currentUser?.logout();
  }

  editUser() {
    if (this.currentUser) {
      openUserEditModal(this.modalCtrl); // 假设 modalCtrl 内部会处理 currentUser
    } else {
      console.error("未登录，无法执行此操作");
    }
  }

  editTags: Array<string> = [];

  async setTagsValue(ev: any) {
    let currentUser = new CloudUser();
    let userPrompt = ``;
    if (!currentUser?.id) {
      console.log("用户未登录，请登录后重试");
      let user = await openUserLoginModal(this.modalCtrl);
      if (!user?.id) {
        return;
      }
      currentUser = user;
    }
    this.editTags = ev;
  }

  async showAlert() {
    const alert = await this.alertController.create({
      header: '提示', // 提示框的标题
      message: '请先登录以查看个人信息。', // 提示框的消息
      buttons: ['确定'], // 按钮文本，用户点击后关闭提示框
    });

    await alert.present(); // 显示提示框
  }
  async loadFavoriteOrLikedContents(userId: string) {
    try {
      this.loading = true;
      let query = new CloudQuery("PL_UserRelation");
      query.equalTo('user_id', userId); // 根据用户ID查询
      const subQuery1 = new CloudQuery("PL_UserRelation");
      subQuery1.equalTo('is_favorite', true);
      const subQuery2 = new CloudQuery("PL_UserRelation");
      subQuery2.equalTo('is_liked', true);
      query.or(subQuery1, subQuery2); // 查询 is_favorite 或 is_like 为 true 的记录
      const userRelations = await query.find();
      console.log('User relations:', userRelations);

      // 获取所有符合条件的 article_id
      const articleIds = userRelations.map((relation: CloudObject) => relation.get('article_id'));

      // 根据 article_id 查询 PL_Contents 表
      if (articleIds.length > 0) {
        let contentQuery = new CloudQuery("PL_Contents");
        contentQuery.containedIn('objectId', articleIds); // 使用 containedIn 查询多个 article_id
        this.favoriteOrLikedContents = await contentQuery.find();
        console.log('Favorite or liked contents:', this.favoriteOrLikedContents);
      }
    } catch (err) {
      this.error = '加载喜欢或收藏的内容时出错';
      console.error(err);
    } finally {
      this.loading = false;
    }
  }
}



