import { Component, OnInit, ViewChild, ElementRef, Renderer2 } from '@angular/core';
import { Router } from '@angular/router';
import * as Parse from "parse";
@Component({
  selector: 'app-community',
  templateUrl: './community.component.html',
  styleUrls: ['./community.component.scss'],
})
export class CommunityComponent implements OnInit {
  scienceList: Array<Parse.Object> = [];
  recommendList: Array<Parse.Object> = [];
  attentionList: Array<Parse.Object> = [];
  startX: number = 0;
  currentX: number = 0;
  isDragging: boolean = false;
  minTranslateX: number = 0; // 最小平移距离
  maxTranslateX: number = 0;
  @ViewChild('carousel', { static: true }) carousel!: ElementRef;
  cate: string = 'all';
  constructor(private router: Router, private renderer: Renderer2) {
    this.initPage();
  }
  ngOnInit(): void {
    this.renderer.listen(this.carousel.nativeElement, 'touchstart', this.onTouchStart.bind(this));
    this.renderer.listen(this.carousel.nativeElement, 'touchmove', this.onTouchMove.bind(this));
    this.renderer.listen(this.carousel.nativeElement, 'touchend', this.onTouchEnd.bind(this));
  }
  async initPage() {
    this.scienceList = await this.getScienceData();
    this.recommendList = await this.getRecommendData();
    this.attentionList = await this.getAttentionData();
    // 设置最大最小平移距离
    this.maxTranslateX = this.carousel.nativeElement.offsetWidth - window.innerWidth;
  }
  async getScienceData() {
    let query = new Parse.Query("HrmScience");
    let list = await query.find();
    return list;
  }
  async getRecommendData() {
    let query = new Parse.Query("HrmRecommend");
    let list = await query.find();
    return list;
  }
  async getAttentionData() {
    let query = new Parse.Query("HrmAttention");
    let list = await query.find();
    return list;
  }
  goScienceDetail(science: Parse.Object) {
    this.router.navigate(["/lesson/community/scienceDetail"], {
      queryParams: science
    });
  }
  goRecommendDetail(recommend: Parse.Object) {
    this.router.navigate(["/lesson/community/recommendDetail"], {
      queryParams: recommend
    });
  }
  goAttentionDetail(attention: Parse.Object) {
    this.router.navigate(["/lesson/community/attentionDetail"], {
      queryParams: attention
    });
  }
  onTouchStart(event: TouchEvent): void {
    this.startX = event.touches[0].clientX;
    this.isDragging = true;
  }
  onTouchMove(event: TouchEvent): void {
    if (this.carousel && this.isDragging) {
        const touch = event.touches[0];
        const deltaX = touch.clientX - this.startX;
        this.currentX = this.currentX + deltaX;
        // 限制平移范围在最大最小值之间
        this.currentX = Math.max(this.minTranslateX, Math.min(this.maxTranslateX, this.currentX));

        this.renderer.setStyle(this.carousel.nativeElement, 'transform', `translateX(${-this.currentX}px)`);
        this.startX = touch.clientX;
    }
}
  onTouchEnd(): void {
    this.isDragging = false;
  }
}
