import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import {
  AlertController,
  ToastController,
} from '../../../modules/ionic-standalone.modules';
import { AiChatService } from '../../../services/aichart.service';
import { ConnectTaskService } from '../../../services/connectTask.service';
import { MessageService } from '../../../services/message.service';
import * as Parse from 'parse';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
  selector: 'app-call-modal',
  templateUrl: './call-modal.component.html',
  styleUrls: ['./call-modal.component.scss'],
  standalone: true,
  imports: [],
})
export class CallModalComponent implements OnInit {
  @Input('profile') profile?: Parse.Object;
  @Input('userStatus') userStatus: string = 'OFFLINE';
  room?: Parse.Object;
  uid?: string; //主播频道&uid
  currentUser?: Parse.Object = Parse.User.current(); //当前登录用户
  iscall: boolean = false;
  isLiveing: boolean = false; // 是否在直播通话中
  private ngUnsubscribe = new Subject<void>(); // 用于取消订阅
  constructor(
    private router: Router,
    private toastController: ToastController,
    private alertController: AlertController,
    private connectTask: ConnectTaskService,
    private msgSer: MessageService,
    private aiChatServ: AiChatService
  ) {
    this.msgSer.event$
    .pipe(takeUntil(this.ngUnsubscribe)) // 使用 takeUntil 取消订阅
    .subscribe((data) => {
      this.inviteCallback(data);
    });
  }

  ngOnInit() {
    this.uid = this.profile?.get('user').id;
    this.refresh();
  }
  ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
    
    if (!this.isLiveing && this.uid !== this.currentUser?.id) {
      console.log('断开连接');
      this.msgSer?.unsubscribeMessage(this.uid!);
    }
  }
  refresh() {
    this.getRoom();
  }

  async getRoom() {
    let query = new Parse.Query('Room');
    query.equalTo('profile', this.profile?.id);
    query.notEqualTo('isDeleted', true);
    this.room = await query.first();
    // console.log(this.room);
    if (!this.room?.id) return;
    this.userStatus = await this.connectTask.getState(
      this.profile?.get('user').id,
      this.profile?.get('user').id
    );
    if (this.profile?.get('isCheck') && this.userStatus == 'ONLINE') {
      this.userStatus = 'REFUSE';
    }
  }
  async toLiveContact() {
    if (this.userStatus == 'REFUSE') {
      const toast = await this.toastController.create({
        message: '对方已设置免打扰状态',
        color: 'warning',
        duration: 1500,
      });
      toast.present();
      return;
    }
    this.userStatus = await this.connectTask.getState(this.uid!, this.uid!);
    if (this.userStatus !== 'ONLINE') {
      const toast = await this.toastController.create({
        message: '对方不在线或忙线中',
        color: 'warning',
        duration: 1500,
      });
      toast.present();
      return;
    }
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '邀请通话',
      backdropDismiss: false,
      message: '你将与对方发起私聊通话',
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: (blah) => {},
        },
        {
          text: '确定',
          cssClass: 'secondary',
          handler: () => {
            this.sendVideoCallInvite();
          },
        },
      ],
    });
    await alert.present();
  }
  timer: any; // 定时器
  inviteCallback(event: boolean) {
    console.log(event);
    if (event == undefined) return;
    this.timer && clearTimeout(this.timer);
    this.timer = setTimeout(async () => {
      this.iscall = false;
      const toast = await this.toastController.create({
        message: `对方${event ? '已接受' : '拒绝'}通话邀请`,
        color: event ? 'success' : 'warning',
        duration: 1500,
      });
      toast.present();
      if (event) {
        this.isLiveing = true;
        let path = location.pathname;
        if (path.indexOf('/live/link-room/') != -1) return;
        this.router.navigate(['live/link-room/' + this.room?.id]);
      }
    }, 100);
  }
  async sendVideoCallInvite() {
    let second = await this.aiChatServ.get_duration(
      this.room?.id!,
      this.currentUser?.id!
    );
    if (second < 120) {
      const toast = await this.toastController.create({
        message: '通话时长不足2分钟，请充值后再试通',
        color: 'warning',
        duration: 1500,
      });
      toast.present();
      return;
    }
    this.iscall = true;
    // this.router.navigate(['live/link-room/' + this.room?.id]);
    await this.msgSer.subscribeMessage(this.uid!, {
      message: true,
      presence: true,
    }); //进入对方主播频道发送聊天邀请
    this.msgSer.publishMessage('USERCALLINVITATION', this.uid!);
  }
  async onCloseCall() {
    this.timer && clearTimeout(this.timer);
    this.iscall = false;
    const toast = await this.toastController.create({
      message: '已取消视频通话邀请',
      color: 'warning',
      duration: 1500,
    });
    toast.present();
    this.msgSer.publishMessage('CLOASEINVITATION', this.uid!);
  }
}
