import { CommonModule, DatePipe } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AiChatService } from '../../../services/aichart.service';
// import { NavComponent } from '../../../app/components/nav/nav.component';
import {
  AlertController,
  ionicStandaloneModules,
  ToastController,
} from '../../ionic-standalone.modules';
import { ImagePreviewComponent } from '../../../app/components/image-preview/image-preview.component';
import * as Parse from 'parse';
import { InfiniteScrollCustomEvent } from '@ionic/core';
import { DeviceService } from '../../../services/device.service';

@Component({
  selector: 'app-space',
  templateUrl: './space.component.html',
  styleUrls: ['./space.component.scss'],
  standalone: true,
  imports: [...ionicStandaloneModules, CommonModule, ImagePreviewComponent],
  providers: [DatePipe],
})
export class SpaceComponent implements OnInit {
  active: string = 'all';
  list: Array<any> = [];
  currenImg: string = '';
  @ViewChild('preview') preview!: ImagePreviewComponent;
  user:Parse.Object = Parse.User.current()!;
  disbable:boolean = true

  constructor(
    private activateRoute: ActivatedRoute,
    private router: Router,
    private aiServ: AiChatService,
    private alertController: AlertController,
    private toastController: ToastController,
    public deviceSer: DeviceService
  ) {}

  ngOnInit() {
    this.activateRoute.paramMap.subscribe(async (params) => {
      this.getList();
    });
  }
  async getList() {
    let arr = await this.aiServ.getPost(
      10,
      this.list.length,
      this.active == 'self' ? Parse.User.current()?.id : undefined
    );
    console.log(arr);
    this.list.push(...arr);
    if(arr.length == 0){
      const toast = await this.toastController.create({
        message: '已加载全部',
        color: 'warning',
        duration: 1000,
      });
      toast.present();
    }
    return arr;
  }
  segmentChanged(e: any) {
    let { value } = e.detail;
    this.active = value;
    this.list = [];
    this.disbable = true;
    this.getList();
  }
  onShowImg(url: string) {
    this.currenImg = url;
    this.preview.show = 'inline-flex';
  }
  async onPostLog(item: any, index: number) {
    console.log(item);
    let query = new Parse.Query('DramaPostLog');
    query.equalTo('dramaPost', item.objectId);
    query.equalTo('user', Parse.User.current());
    query.notEqualTo('isDeleted', true);
    let r = await query.first();
    if (!r?.id) {
      let obj = Parse.Object.extend('DramaPostLog');
      r = new obj();
      r?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.aiServ.company,
      });
      r?.set('dramaPost', {
        __type: 'Pointer',
        className: 'DramaPost',
        objectId: item.objectId,
      });
      r?.set('user', Parse.User.current()?.toPointer());
    }
    r?.set('isVerify', true);
    r?.set('type', 'like');
    await r?.save();
    const toast = await this.toastController.create({
      message: `${item.isPostLog ? '已取消点赞' : '已点赞'}`,
      color: 'success',
      duration: 1000,
    });
    toast.present();
    this.list[index].postCount = this.list[index].isPostLog
      ? --this.list[index].postCount
      : ++this.list[index].postCount;
    this.list[index].isPostLog = !this.list[index].isPostLog;
  }
  async onIonInfinite(ev: any) {
    let result = await this.getList();
    if (result.length == 0) {
      this.disbable = false;
      (ev as InfiniteScrollCustomEvent).target.disabled = true;
    }
    setTimeout(() => {
      (ev as InfiniteScrollCustomEvent).target.complete();
    }, 500);
  }
  toUrl(url: string) {
    this.router.navigate([url]);
  }
  async delPost(id:string,index:number){
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '提示',
      message: '确定删除该种花吗？',
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: (data) => {},
        },
        {
          text: '确定',
          cssClass: 'secondary',
          handler:async (data) => {
            let query = new Parse.Query('DramaPost');
            let post = await query.get(id);
            post.set('isDeleted',true)
            await post.save();
            const toast = await this.toastController.create({
              message: '删除成功',
              color: 'success',
              duration: 1000,
            });
            toast.present();
            this.list.splice(index,1)
          },
        },
      ],
    });
    await alert.present();
  }
  async onReport() {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '举报',
      message: '请填写你需要举报的内容',
      inputs: [
        {
          name: 'report',
          type: 'textarea',
          placeholder: '举报内容',
        },
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: (data) => {},
        },
        {
          text: '确定',
          cssClass: 'secondary',
          handler:async (data) => {
            let report = data.report;
            console.log(report);
            const toast = await this.toastController.create({
              message: '感谢您的反馈',
              color: 'success',
              duration: 1000,
            });
            toast.present();
          },
        },
      ],
    });
    await alert.present();
  }
}
