import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import * as Parse from 'parse';
import { ModalController } from '@ionic/angular';
import { PageChatPanelComponent } from '../page-chat-panel/page-chat-panel.component'; // 引入PageChatPanelComponent

interface Item {
  name: string;
  description: string;
  imgUrl: string;
 detailId: string;
}

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
  items: Item[] = [];
  currentContent: string = 'module-one';
  chatPanelOpen: boolean = false; // 添加一个标记来跟踪聊天面板的打开状态


  constructor(private router: Router,private modalController: ModalController) {}

  ngOnInit() {
    this.getData();
  }

  getData() {
    (Parse as any).serverURL = 'https://web2023.fmode.cn/parse';
    Parse.initialize('dev');

    let query: Parse.Query;
    if (this.currentContent === 'module-one') {
      query = new Parse.Query('LcmModuleOne');
    } else if (this.currentContent === 'module-two') {
      query = new Parse.Query('LcmModuleTwo');
    } else if (this.currentContent === 'module-three') {
      query = new Parse.Query('LcmModuleThree');
    } else {
      return; // 如果没有匹配的模块，退出方法
    }

    query.find()
      .then((results) => {
        this.items = results.map((result) => ({
          name: result.get('name'),
          description: result.get('description'),
          imgUrl: result.get('imgUrl'),
         detailId: result.get('detailId')
        }));
        console.log(this.items);
      })
      .catch((error) => {
        console.error('Error retrieving data from Parse:', error);
      });
  }

  selectItem(item: Item) {
    localStorage.setItem('selectedItem', JSON.stringify(item)); // 存储选定的项目到localStorage
    console.log(this.selectItem);
    this.router.navigate(['/page-item-detail', item.detailId]); // 导航到详情页，并传递选定的项目ID作为参数
  console.log(this.router.navigate)
  }

  showContent(content: string) {
    this.currentContent = content;
    this.getData();
  }

  async openChatPanel() {
    if (this.chatPanelOpen) {
      const modal = await this.modalController.getTop();
      if (modal) {
        modal.dismiss();
      }
      this.chatPanelOpen = false;
    } else {
      const modal = await this.modalController.create({
        component: PageChatPanelComponent,
        cssClass: 'chat-panel-modal',
        componentProps: {}
      });
      modal.style.height = '40vh'; // 设置弹框高度为50%
      modal.style.margin = '40vh 0 0 40vw'; // 设置弹框高度为50%

      await modal.present();
      this.chatPanelOpen = true;

    }

  }
}
