import { CommonModule, DatePipe } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { NavComponent } from '../../../app/components/nav/nav.component';
import { AiChatService } from '../../../services/aichart.service';
import {
  ionicStandaloneModules,
  LoadingController,
  ToastController,
} from '../../ionic-standalone.modules';
import * as Parse from 'parse';
import { InfiniteScrollCustomEvent } from '@ionic/core';
import { Router } from '@angular/router';
import { MessageService } from '../../../services/message.service';

@Component({
  selector: 'app-notice-log',
  templateUrl: './notice-log.component.html',
  styleUrls: ['./notice-log.component.scss'],
  standalone: true,
  imports: [...ionicStandaloneModules, NavComponent, CommonModule],
  providers: [DatePipe],
})
export class NoticeLogComponent implements OnInit {
  list: Array<any> = [];
  user: Parse.Object = Parse.User.current()!;

  constructor(
    private toastController: ToastController,
    private loadingCtrl: LoadingController,
    private router: Router,
    private msgSer: MessageService,
    private aiSer: AiChatService
  ) {}

  ngOnInit() {
    this.getLog();
  }
  async getLog() {
    let uid: any = Parse.User.current()?.id;
    let r = await this.aiSer.getSysNotice(uid, 20, this.list.length);
    this.list.push(...r?.data);
    return r?.data;
  }
  async onIonInfinite(ev: any) {
    let uid: any = Parse.User.current()?.id;
    let result = await this.aiSer.getSysNotice(uid, 20, this.list.length);
    if (result.data.length == 0) {
      (ev as InfiniteScrollCustomEvent).target.disabled = true;
    }
    setTimeout(() => {
      (ev as InfiniteScrollCustomEvent).target.complete();
    }, 500);
  }
  toUrl(url: string) {
    this.router.navigate([url]);
  }
  async onApply(id: string, index: number, pass: boolean) {
    let isAnthor = this.aiSer.identity
    const loading = await this.loadingCtrl.create({
      message: '加载中',
    });
    loading.present();
    this.list[index].status = pass ? '200' : '101';
    let query = new Parse.Query('Friends');
    let res = await query.get(id);
    res.set('isPass', pass);
    if(pass){
      let channel = isAnthor ? `${this.user.id}-${this.list[index].tuid}` : `${this.list[index].tuid}-${this.user.id}`
      res.set('channel', channel)
      this.msgSer.subscribeMessage(channel); //同意好友邀请并且订阅频道
    }
    await res.save();
    loading.dismiss();
    const toast = await this.toastController.create({
      message: `已${pass ? '通过' : '拒绝'}申请`,
      color: 'success',
      duration: 1000,
    });
    toast.present();
  }
}
